@cloudflare/realtimekit 0.0.3 → 0.5.0-staging.101

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.
@@ -0,0 +1,29 @@
1
+ "use strict";var Rc,PE=new Uint8Array(16);function AE(){if(!Rc&&(Rc=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!Rc))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Rc(PE)}var ME=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function Pp(t){return typeof t=="string"&&ME.test(t)}var Rt=[];for(var ru=0;ru<256;++ru)Rt.push((ru+256).toString(16).substr(1));function OE(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=(Rt[t[e+0]]+Rt[t[e+1]]+Rt[t[e+2]]+Rt[t[e+3]]+"-"+Rt[t[e+4]]+Rt[t[e+5]]+"-"+Rt[t[e+6]]+Rt[t[e+7]]+"-"+Rt[t[e+8]]+Rt[t[e+9]]+"-"+Rt[t[e+10]]+Rt[t[e+11]]+Rt[t[e+12]]+Rt[t[e+13]]+Rt[t[e+14]]+Rt[t[e+15]]).toLowerCase();if(!Pp(n))throw TypeError("Stringified UUID is invalid");return n}function Ia(t,e,n){t=t||{};var i=t.random||(t.rng||AE)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){n=n||0;for(var s=0;s<16;++s)e[n+s]=i[s];return e}return OE(i)}const DE={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},iv={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},tt={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},Ft={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},zi={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};class j{static getFirstMatch(e,n){const i=n.match(e);return i&&i.length>0&&i[1]||""}static getSecondMatch(e,n){const i=n.match(e);return i&&i.length>1&&i[2]||""}static matchAndReturnConst(e,n,i){if(e.test(n))return i}static getWindowsVersionName(e){switch(e){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}}static getMacOSVersionName(e){const n=e.split(".").splice(0,2).map(i=>parseInt(i,10)||0);if(n.push(0),n[0]===10)switch(n[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}}static getAndroidVersionName(e){const n=e.split(".").splice(0,2).map(i=>parseInt(i,10)||0);if(n.push(0),!(n[0]===1&&n[1]<5)){if(n[0]===1&&n[1]<6)return"Cupcake";if(n[0]===1&&n[1]>=6)return"Donut";if(n[0]===2&&n[1]<2)return"Eclair";if(n[0]===2&&n[1]===2)return"Froyo";if(n[0]===2&&n[1]>2)return"Gingerbread";if(n[0]===3)return"Honeycomb";if(n[0]===4&&n[1]<1)return"Ice Cream Sandwich";if(n[0]===4&&n[1]<4)return"Jelly Bean";if(n[0]===4&&n[1]>=4)return"KitKat";if(n[0]===5)return"Lollipop";if(n[0]===6)return"Marshmallow";if(n[0]===7)return"Nougat";if(n[0]===8)return"Oreo";if(n[0]===9)return"Pie"}}static getVersionPrecision(e){return e.split(".").length}static compareVersions(e,n,i=!1){const s=j.getVersionPrecision(e),r=j.getVersionPrecision(n);let a=Math.max(s,r),c=0;const d=j.map([e,n],h=>{const u=a-j.getVersionPrecision(h),g=h+new Array(u+1).join(".0");return j.map(g.split("."),E=>new Array(20-E.length).join("0")+E).reverse()});for(i&&(c=a-Math.min(s,r)),a-=1;a>=c;){if(d[0][a]>d[1][a])return 1;if(d[0][a]===d[1][a]){if(a===c)return 0;a-=1}else if(d[0][a]<d[1][a])return-1}}static map(e,n){const i=[];let s;if(Array.prototype.map)return Array.prototype.map.call(e,n);for(s=0;s<e.length;s+=1)i.push(n(e[s]));return i}static find(e,n){let i,s;if(Array.prototype.find)return Array.prototype.find.call(e,n);for(i=0,s=e.length;i<s;i+=1){const r=e[i];if(n(r,i))return r}}static assign(e,...n){const i=e;let s,r;if(Object.assign)return Object.assign(e,...n);for(s=0,r=n.length;s<r;s+=1){const a=n[s];typeof a=="object"&&a!==null&&Object.keys(a).forEach(d=>{i[d]=a[d]})}return e}static getBrowserAlias(e){return DE[e]}static getBrowserTypeByAlias(e){return iv[e]||""}}const Ce=/version\/(\d+(\.?_?\d+)+)/i,NE=[{test:[/googlebot/i],describe(t){const e={name:"Googlebot"},n=j.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,t)||j.getFirstMatch(Ce,t);return n&&(e.version=n),e}},{test:[/opera/i],describe(t){const e={name:"Opera"},n=j.getFirstMatch(Ce,t)||j.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/opr\/|opios/i],describe(t){const e={name:"Opera"},n=j.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,t)||j.getFirstMatch(Ce,t);return n&&(e.version=n),e}},{test:[/SamsungBrowser/i],describe(t){const e={name:"Samsung Internet for Android"},n=j.getFirstMatch(Ce,t)||j.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/Whale/i],describe(t){const e={name:"NAVER Whale Browser"},n=j.getFirstMatch(Ce,t)||j.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/MZBrowser/i],describe(t){const e={name:"MZ Browser"},n=j.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,t)||j.getFirstMatch(Ce,t);return n&&(e.version=n),e}},{test:[/focus/i],describe(t){const e={name:"Focus"},n=j.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,t)||j.getFirstMatch(Ce,t);return n&&(e.version=n),e}},{test:[/swing/i],describe(t){const e={name:"Swing"},n=j.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,t)||j.getFirstMatch(Ce,t);return n&&(e.version=n),e}},{test:[/coast/i],describe(t){const e={name:"Opera Coast"},n=j.getFirstMatch(Ce,t)||j.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(t){const e={name:"Opera Touch"},n=j.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,t)||j.getFirstMatch(Ce,t);return n&&(e.version=n),e}},{test:[/yabrowser/i],describe(t){const e={name:"Yandex Browser"},n=j.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,t)||j.getFirstMatch(Ce,t);return n&&(e.version=n),e}},{test:[/ucbrowser/i],describe(t){const e={name:"UC Browser"},n=j.getFirstMatch(Ce,t)||j.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/Maxthon|mxios/i],describe(t){const e={name:"Maxthon"},n=j.getFirstMatch(Ce,t)||j.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/epiphany/i],describe(t){const e={name:"Epiphany"},n=j.getFirstMatch(Ce,t)||j.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/puffin/i],describe(t){const e={name:"Puffin"},n=j.getFirstMatch(Ce,t)||j.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/sleipnir/i],describe(t){const e={name:"Sleipnir"},n=j.getFirstMatch(Ce,t)||j.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/k-meleon/i],describe(t){const e={name:"K-Meleon"},n=j.getFirstMatch(Ce,t)||j.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/micromessenger/i],describe(t){const e={name:"WeChat"},n=j.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,t)||j.getFirstMatch(Ce,t);return n&&(e.version=n),e}},{test:[/qqbrowser/i],describe(t){const e={name:/qqbrowserlite/i.test(t)?"QQ Browser Lite":"QQ Browser"},n=j.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,t)||j.getFirstMatch(Ce,t);return n&&(e.version=n),e}},{test:[/msie|trident/i],describe(t){const e={name:"Internet Explorer"},n=j.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/\sedg\//i],describe(t){const e={name:"Microsoft Edge"},n=j.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/edg([ea]|ios)/i],describe(t){const e={name:"Microsoft Edge"},n=j.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/vivaldi/i],describe(t){const e={name:"Vivaldi"},n=j.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/seamonkey/i],describe(t){const e={name:"SeaMonkey"},n=j.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/sailfish/i],describe(t){const e={name:"Sailfish"},n=j.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,t);return n&&(e.version=n),e}},{test:[/silk/i],describe(t){const e={name:"Amazon Silk"},n=j.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/phantom/i],describe(t){const e={name:"PhantomJS"},n=j.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/slimerjs/i],describe(t){const e={name:"SlimerJS"},n=j.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(t){const e={name:"BlackBerry"},n=j.getFirstMatch(Ce,t)||j.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/(web|hpw)[o0]s/i],describe(t){const e={name:"WebOS Browser"},n=j.getFirstMatch(Ce,t)||j.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/bada/i],describe(t){const e={name:"Bada"},n=j.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/tizen/i],describe(t){const e={name:"Tizen"},n=j.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,t)||j.getFirstMatch(Ce,t);return n&&(e.version=n),e}},{test:[/qupzilla/i],describe(t){const e={name:"QupZilla"},n=j.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,t)||j.getFirstMatch(Ce,t);return n&&(e.version=n),e}},{test:[/firefox|iceweasel|fxios/i],describe(t){const e={name:"Firefox"},n=j.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/electron/i],describe(t){const e={name:"Electron"},n=j.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/MiuiBrowser/i],describe(t){const e={name:"Miui"},n=j.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/chromium/i],describe(t){const e={name:"Chromium"},n=j.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,t)||j.getFirstMatch(Ce,t);return n&&(e.version=n),e}},{test:[/chrome|crios|crmo/i],describe(t){const e={name:"Chrome"},n=j.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/GSA/i],describe(t){const e={name:"Google Search"},n=j.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test(t){const e=!t.test(/like android/i),n=t.test(/android/i);return e&&n},describe(t){const e={name:"Android Browser"},n=j.getFirstMatch(Ce,t);return n&&(e.version=n),e}},{test:[/playstation 4/i],describe(t){const e={name:"PlayStation 4"},n=j.getFirstMatch(Ce,t);return n&&(e.version=n),e}},{test:[/safari|applewebkit/i],describe(t){const e={name:"Safari"},n=j.getFirstMatch(Ce,t);return n&&(e.version=n),e}},{test:[/.*/i],describe(t){const e=/^(.*)\/(.*) /,n=/^(.*)\/(.*)[ \t]\((.*)/,s=t.search("\\(")!==-1?n:e;return{name:j.getFirstMatch(s,t),version:j.getSecondMatch(s,t)}}}];var LE=[{test:[/Roku\/DVP/],describe(t){const e=j.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,t);return{name:Ft.Roku,version:e}}},{test:[/windows phone/i],describe(t){const e=j.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,t);return{name:Ft.WindowsPhone,version:e}}},{test:[/windows /i],describe(t){const e=j.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,t),n=j.getWindowsVersionName(e);return{name:Ft.Windows,version:e,versionName:n}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(t){const e={name:Ft.iOS},n=j.getSecondMatch(/(Version\/)(\d[\d.]+)/,t);return n&&(e.version=n),e}},{test:[/macintosh/i],describe(t){const e=j.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,t).replace(/[_\s]/g,"."),n=j.getMacOSVersionName(e),i={name:Ft.MacOS,version:e};return n&&(i.versionName=n),i}},{test:[/(ipod|iphone|ipad)/i],describe(t){const e=j.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,t).replace(/[_\s]/g,".");return{name:Ft.iOS,version:e}}},{test(t){const e=!t.test(/like android/i),n=t.test(/android/i);return e&&n},describe(t){const e=j.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,t),n=j.getAndroidVersionName(e),i={name:Ft.Android,version:e};return n&&(i.versionName=n),i}},{test:[/(web|hpw)[o0]s/i],describe(t){const e=j.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,t),n={name:Ft.WebOS};return e&&e.length&&(n.version=e),n}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(t){const e=j.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,t)||j.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,t)||j.getFirstMatch(/\bbb(\d+)/i,t);return{name:Ft.BlackBerry,version:e}}},{test:[/bada/i],describe(t){const e=j.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,t);return{name:Ft.Bada,version:e}}},{test:[/tizen/i],describe(t){const e=j.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,t);return{name:Ft.Tizen,version:e}}},{test:[/linux/i],describe(){return{name:Ft.Linux}}},{test:[/CrOS/],describe(){return{name:Ft.ChromeOS}}},{test:[/PlayStation 4/],describe(t){const e=j.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,t);return{name:Ft.PlayStation4,version:e}}}],xE=[{test:[/googlebot/i],describe(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe(t){const e=j.getFirstMatch(/(can-l01)/i,t)&&"Nova",n={type:tt.mobile,vendor:"Huawei"};return e&&(n.model=e),n}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe(){return{type:tt.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe(){return{type:tt.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(){return{type:tt.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe(){return{type:tt.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe(){return{type:tt.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe(){return{type:tt.tablet}}},{test(t){const e=t.test(/ipod|iphone/i),n=t.test(/like (ipod|iphone)/i);return e&&!n},describe(t){const e=j.getFirstMatch(/(ipod|iphone)/i,t);return{type:tt.mobile,vendor:"Apple",model:e}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe(){return{type:tt.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe(){return{type:tt.mobile}}},{test(t){return t.getBrowserName(!0)==="blackberry"},describe(){return{type:tt.mobile,vendor:"BlackBerry"}}},{test(t){return t.getBrowserName(!0)==="bada"},describe(){return{type:tt.mobile}}},{test(t){return t.getBrowserName()==="windows phone"},describe(){return{type:tt.mobile,vendor:"Microsoft"}}},{test(t){const e=Number(String(t.getOSVersion()).split(".")[0]);return t.getOSName(!0)==="android"&&e>=3},describe(){return{type:tt.tablet}}},{test(t){return t.getOSName(!0)==="android"},describe(){return{type:tt.mobile}}},{test(t){return t.getOSName(!0)==="macos"},describe(){return{type:tt.desktop,vendor:"Apple"}}},{test(t){return t.getOSName(!0)==="windows"},describe(){return{type:tt.desktop}}},{test(t){return t.getOSName(!0)==="linux"},describe(){return{type:tt.desktop}}},{test(t){return t.getOSName(!0)==="playstation 4"},describe(){return{type:tt.tv}}},{test(t){return t.getOSName(!0)==="roku"},describe(){return{type:tt.tv}}}],VE=[{test(t){return t.getBrowserName(!0)==="microsoft edge"},describe(t){if(/\sedg\//i.test(t))return{name:zi.Blink};const n=j.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,t);return{name:zi.EdgeHTML,version:n}}},{test:[/trident/i],describe(t){const e={name:zi.Trident},n=j.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test(t){return t.test(/presto/i)},describe(t){const e={name:zi.Presto},n=j.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test(t){const e=t.test(/gecko/i),n=t.test(/like gecko/i);return e&&!n},describe(t){const e={name:zi.Gecko},n=j.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:zi.Blink}}},{test:[/(apple)?webkit/i],describe(t){const e={name:zi.WebKit},n=j.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}}];class Sm{constructor(e,n=!1){if(e==null||e==="")throw new Error("UserAgent parameter can't be empty");this._ua=e,this.parsedResult={},n!==!0&&this.parse()}getUA(){return this._ua}test(e){return e.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const e=j.find(NE,n=>{if(typeof n.test=="function")return n.test(this);if(n.test instanceof Array)return n.test.some(i=>this.test(i));throw new Error("Browser's test function is not valid")});return e&&(this.parsedResult.browser=e.describe(this.getUA())),this.parsedResult.browser}getBrowser(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()}getBrowserName(e){return e?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""}getBrowserVersion(){return this.getBrowser().version}getOS(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()}parseOS(){this.parsedResult.os={};const e=j.find(LE,n=>{if(typeof n.test=="function")return n.test(this);if(n.test instanceof Array)return n.test.some(i=>this.test(i));throw new Error("Browser's test function is not valid")});return e&&(this.parsedResult.os=e.describe(this.getUA())),this.parsedResult.os}getOSName(e){const{name:n}=this.getOS();return e?String(n).toLowerCase()||"":n||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(e=!1){const{type:n}=this.getPlatform();return e?String(n).toLowerCase()||"":n||""}parsePlatform(){this.parsedResult.platform={};const e=j.find(xE,n=>{if(typeof n.test=="function")return n.test(this);if(n.test instanceof Array)return n.test.some(i=>this.test(i));throw new Error("Browser's test function is not valid")});return e&&(this.parsedResult.platform=e.describe(this.getUA())),this.parsedResult.platform}getEngine(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()}getEngineName(e){return e?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""}parseEngine(){this.parsedResult.engine={};const e=j.find(VE,n=>{if(typeof n.test=="function")return n.test(this);if(n.test instanceof Array)return n.test.some(i=>this.test(i));throw new Error("Browser's test function is not valid")});return e&&(this.parsedResult.engine=e.describe(this.getUA())),this.parsedResult.engine}parse(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this}getResult(){return j.assign({},this.parsedResult)}satisfies(e){const n={};let i=0;const s={};let r=0;if(Object.keys(e).forEach(c=>{const d=e[c];typeof d=="string"?(s[c]=d,r+=1):typeof d=="object"&&(n[c]=d,i+=1)}),i>0){const c=Object.keys(n),d=j.find(c,u=>this.isOS(u));if(d){const u=this.satisfies(n[d]);if(u!==void 0)return u}const h=j.find(c,u=>this.isPlatform(u));if(h){const u=this.satisfies(n[h]);if(u!==void 0)return u}}if(r>0){const c=Object.keys(s),d=j.find(c,h=>this.isBrowser(h,!0));if(d!==void 0)return this.compareVersion(s[d])}}isBrowser(e,n=!1){const i=this.getBrowserName().toLowerCase();let s=e.toLowerCase();const r=j.getBrowserTypeByAlias(s);return n&&r&&(s=r.toLowerCase()),s===i}compareVersion(e){let n=[0],i=e,s=!1;const r=this.getBrowserVersion();if(typeof r=="string")return e[0]===">"||e[0]==="<"?(i=e.substr(1),e[1]==="="?(s=!0,i=e.substr(2)):n=[],e[0]===">"?n.push(1):n.push(-1)):e[0]==="="?i=e.substr(1):e[0]==="~"&&(s=!0,i=e.substr(1)),n.indexOf(j.compareVersions(r,i,s))>-1}isOS(e){return this.getOSName(!0)===String(e).toLowerCase()}isPlatform(e){return this.getPlatformType(!0)===String(e).toLowerCase()}isEngine(e){return this.getEngineName(!0)===String(e).toLowerCase()}is(e,n=!1){return this.isBrowser(e,n)||this.isOS(e)||this.isPlatform(e)}some(e=[]){return e.some(n=>this.is(n))}}/*!
2
+ * Bowser - a browser detector
3
+ * https://github.com/lancedikson/bowser
4
+ * MIT License | (c) Dustin Diaz 2012-2015
5
+ * MIT License | (c) Denis Demchenko 2015-2019
6
+ */class sv{static getParser(e,n=!1){if(typeof e!="string")throw new Error("UserAgent should be a string");return new Sm(e,n)}static parse(e){return new Sm(e).getResult()}static get BROWSER_MAP(){return iv}static get ENGINE_MAP(){return zi}static get OS_MAP(){return Ft}static get PLATFORMS_MAP(){return tt}}function Ap(t){let e=typeof t;if(e=="object"){if(Array.isArray(t))return"array";if(t===null)return"null"}return e}function UE(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}let bi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Cl=[];for(let t=0;t<bi.length;t++)Cl[bi[t].charCodeAt(0)]=t;Cl["-".charCodeAt(0)]=bi.indexOf("+");Cl["_".charCodeAt(0)]=bi.indexOf("/");function BE(t){let e=t.length*3/4;t[t.length-2]=="="?e-=2:t[t.length-1]=="="&&(e-=1);let n=new Uint8Array(e),i=0,s=0,r,a=0;for(let c=0;c<t.length;c++){if(r=Cl[t.charCodeAt(c)],r===void 0)switch(t[c]){case"=":s=0;case`
7
+ `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:a=r,s=1;break;case 1:n[i++]=a<<2|(r&48)>>4,a=r,s=2;break;case 2:n[i++]=(a&15)<<4|(r&60)>>2,a=r,s=3;break;case 3:n[i++]=(a&3)<<6|r,s=0;break}}if(s==1)throw Error("invalid base64 string.");return n.subarray(0,i)}function FE(t){let e="",n=0,i,s=0;for(let r=0;r<t.length;r++)switch(i=t[r],n){case 0:e+=bi[i>>2],s=(i&3)<<4,n=1;break;case 1:e+=bi[s|i>>4],s=(i&15)<<2,n=2;break;case 2:e+=bi[s|i>>6],e+=bi[i&63],n=0;break}return n&&(e+=bi[s],e+="=",n==1&&(e+="=")),e}var $d;(function(t){t.symbol=Symbol.for("protobuf-ts/unknown"),t.onRead=(n,i,s,r,a)=>{(e(i)?i[t.symbol]:i[t.symbol]=[]).push({no:s,wireType:r,data:a})},t.onWrite=(n,i,s)=>{for(let{no:r,wireType:a,data:c}of t.list(i))s.tag(r,a).raw(c)},t.list=(n,i)=>{if(e(n)){let s=n[t.symbol];return i?s.filter(r=>r.no==i):s}return[]},t.last=(n,i)=>t.list(n,i).slice(-1)[0];const e=n=>n&&Array.isArray(n[t.symbol])})($d||($d={}));var it;(function(t){t[t.Varint=0]="Varint",t[t.Bit64=1]="Bit64",t[t.LengthDelimited=2]="LengthDelimited",t[t.StartGroup=3]="StartGroup",t[t.EndGroup=4]="EndGroup",t[t.Bit32=5]="Bit32"})(it||(it={}));function jE(){let t=0,e=0;for(let i=0;i<28;i+=7){let s=this.buf[this.pos++];if(t|=(s&127)<<i,(s&128)==0)return this.assertBounds(),[t,e]}let n=this.buf[this.pos++];if(t|=(n&15)<<28,e=(n&112)>>4,(n&128)==0)return this.assertBounds(),[t,e];for(let i=3;i<=31;i+=7){let s=this.buf[this.pos++];if(e|=(s&127)<<i,(s&128)==0)return this.assertBounds(),[t,e]}throw new Error("invalid varint")}function au(t,e,n){for(let r=0;r<28;r=r+7){const a=t>>>r,c=!(a>>>7==0&&e==0),d=(c?a|128:a)&255;if(n.push(d),!c)return}const i=t>>>28&15|(e&7)<<4,s=e>>3!=0;if(n.push((s?i|128:i)&255),!!s){for(let r=3;r<31;r=r+7){const a=e>>>r,c=a>>>7!=0,d=(c?a|128:a)&255;if(n.push(d),!c)return}n.push(e>>>31&1)}}const od=(1<<16)*(1<<16);function rv(t){let e=t[0]=="-";e&&(t=t.slice(1));const n=1e6;let i=0,s=0;function r(a,c){const d=Number(t.slice(a,c));s*=n,i=i*n+d,i>=od&&(s=s+(i/od|0),i=i%od)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),[e,i,s]}function th(t,e){if(e>>>0<=2097151)return""+(od*e+(t>>>0));let n=t&16777215,i=(t>>>24|e<<8)>>>0&16777215,s=e>>16&65535,r=n+i*6777216+s*6710656,a=i+s*8147497,c=s*2,d=1e7;r>=d&&(a+=Math.floor(r/d),r%=d),a>=d&&(c+=Math.floor(a/d),a%=d);function h(u,g){let E=u?String(u):"";return g?"0000000".slice(E.length)+E:E}return h(c,0)+h(a,c)+h(r,1)}function Tm(t,e){if(t>=0){for(;t>127;)e.push(t&127|128),t=t>>>7;e.push(t)}else{for(let n=0;n<9;n++)e.push(t&127|128),t=t>>7;e.push(1)}}function WE(){let t=this.buf[this.pos++],e=t&127;if((t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<7,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<14,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<21,(t&128)==0)return this.assertBounds(),e;t=this.buf[this.pos++],e|=(t&15)<<28;for(let n=5;(t&128)!==0&&n<10;n++)t=this.buf[this.pos++];if((t&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}let Re;function HE(){const t=new DataView(new ArrayBuffer(8));Re=globalThis.BigInt!==void 0&&typeof t.getBigInt64=="function"&&typeof t.getBigUint64=="function"&&typeof t.setBigInt64=="function"&&typeof t.setBigUint64=="function"?{MIN:BigInt("-9223372036854775808"),MAX:BigInt("9223372036854775807"),UMIN:BigInt("0"),UMAX:BigInt("18446744073709551615"),C:BigInt,V:t}:void 0}HE();function av(t){if(!t)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const ov=/^-?[0-9]+$/,Jd=4294967296,Pc=2147483648;class cv{constructor(e,n){this.lo=e|0,this.hi=n|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let e=this.hi*Jd+(this.lo>>>0);if(!Number.isSafeInteger(e))throw new Error("cannot convert to safe number");return e}}class Dt extends cv{static from(e){if(Re)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=Re.C(e);case"number":if(e===0)return this.ZERO;e=Re.C(e);case"bigint":if(!e)return this.ZERO;if(e<Re.UMIN)throw new Error("signed value for ulong");if(e>Re.UMAX)throw new Error("ulong too large");return Re.V.setBigUint64(0,e,!0),new Dt(Re.V.getInt32(0,!0),Re.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!ov.test(e))throw new Error("string is no integer");let[n,i,s]=rv(e);if(n)throw new Error("signed value for ulong");return new Dt(i,s);case"number":if(e==0)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");if(e<0)throw new Error("signed value for ulong");return new Dt(e,e/Jd)}throw new Error("unknown value "+typeof e)}toString(){return Re?this.toBigInt().toString():th(this.lo,this.hi)}toBigInt(){return av(Re),Re.V.setInt32(0,this.lo,!0),Re.V.setInt32(4,this.hi,!0),Re.V.getBigUint64(0,!0)}}Dt.ZERO=new Dt(0,0);class xe extends cv{static from(e){if(Re)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=Re.C(e);case"number":if(e===0)return this.ZERO;e=Re.C(e);case"bigint":if(!e)return this.ZERO;if(e<Re.MIN)throw new Error("signed long too small");if(e>Re.MAX)throw new Error("signed long too large");return Re.V.setBigInt64(0,e,!0),new xe(Re.V.getInt32(0,!0),Re.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!ov.test(e))throw new Error("string is no integer");let[n,i,s]=rv(e);if(n){if(s>Pc||s==Pc&&i!=0)throw new Error("signed long too small")}else if(s>=Pc)throw new Error("signed long too large");let r=new xe(i,s);return n?r.negate():r;case"number":if(e==0)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");return e>0?new xe(e,e/Jd):new xe(-e,-e/Jd).negate()}throw new Error("unknown value "+typeof e)}isNegative(){return(this.hi&Pc)!==0}negate(){let e=~this.hi,n=this.lo;return n?n=~n+1:e+=1,new xe(n,e)}toString(){if(Re)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return"-"+th(e.lo,e.hi)}return th(this.lo,this.hi)}toBigInt(){return av(Re),Re.V.setInt32(0,this.lo,!0),Re.V.setInt32(4,this.hi,!0),Re.V.getBigInt64(0,!0)}}xe.ZERO=new xe(0,0);const bm={readUnknownField:!0,readerFactory:t=>new GE(t)};function qE(t){return t?Object.assign(Object.assign({},bm),t):bm}class GE{constructor(e,n){this.varint64=jE,this.uint32=WE,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=n!=null?n:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let e=this.uint32(),n=e>>>3,i=e&7;if(n<=0||i<0||i>5)throw new Error("illegal tag: field no "+n+" wire type "+i);return[n,i]}skip(e){let n=this.pos;switch(e){case it.Varint:for(;this.buf[this.pos++]&128;);break;case it.Bit64:this.pos+=4;case it.Bit32:this.pos+=4;break;case it.LengthDelimited:let i=this.uint32();this.pos+=i;break;case it.StartGroup:let s;for(;(s=this.tag()[1])!==it.EndGroup;)this.skip(s);break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return new xe(...this.varint64())}uint64(){return new Dt(...this.varint64())}sint64(){let[e,n]=this.varint64(),i=-(e&1);return e=(e>>>1|(n&1)<<31)^i,n=n>>>1^i,new xe(e,n)}bool(){let[e,n]=this.varint64();return e!==0||n!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new Dt(this.sfixed32(),this.sfixed32())}sfixed64(){return new xe(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),n=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(n,n+e)}string(){return this.textDecoder.decode(this.bytes())}}function Ee(t,e){if(!t)throw new Error(e)}const $E=34028234663852886e22,JE=-34028234663852886e22,KE=4294967295,zE=2147483647,YE=-2147483648;function Ho(t){if(typeof t!="number")throw new Error("invalid int 32: "+typeof t);if(!Number.isInteger(t)||t>zE||t<YE)throw new Error("invalid int 32: "+t)}function Kd(t){if(typeof t!="number")throw new Error("invalid uint 32: "+typeof t);if(!Number.isInteger(t)||t>KE||t<0)throw new Error("invalid uint 32: "+t)}function Mp(t){if(typeof t!="number")throw new Error("invalid float 32: "+typeof t);if(!!Number.isFinite(t)&&(t>$E||t<JE))throw new Error("invalid float 32: "+t)}const km={writeUnknownFields:!0,writerFactory:()=>new XE};function QE(t){return t?Object.assign(Object.assign({},km),t):km}class XE{constructor(e){this.stack=[],this.textEncoder=e!=null?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let s=0;s<this.chunks.length;s++)e+=this.chunks[s].length;let n=new Uint8Array(e),i=0;for(let s=0;s<this.chunks.length;s++)n.set(this.chunks[s],i),i+=this.chunks[s].length;return this.chunks=[],n}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),n=this.stack.pop();if(!n)throw new Error("invalid state, fork stack empty");return this.chunks=n.chunks,this.buf=n.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,n){return this.uint32((e<<3|n)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Kd(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Ho(e),Tm(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let n=this.textEncoder.encode(e);return this.uint32(n.byteLength),this.raw(n)}float(e){Mp(e);let n=new Uint8Array(4);return new DataView(n.buffer).setFloat32(0,e,!0),this.raw(n)}double(e){let n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,e,!0),this.raw(n)}fixed32(e){Kd(e);let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,e,!0),this.raw(n)}sfixed32(e){Ho(e);let n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,e,!0),this.raw(n)}sint32(e){return Ho(e),e=(e<<1^e>>31)>>>0,Tm(e,this.buf),this}sfixed64(e){let n=new Uint8Array(8),i=new DataView(n.buffer),s=xe.from(e);return i.setInt32(0,s.lo,!0),i.setInt32(4,s.hi,!0),this.raw(n)}fixed64(e){let n=new Uint8Array(8),i=new DataView(n.buffer),s=Dt.from(e);return i.setInt32(0,s.lo,!0),i.setInt32(4,s.hi,!0),this.raw(n)}int64(e){let n=xe.from(e);return au(n.lo,n.hi,this.buf),this}sint64(e){let n=xe.from(e),i=n.hi>>31,s=n.lo<<1^i,r=(n.hi<<1|n.lo>>>31)^i;return au(s,r,this.buf),this}uint64(e){let n=Dt.from(e);return au(n.lo,n.hi,this.buf),this}}const wm={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},_m={ignoreUnknownFields:!1};function ZE(t){return t?Object.assign(Object.assign({},_m),t):_m}function eS(t){return t?Object.assign(Object.assign({},wm),t):wm}const dv=Symbol.for("protobuf-ts/message-type");function Im(t){let e=!1;const n=[];for(let i=0;i<t.length;i++){let s=t.charAt(i);s=="_"?e=!0:/\d/.test(s)?(n.push(s),e=!0):e?(n.push(s.toUpperCase()),e=!1):i==0?n.push(s.toLowerCase()):n.push(s)}return n.join("")}var B;(function(t){t[t.DOUBLE=1]="DOUBLE",t[t.FLOAT=2]="FLOAT",t[t.INT64=3]="INT64",t[t.UINT64=4]="UINT64",t[t.INT32=5]="INT32",t[t.FIXED64=6]="FIXED64",t[t.FIXED32=7]="FIXED32",t[t.BOOL=8]="BOOL",t[t.STRING=9]="STRING",t[t.BYTES=12]="BYTES",t[t.UINT32=13]="UINT32",t[t.SFIXED32=15]="SFIXED32",t[t.SFIXED64=16]="SFIXED64",t[t.SINT32=17]="SINT32",t[t.SINT64=18]="SINT64"})(B||(B={}));var di;(function(t){t[t.BIGINT=0]="BIGINT",t[t.STRING=1]="STRING",t[t.NUMBER=2]="NUMBER"})(di||(di={}));var zd;(function(t){t[t.NO=0]="NO",t[t.PACKED=1]="PACKED",t[t.UNPACKED=2]="UNPACKED"})(zd||(zd={}));function tS(t){var e,n,i,s;return t.localName=(e=t.localName)!==null&&e!==void 0?e:Im(t.name),t.jsonName=(n=t.jsonName)!==null&&n!==void 0?n:Im(t.name),t.repeat=(i=t.repeat)!==null&&i!==void 0?i:zd.NO,t.opt=(s=t.opt)!==null&&s!==void 0?s:t.repeat||t.oneof?!1:t.kind=="message",t}function nS(t){if(typeof t!="object"||t===null||!t.hasOwnProperty("oneofKind"))return!1;switch(typeof t.oneofKind){case"string":return t[t.oneofKind]===void 0?!1:Object.keys(t).length==2;case"undefined":return Object.keys(t).length==1;default:return!1}}class iS{constructor(e){var n;this.fields=(n=e.fields)!==null&&n!==void 0?n:[]}prepare(){if(this.data)return;const e=[],n=[],i=[];for(let s of this.fields)if(s.oneof)i.includes(s.oneof)||(i.push(s.oneof),e.push(s.oneof),n.push(s.oneof));else switch(n.push(s.localName),s.kind){case"scalar":case"enum":(!s.opt||s.repeat)&&e.push(s.localName);break;case"message":s.repeat&&e.push(s.localName);break;case"map":e.push(s.localName);break}this.data={req:e,known:n,oneofs:Object.values(i)}}is(e,n,i=!1){if(n<0)return!0;if(e==null||typeof e!="object")return!1;this.prepare();let s=Object.keys(e),r=this.data;if(s.length<r.req.length||r.req.some(a=>!s.includes(a))||!i&&s.some(a=>!r.known.includes(a)))return!1;if(n<1)return!0;for(const a of r.oneofs){const c=e[a];if(!nS(c))return!1;if(c.oneofKind===void 0)continue;const d=this.fields.find(h=>h.localName===c.oneofKind);if(!d||!this.field(c[c.oneofKind],d,i,n))return!1}for(const a of this.fields)if(a.oneof===void 0&&!this.field(e[a.localName],a,i,n))return!1;return!0}field(e,n,i,s){let r=n.repeat;switch(n.kind){case"scalar":return e===void 0?n.opt:r?this.scalars(e,n.T,s,n.L):this.scalar(e,n.T,n.L);case"enum":return e===void 0?n.opt:r?this.scalars(e,B.INT32,s):this.scalar(e,B.INT32);case"message":return e===void 0?!0:r?this.messages(e,n.T(),i,s):this.message(e,n.T(),i,s);case"map":if(typeof e!="object"||e===null)return!1;if(s<2)return!0;if(!this.mapKeys(e,n.K,s))return!1;switch(n.V.kind){case"scalar":return this.scalars(Object.values(e),n.V.T,s,n.V.L);case"enum":return this.scalars(Object.values(e),B.INT32,s);case"message":return this.messages(Object.values(e),n.V.T(),i,s)}break}return!0}message(e,n,i,s){return i?n.isAssignable(e,s):n.is(e,s)}messages(e,n,i,s){if(!Array.isArray(e))return!1;if(s<2)return!0;if(i){for(let r=0;r<e.length&&r<s;r++)if(!n.isAssignable(e[r],s-1))return!1}else for(let r=0;r<e.length&&r<s;r++)if(!n.is(e[r],s-1))return!1;return!0}scalar(e,n,i){let s=typeof e;switch(n){case B.UINT64:case B.FIXED64:case B.INT64:case B.SFIXED64:case B.SINT64:switch(i){case di.BIGINT:return s=="bigint";case di.NUMBER:return s=="number"&&!isNaN(e);default:return s=="string"}case B.BOOL:return s=="boolean";case B.STRING:return s=="string";case B.BYTES:return e instanceof Uint8Array;case B.DOUBLE:case B.FLOAT:return s=="number"&&!isNaN(e);default:return s=="number"&&Number.isInteger(e)}}scalars(e,n,i,s){if(!Array.isArray(e))return!1;if(i<2)return!0;if(Array.isArray(e)){for(let r=0;r<e.length&&r<i;r++)if(!this.scalar(e[r],n,s))return!1}return!0}mapKeys(e,n,i){let s=Object.keys(e);switch(n){case B.INT32:case B.FIXED32:case B.SFIXED32:case B.SINT32:case B.UINT32:return this.scalars(s.slice(0,i).map(r=>parseInt(r)),n,i);case B.BOOL:return this.scalars(s.slice(0,i).map(r=>r=="true"?!0:r=="false"?!1:r),n,i);default:return this.scalars(s,n,i,di.STRING)}}}function Hn(t,e){switch(e){case di.BIGINT:return t.toBigInt();case di.NUMBER:return t.toNumber();default:return t.toString()}}class sS{constructor(e){this.info=e}prepare(){var e;if(this.fMap===void 0){this.fMap={};const n=(e=this.info.fields)!==null&&e!==void 0?e:[];for(const i of n)this.fMap[i.name]=i,this.fMap[i.jsonName]=i,this.fMap[i.localName]=i}}assert(e,n,i){if(!e){let s=Ap(i);throw(s=="number"||s=="boolean")&&(s=i.toString()),new Error(`Cannot parse JSON ${s} for ${this.info.typeName}#${n}`)}}read(e,n,i){this.prepare();const s=[];for(const[r,a]of Object.entries(e)){const c=this.fMap[r];if(!c){if(!i.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${r}`);continue}const d=c.localName;let h;if(c.oneof){if(a===null&&(c.kind!=="enum"||c.T()[0]!=="google.protobuf.NullValue"))continue;if(s.includes(c.oneof))throw new Error(`Multiple members of the oneof group "${c.oneof}" of ${this.info.typeName} are present in JSON.`);s.push(c.oneof),h=n[c.oneof]={oneofKind:d}}else h=n;if(c.kind=="map"){if(a===null)continue;this.assert(UE(a),c.name,a);const u=h[d];for(const[g,E]of Object.entries(a)){this.assert(E!==null,c.name+" map value",null);let b;switch(c.V.kind){case"message":b=c.V.T().internalJsonRead(E,i);break;case"enum":if(b=this.enum(c.V.T(),E,c.name,i.ignoreUnknownFields),b===!1)continue;break;case"scalar":b=this.scalar(E,c.V.T,c.V.L,c.name);break}this.assert(b!==void 0,c.name+" map value",E);let w=g;c.K==B.BOOL&&(w=w=="true"?!0:w=="false"?!1:w),w=this.scalar(w,c.K,di.STRING,c.name).toString(),u[w]=b}}else if(c.repeat){if(a===null)continue;this.assert(Array.isArray(a),c.name,a);const u=h[d];for(const g of a){this.assert(g!==null,c.name,null);let E;switch(c.kind){case"message":E=c.T().internalJsonRead(g,i);break;case"enum":if(E=this.enum(c.T(),g,c.name,i.ignoreUnknownFields),E===!1)continue;break;case"scalar":E=this.scalar(g,c.T,c.L,c.name);break}this.assert(E!==void 0,c.name,a),u.push(E)}}else switch(c.kind){case"message":if(a===null&&c.T().typeName!="google.protobuf.Value"){this.assert(c.oneof===void 0,c.name+" (oneof member)",null);continue}h[d]=c.T().internalJsonRead(a,i,h[d]);break;case"enum":if(a===null)continue;let u=this.enum(c.T(),a,c.name,i.ignoreUnknownFields);if(u===!1)continue;h[d]=u;break;case"scalar":if(a===null)continue;h[d]=this.scalar(a,c.T,c.L,c.name);break}}}enum(e,n,i,s){if(e[0]=="google.protobuf.NullValue"&&Ee(n===null||n==="NULL_VALUE",`Unable to parse field ${this.info.typeName}#${i}, enum ${e[0]} only accepts null.`),n===null)return 0;switch(typeof n){case"number":return Ee(Number.isInteger(n),`Unable to parse field ${this.info.typeName}#${i}, enum can only be integral number, got ${n}.`),n;case"string":let r=n;e[2]&&n.substring(0,e[2].length)===e[2]&&(r=n.substring(e[2].length));let a=e[1][r];return typeof a=="undefined"&&s?!1:(Ee(typeof a=="number",`Unable to parse field ${this.info.typeName}#${i}, enum ${e[0]} has no value for "${n}".`),a)}Ee(!1,`Unable to parse field ${this.info.typeName}#${i}, cannot parse enum value from ${typeof n}".`)}scalar(e,n,i,s){let r;try{switch(n){case B.DOUBLE:case B.FLOAT:if(e===null)return 0;if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""){r="empty string";break}if(typeof e=="string"&&e.trim().length!==e.length){r="extra whitespace";break}if(typeof e!="string"&&typeof e!="number")break;let a=Number(e);if(Number.isNaN(a)){r="not a number";break}if(!Number.isFinite(a)){r="too large or small";break}return n==B.FLOAT&&Mp(a),a;case B.INT32:case B.FIXED32:case B.SFIXED32:case B.SINT32:case B.UINT32:if(e===null)return 0;let c;if(typeof e=="number"?c=e:e===""?r="empty string":typeof e=="string"&&(e.trim().length!==e.length?r="extra whitespace":c=Number(e)),c===void 0)break;return n==B.UINT32?Kd(c):Ho(c),c;case B.INT64:case B.SFIXED64:case B.SINT64:if(e===null)return Hn(xe.ZERO,i);if(typeof e!="number"&&typeof e!="string")break;return Hn(xe.from(e),i);case B.FIXED64:case B.UINT64:if(e===null)return Hn(Dt.ZERO,i);if(typeof e!="number"&&typeof e!="string")break;return Hn(Dt.from(e),i);case B.BOOL:if(e===null)return!1;if(typeof e!="boolean")break;return e;case B.STRING:if(e===null)return"";if(typeof e!="string"){r="extra whitespace";break}try{encodeURIComponent(e)}catch(d){d="invalid UTF8";break}return e;case B.BYTES:if(e===null||e==="")return new Uint8Array(0);if(typeof e!="string")break;return BE(e)}}catch(a){r=a.message}this.assert(!1,s+(r?" - "+r:""),e)}}class rS{constructor(e){var n;this.fields=(n=e.fields)!==null&&n!==void 0?n:[]}write(e,n){const i={},s=e;for(const r of this.fields){if(!r.oneof){let h=this.field(r,s[r.localName],n);h!==void 0&&(i[n.useProtoFieldName?r.name:r.jsonName]=h);continue}const a=s[r.oneof];if(a.oneofKind!==r.localName)continue;const c=r.kind=="scalar"||r.kind=="enum"?Object.assign(Object.assign({},n),{emitDefaultValues:!0}):n;let d=this.field(r,a[r.localName],c);Ee(d!==void 0),i[n.useProtoFieldName?r.name:r.jsonName]=d}return i}field(e,n,i){let s;if(e.kind=="map"){Ee(typeof n=="object"&&n!==null);const r={};switch(e.V.kind){case"scalar":for(const[d,h]of Object.entries(n)){const u=this.scalar(e.V.T,h,e.name,!1,!0);Ee(u!==void 0),r[d.toString()]=u}break;case"message":const a=e.V.T();for(const[d,h]of Object.entries(n)){const u=this.message(a,h,e.name,i);Ee(u!==void 0),r[d.toString()]=u}break;case"enum":const c=e.V.T();for(const[d,h]of Object.entries(n)){Ee(h===void 0||typeof h=="number");const u=this.enum(c,h,e.name,!1,!0,i.enumAsInteger);Ee(u!==void 0),r[d.toString()]=u}break}(i.emitDefaultValues||Object.keys(r).length>0)&&(s=r)}else if(e.repeat){Ee(Array.isArray(n));const r=[];switch(e.kind){case"scalar":for(let d=0;d<n.length;d++){const h=this.scalar(e.T,n[d],e.name,e.opt,!0);Ee(h!==void 0),r.push(h)}break;case"enum":const a=e.T();for(let d=0;d<n.length;d++){Ee(n[d]===void 0||typeof n[d]=="number");const h=this.enum(a,n[d],e.name,e.opt,!0,i.enumAsInteger);Ee(h!==void 0),r.push(h)}break;case"message":const c=e.T();for(let d=0;d<n.length;d++){const h=this.message(c,n[d],e.name,i);Ee(h!==void 0),r.push(h)}break}(i.emitDefaultValues||r.length>0||i.emitDefaultValues)&&(s=r)}else switch(e.kind){case"scalar":s=this.scalar(e.T,n,e.name,e.opt,i.emitDefaultValues);break;case"enum":s=this.enum(e.T(),n,e.name,e.opt,i.emitDefaultValues,i.enumAsInteger);break;case"message":s=this.message(e.T(),n,e.name,i);break}return s}enum(e,n,i,s,r,a){if(e[0]=="google.protobuf.NullValue")return!r&&!s?void 0:null;if(n===void 0){Ee(s);return}if(!(n===0&&!r&&!s))return Ee(typeof n=="number"),Ee(Number.isInteger(n)),a||!e[1].hasOwnProperty(n)?n:e[2]?e[2]+e[1][n]:e[1][n]}message(e,n,i,s){return n===void 0?s.emitDefaultValues?null:void 0:e.internalJsonWrite(n,s)}scalar(e,n,i,s,r){if(n===void 0){Ee(s);return}const a=r||s;switch(e){case B.INT32:case B.SFIXED32:case B.SINT32:return n===0?a?0:void 0:(Ho(n),n);case B.FIXED32:case B.UINT32:return n===0?a?0:void 0:(Kd(n),n);case B.FLOAT:Mp(n);case B.DOUBLE:return n===0?a?0:void 0:(Ee(typeof n=="number"),Number.isNaN(n)?"NaN":n===Number.POSITIVE_INFINITY?"Infinity":n===Number.NEGATIVE_INFINITY?"-Infinity":n);case B.STRING:return n===""?a?"":void 0:(Ee(typeof n=="string"),n);case B.BOOL:return n===!1?a?!1:void 0:(Ee(typeof n=="boolean"),n);case B.UINT64:case B.FIXED64:Ee(typeof n=="number"||typeof n=="string"||typeof n=="bigint");let c=Dt.from(n);return c.isZero()&&!a?void 0:c.toString();case B.INT64:case B.SFIXED64:case B.SINT64:Ee(typeof n=="number"||typeof n=="string"||typeof n=="bigint");let d=xe.from(n);return d.isZero()&&!a?void 0:d.toString();case B.BYTES:return Ee(n instanceof Uint8Array),n.byteLength?FE(n):a?"":void 0}}}function nh(t,e=di.STRING){switch(t){case B.BOOL:return!1;case B.UINT64:case B.FIXED64:return Hn(Dt.ZERO,e);case B.INT64:case B.SFIXED64:case B.SINT64:return Hn(xe.ZERO,e);case B.DOUBLE:case B.FLOAT:return 0;case B.BYTES:return new Uint8Array(0);case B.STRING:return"";default:return 0}}class aS{constructor(e){this.info=e}prepare(){var e;if(!this.fieldNoToField){const n=(e=this.info.fields)!==null&&e!==void 0?e:[];this.fieldNoToField=new Map(n.map(i=>[i.no,i]))}}read(e,n,i,s){this.prepare();const r=s===void 0?e.len:e.pos+s;for(;e.pos<r;){const[a,c]=e.tag(),d=this.fieldNoToField.get(a);if(!d){let E=i.readUnknownField;if(E=="throw")throw new Error(`Unknown field ${a} (wire type ${c}) for ${this.info.typeName}`);let b=e.skip(c);E!==!1&&(E===!0?$d.onRead:E)(this.info.typeName,n,a,c,b);continue}let h=n,u=d.repeat,g=d.localName;switch(d.oneof&&(h=h[d.oneof],h.oneofKind!==g&&(h=n[d.oneof]={oneofKind:g})),d.kind){case"scalar":case"enum":let E=d.kind=="enum"?B.INT32:d.T,b=d.kind=="scalar"?d.L:void 0;if(u){let D=h[g];if(c==it.LengthDelimited&&E!=B.STRING&&E!=B.BYTES){let F=e.uint32()+e.pos;for(;e.pos<F;)D.push(this.scalar(e,E,b))}else D.push(this.scalar(e,E,b))}else h[g]=this.scalar(e,E,b);break;case"message":if(u){let D=h[g],F=d.T().internalBinaryRead(e,e.uint32(),i);D.push(F)}else h[g]=d.T().internalBinaryRead(e,e.uint32(),i,h[g]);break;case"map":let[w,M]=this.mapEntry(d,e,i);h[g][w]=M;break}}}mapEntry(e,n,i){let s=n.uint32(),r=n.pos+s,a,c;for(;n.pos<r;){let[d,h]=n.tag();switch(d){case 1:e.K==B.BOOL?a=n.bool().toString():a=this.scalar(n,e.K,di.STRING);break;case 2:switch(e.V.kind){case"scalar":c=this.scalar(n,e.V.T,e.V.L);break;case"enum":c=n.int32();break;case"message":c=e.V.T().internalBinaryRead(n,n.uint32(),i);break}break;default:throw new Error(`Unknown field ${d} (wire type ${h}) in map entry for ${this.info.typeName}#${e.name}`)}}if(a===void 0){let d=nh(e.K);a=e.K==B.BOOL?d.toString():d}if(c===void 0)switch(e.V.kind){case"scalar":c=nh(e.V.T,e.V.L);break;case"enum":c=0;break;case"message":c=e.V.T().create();break}return[a,c]}scalar(e,n,i){switch(n){case B.INT32:return e.int32();case B.STRING:return e.string();case B.BOOL:return e.bool();case B.DOUBLE:return e.double();case B.FLOAT:return e.float();case B.INT64:return Hn(e.int64(),i);case B.UINT64:return Hn(e.uint64(),i);case B.FIXED64:return Hn(e.fixed64(),i);case B.FIXED32:return e.fixed32();case B.BYTES:return e.bytes();case B.UINT32:return e.uint32();case B.SFIXED32:return e.sfixed32();case B.SFIXED64:return Hn(e.sfixed64(),i);case B.SINT32:return e.sint32();case B.SINT64:return Hn(e.sint64(),i)}}}class oS{constructor(e){this.info=e}prepare(){if(!this.fields){const e=this.info.fields?this.info.fields.concat():[];this.fields=e.sort((n,i)=>n.no-i.no)}}write(e,n,i){this.prepare();for(const r of this.fields){let a,c,d=r.repeat,h=r.localName;if(r.oneof){const u=e[r.oneof];if(u.oneofKind!==h)continue;a=u[h],c=!0}else a=e[h],c=!1;switch(r.kind){case"scalar":case"enum":let u=r.kind=="enum"?B.INT32:r.T;if(d)if(Ee(Array.isArray(a)),d==zd.PACKED)this.packed(n,u,r.no,a);else for(const g of a)this.scalar(n,u,r.no,g,!0);else a===void 0?Ee(r.opt):this.scalar(n,u,r.no,a,c||r.opt);break;case"message":if(d){Ee(Array.isArray(a));for(const g of a)this.message(n,i,r.T(),r.no,g)}else this.message(n,i,r.T(),r.no,a);break;case"map":Ee(typeof a=="object"&&a!==null);for(const[g,E]of Object.entries(a))this.mapEntry(n,i,r,g,E);break}}let s=i.writeUnknownFields;s!==!1&&(s===!0?$d.onWrite:s)(this.info.typeName,e,n)}mapEntry(e,n,i,s,r){e.tag(i.no,it.LengthDelimited),e.fork();let a=s;switch(i.K){case B.INT32:case B.FIXED32:case B.UINT32:case B.SFIXED32:case B.SINT32:a=Number.parseInt(s);break;case B.BOOL:Ee(s=="true"||s=="false"),a=s=="true";break}switch(this.scalar(e,i.K,1,a,!0),i.V.kind){case"scalar":this.scalar(e,i.V.T,2,r,!0);break;case"enum":this.scalar(e,B.INT32,2,r,!0);break;case"message":this.message(e,n,i.V.T(),2,r);break}e.join()}message(e,n,i,s,r){r!==void 0&&(i.internalBinaryWrite(r,e.tag(s,it.LengthDelimited).fork(),n),e.join())}scalar(e,n,i,s,r){let[a,c,d]=this.scalarInfo(n,s);(!d||r)&&(e.tag(i,a),e[c](s))}packed(e,n,i,s){if(!s.length)return;Ee(n!==B.BYTES&&n!==B.STRING),e.tag(i,it.LengthDelimited),e.fork();let[,r]=this.scalarInfo(n);for(let a=0;a<s.length;a++)e[r](s[a]);e.join()}scalarInfo(e,n){let i=it.Varint,s,r=n===void 0,a=n===0;switch(e){case B.INT32:s="int32";break;case B.STRING:a=r||!n.length,i=it.LengthDelimited,s="string";break;case B.BOOL:a=n===!1,s="bool";break;case B.UINT32:s="uint32";break;case B.DOUBLE:i=it.Bit64,s="double";break;case B.FLOAT:i=it.Bit32,s="float";break;case B.INT64:a=r||xe.from(n).isZero(),s="int64";break;case B.UINT64:a=r||Dt.from(n).isZero(),s="uint64";break;case B.FIXED64:a=r||Dt.from(n).isZero(),i=it.Bit64,s="fixed64";break;case B.BYTES:a=r||!n.byteLength,i=it.LengthDelimited,s="bytes";break;case B.FIXED32:i=it.Bit32,s="fixed32";break;case B.SFIXED32:i=it.Bit32,s="sfixed32";break;case B.SFIXED64:a=r||xe.from(n).isZero(),i=it.Bit64,s="sfixed64";break;case B.SINT32:s="sint32";break;case B.SINT64:a=r||xe.from(n).isZero(),s="sint64";break}return[i,s,r||a]}}function cS(t){const e=t.messagePrototype?Object.create(t.messagePrototype):Object.defineProperty({},dv,{value:t});for(let n of t.fields){let i=n.localName;if(!n.opt)if(n.oneof)e[n.oneof]={oneofKind:void 0};else if(n.repeat)e[i]=[];else switch(n.kind){case"scalar":e[i]=nh(n.T,n.L);break;case"enum":e[i]=0;break;case"map":e[i]={};break}}return e}function ou(t,e,n){let i,s=n,r;for(let a of t.fields){let c=a.localName;if(a.oneof){const d=s[a.oneof];if((d==null?void 0:d.oneofKind)==null)continue;if(i=d[c],r=e[a.oneof],r.oneofKind=d.oneofKind,i==null){delete r[c];continue}}else if(i=s[c],r=e,i==null)continue;switch(a.repeat&&(r[c].length=i.length),a.kind){case"scalar":case"enum":if(a.repeat)for(let h=0;h<i.length;h++)r[c][h]=i[h];else r[c]=i;break;case"message":let d=a.T();if(a.repeat)for(let h=0;h<i.length;h++)r[c][h]=d.create(i[h]);else r[c]===void 0?r[c]=d.create(i):d.mergePartial(r[c],i);break;case"map":switch(a.V.kind){case"scalar":case"enum":Object.assign(r[c],i);break;case"message":let h=a.V.T();for(let u of Object.keys(i))r[c][u]=h.create(i[u]);break}break}}}function dS(t,e,n){if(e===n)return!0;if(!e||!n)return!1;for(let i of t.fields){let s=i.localName,r=i.oneof?e[i.oneof][s]:e[s],a=i.oneof?n[i.oneof][s]:n[s];switch(i.kind){case"enum":case"scalar":let c=i.kind=="enum"?B.INT32:i.T;if(!(i.repeat?Cm(c,r,a):lv(c,r,a)))return!1;break;case"map":if(!(i.V.kind=="message"?Rm(i.V.T(),Ac(r),Ac(a)):Cm(i.V.kind=="enum"?B.INT32:i.V.T,Ac(r),Ac(a))))return!1;break;case"message":let d=i.T();if(!(i.repeat?Rm(d,r,a):d.equals(r,a)))return!1;break}}return!0}const Ac=Object.values;function lv(t,e,n){if(e===n)return!0;if(t!==B.BYTES)return!1;let i=e,s=n;if(i.length!==s.length)return!1;for(let r=0;r<i.length;r++)if(i[r]!=s[r])return!1;return!0}function Cm(t,e,n){if(e.length!==n.length)return!1;for(let i=0;i<e.length;i++)if(!lv(t,e[i],n[i]))return!1;return!0}function Rm(t,e,n){if(e.length!==n.length)return!1;for(let i=0;i<e.length;i++)if(!t.equals(e[i],n[i]))return!1;return!0}const lS=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({}));class _{constructor(e,n,i){this.defaultCheckDepth=16,this.typeName=e,this.fields=n.map(tS),this.options=i!=null?i:{},this.messagePrototype=Object.create(null,Object.assign(Object.assign({},lS),{[dv]:{value:this}})),this.refTypeCheck=new iS(this),this.refJsonReader=new sS(this),this.refJsonWriter=new rS(this),this.refBinReader=new aS(this),this.refBinWriter=new oS(this)}create(e){let n=cS(this);return e!==void 0&&ou(this,n,e),n}clone(e){let n=this.create();return ou(this,n,e),n}equals(e,n){return dS(this,e,n)}is(e,n=this.defaultCheckDepth){return this.refTypeCheck.is(e,n,!1)}isAssignable(e,n=this.defaultCheckDepth){return this.refTypeCheck.is(e,n,!0)}mergePartial(e,n){ou(this,e,n)}fromBinary(e,n){let i=qE(n);return this.internalBinaryRead(i.readerFactory(e),e.byteLength,i)}fromJson(e,n){return this.internalJsonRead(e,ZE(n))}fromJsonString(e,n){let i=JSON.parse(e);return this.fromJson(i,n)}toJson(e,n){return this.internalJsonWrite(e,eS(n))}toJsonString(e,n){var i;let s=this.toJson(e,n);return JSON.stringify(s,null,(i=n==null?void 0:n.prettySpaces)!==null&&i!==void 0?i:0)}toBinary(e,n){let i=QE(n);return this.internalBinaryWrite(e,i.writerFactory(),i).finish()}internalJsonRead(e,n,i){if(e!==null&&typeof e=="object"&&!Array.isArray(e)){let s=i!=null?i:this.create();return this.refJsonReader.read(e,s,n),s}throw new Error(`Unable to parse message ${this.typeName} from JSON ${Ap(e)}.`)}internalJsonWrite(e,n){return this.refJsonWriter.write(e,n)}internalBinaryWrite(e,n,i){return this.refBinWriter.write(e,n,i),n}internalBinaryRead(e,n,i,s){let r=s!=null?s:this.create();return this.refBinReader.read(e,r,i,n),r}}const uS=t=>(e,n)=>(t.set(e,n),n),Pm=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,uv=536870912,Am=uv*2,hS=(t,e)=>n=>{const i=e.get(n);let s=i===void 0?n.size:i<Am?i+1:0;if(!n.has(s))return t(n,s);if(n.size<uv){for(;n.has(s);)s=Math.floor(Math.random()*Am);return t(n,s)}if(n.size>Pm)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;n.has(s);)s=Math.floor(Math.random()*Pm);return t(n,s)},hv=new WeakMap,pS=uS(hv),Mc=hS(pS,hv),mS=t=>t.method!==void 0&&t.method==="call",fS=t=>t.error===null&&typeof t.id=="number",gS=t=>{const e=new Map([[0,()=>{}]]),n=new Map([[0,()=>{}]]),i=new Map,s=new Worker(t);return s.addEventListener("message",({data:h})=>{if(mS(h)){const{params:{timerId:u,timerType:g}}=h;if(g==="interval"){const E=e.get(u);if(typeof E=="number"){const b=i.get(E);if(b===void 0||b.timerId!==u||b.timerType!==g)throw new Error("The timer is in an undefined state.")}else if(typeof E!="undefined")E();else throw new Error("The timer is in an undefined state.")}else if(g==="timeout"){const E=n.get(u);if(typeof E=="number"){const b=i.get(E);if(b===void 0||b.timerId!==u||b.timerType!==g)throw new Error("The timer is in an undefined state.")}else if(typeof E!="undefined")E(),n.delete(u);else throw new Error("The timer is in an undefined state.")}}else if(fS(h)){const{id:u}=h,g=i.get(u);if(g===void 0)throw new Error("The timer is in an undefined state.");const{timerId:E,timerType:b}=g;i.delete(u),b==="interval"?e.delete(E):n.delete(E)}else{const{error:{message:u}}=h;throw new Error(u)}}),{clearInterval:h=>{const u=Mc(i);i.set(u,{timerId:h,timerType:"interval"}),e.set(h,u),s.postMessage({id:u,method:"clear",params:{timerId:h,timerType:"interval"}})},clearTimeout:h=>{const u=Mc(i);i.set(u,{timerId:h,timerType:"timeout"}),n.set(h,u),s.postMessage({id:u,method:"clear",params:{timerId:h,timerType:"timeout"}})},setInterval:(h,u=0)=>{const g=Mc(e);return e.set(g,()=>{h(),typeof e.get(g)=="function"&&s.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:g,timerType:"interval"}})}),s.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:g,timerType:"interval"}}),g},setTimeout:(h,u=0)=>{const g=Mc(n);return n.set(g,h),s.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:g,timerType:"timeout"}}),g}}},vS=(t,e)=>{let n=null;return()=>{if(n!==null)return n;const i=new Blob([e],{type:"application/javascript; charset=utf-8"}),s=URL.createObjectURL(i);return n=t(s),setTimeout(()=>URL.revokeObjectURL(s)),n}},yS=`(()=>{"use strict";const e=new Map,t=new Map,r=(e,t)=>{let r,o;const i=performance.now();r=i,o=e-Math.max(0,i-t);return{expected:r+o,remainingDelay:o}},o=(e,t,r,i)=>{const s=performance.now();s>r?postMessage({id:null,method:"call",params:{timerId:t,timerType:i}}):e.set(t,setTimeout(o,r-s,e,t,r,i))};addEventListener("message",(i=>{let{data:s}=i;try{if("clear"===s.method){const{id:r,params:{timerId:o,timerType:i}}=s;if("interval"===i)(t=>{const r=e.get(t);if(void 0===r)throw new Error('There is no interval scheduled with the given id "'.concat(t,'".'));clearTimeout(r),e.delete(t)})(o),postMessage({error:null,id:r});else{if("timeout"!==i)throw new Error('The given type "'.concat(i,'" is not supported'));(e=>{const r=t.get(e);if(void 0===r)throw new Error('There is no timeout scheduled with the given id "'.concat(e,'".'));clearTimeout(r),t.delete(e)})(o),postMessage({error:null,id:r})}}else{if("set"!==s.method)throw new Error('The given method "'.concat(s.method,'" is not supported'));{const{params:{delay:i,now:n,timerId:a,timerType:d}}=s;if("interval"===d)((t,i,s)=>{const{expected:n,remainingDelay:a}=r(t,s);e.set(i,setTimeout(o,a,e,i,n,"interval"))})(i,a,n);else{if("timeout"!==d)throw new Error('The given type "'.concat(d,'" is not supported'));((e,i,s)=>{const{expected:n,remainingDelay:a}=r(e,s);t.set(i,setTimeout(o,a,t,i,n,"timeout"))})(i,a,n)}}}}catch(e){postMessage({error:{message:e.message},id:s.id,result:null})}}))})();`,Rl=vS(gS,yS),da=t=>Rl().clearInterval(t),ES=t=>Rl().clearTimeout(t),Yd=(t,e)=>Rl().setInterval(t,e),SS=(t,e)=>Rl().setTimeout(t,e);var TS=Object.freeze(Object.defineProperty({__proto__:null,clearInterval:da,clearTimeout:ES,setInterval:Yd,setTimeout:SS},Symbol.toStringTag,{value:"Module"})),pv={},Op={exports:{}},Mm=Op.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(t){return t.encoding?"rtpmap:%d %s/%s/%s":t.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(t){return t.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(t){return t.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(t){return"extmap:%d"+(t.direction?"/%s":"%v")+(t["encrypt-uri"]?" %s":"%v")+" %s"+(t.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(t){return t.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"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%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(t){var e="candidate:%s %d %s %d %s %d typ %s";return e+=t.raddr!=null?" raddr %s rport %d":"%v%v",e+=t.tcptype!=null?" tcptype %s":"%v",t.generation!=null&&(e+=" generation %d"),e+=t["network-id"]!=null?" network-id %d":"%v",e+=t["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(t){var e="ssrc:%d";return t.attribute!=null&&(e+=" %s",t.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(t){return t.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(t){return t.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(t){return"imageattr:%s %s %s"+(t.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(t){return"simulcast:%s %s"+(t.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(t){return"ts-refclk:%s"+(t.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(t){var e="mediaclk:";return e+=t.id!=null?"id=%s %s":"%v%s",e+=t.mediaClockValue!=null?"=%s":"",e+=t.rateNumerator!=null?" rate=%s":"",e+=t.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(Mm).forEach(function(t){var e=Mm[t];e.forEach(function(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})});(function(t){var e=function(c){return String(Number(c))===c?Number(c):c},n=function(c,d,h,u){if(u&&!h)d[u]=e(c[1]);else for(var g=0;g<h.length;g+=1)c[g+1]!=null&&(d[h[g]]=e(c[g+1]))},i=function(c,d,h){var u=c.name&&c.names;c.push&&!d[c.push]?d[c.push]=[]:u&&!d[c.name]&&(d[c.name]={});var g=c.push?{}:u?d[c.name]:d;n(h.match(c.reg),g,c.names,c.name),c.push&&d[c.push].push(g)},s=Op.exports,r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(c){var d={},h=[],u=d;return c.split(/(\r\n|\r|\n)/).filter(r).forEach(function(g){var E=g[0],b=g.slice(2);E==="m"&&(h.push({rtp:[],fmtp:[]}),u=h[h.length-1]);for(var w=0;w<(s[E]||[]).length;w+=1){var M=s[E][w];if(M.reg.test(b))return i(M,u,b)}}),d.media=h,d};var a=function(c,d){var h=d.split(/=(.+)/,2);return h.length===2?c[h[0]]=e(h[1]):h.length===1&&d.length>1&&(c[h[0]]=void 0),c};t.parseParams=function(c){return c.split(/;\s?/).reduce(a,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(c){return c.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(c){for(var d=[],h=c.split(" ").map(e),u=0;u<h.length;u+=3)d.push({component:h[u],ip:h[u+1],port:h[u+2]});return d},t.parseImageAttributes=function(c){return c.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(a,{})})},t.parseSimulcastStreamList=function(c){return c.split(";").map(function(d){return d.split(",").map(function(h){var u,g=!1;return h[0]!=="~"?u=e(h):(u=e(h.substring(1,h.length)),g=!0),{scid:u,paused:g}})})}})(pv);var cu=Op.exports,bS=/%[sdv%]/g,kS=function(t){var e=1,n=arguments,i=n.length;return t.replace(bS,function(s){if(e>=i)return s;var r=n[e];switch(e+=1,s){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}})},Da=function(t,e,n){var i=e.format instanceof Function?e.format(e.push?n:n[e.name]):e.format,s=[t+"="+i];if(e.names)for(var r=0;r<e.names.length;r+=1){var a=e.names[r];e.name?s.push(n[e.name][a]):s.push(n[e.names[r]])}else s.push(n[e.name]);return kS.apply(null,s)},wS=["v","o","s","i","u","e","p","c","b","t","r","z","a"],_S=["i","c","b","a"],IS=function(t,e){e=e||{},t.version==null&&(t.version=0),t.name==null&&(t.name=" "),t.media.forEach(function(r){r.payloads==null&&(r.payloads="")});var n=e.outerOrder||wS,i=e.innerOrder||_S,s=[];return n.forEach(function(r){cu[r].forEach(function(a){a.name in t&&t[a.name]!=null?s.push(Da(r,a,t)):a.push in t&&t[a.push]!=null&&t[a.push].forEach(function(c){s.push(Da(r,a,c))})})}),t.media.forEach(function(r){s.push(Da("m",cu.m[0],r)),i.forEach(function(a){cu[a].forEach(function(c){c.name in r&&r[c.name]!=null?s.push(Da(a,c,r)):c.push in r&&r[c.push]!=null&&r[c.push].forEach(function(d){s.push(Da(a,c,d))})})})}),s.join(`\r
8
+ `)+`\r
9
+ `},Sr=pv,CS=IS,ih=CS,qo=Sr.parse;Sr.parseParams;Sr.parseFmtpConfig;Sr.parsePayloads;Sr.parseRemoteCandidates;Sr.parseImageAttributes;Sr.parseSimulcastStreamList;var RS=Object.defineProperty,PS=Object.defineProperties,AS=Object.getOwnPropertyDescriptors,Qd=Object.getOwnPropertySymbols,MS=Object.getPrototypeOf,mv=Object.prototype.hasOwnProperty,fv=Object.prototype.propertyIsEnumerable,OS=Reflect.get,Oe=Math.pow,sh=(t,e,n)=>e in t?RS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,H=(t,e)=>{for(var n in e||(e={}))mv.call(e,n)&&sh(t,n,e[n]);if(Qd)for(var n of Qd(e))fv.call(e,n)&&sh(t,n,e[n]);return t},ee=(t,e)=>PS(t,AS(e)),Pl=(t,e)=>{var n={};for(var i in t)mv.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&Qd)for(var i of Qd(t))e.indexOf(i)<0&&fv.call(t,i)&&(n[i]=t[i]);return n},y=(t,e,n)=>(sh(t,typeof e!="symbol"?e+"":e,n),n),Dp=(t,e,n)=>{if(!e.has(t))throw TypeError("Cannot "+n)},o=(t,e,n)=>(Dp(t,e,"read from private field"),n?n.call(t):e.get(t)),S=(t,e,n)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,n)},T=(t,e,n,i)=>(Dp(t,e,"write to private field"),i?i.call(t,n):e.set(t,n),n),Q=(t,e,n)=>(Dp(t,e,"access private method"),n),DS=(t,e,n)=>OS(MS(t),n,e),p=(t,e,n)=>new Promise((i,s)=>{var r=d=>{try{c(n.next(d))}catch(h){s(h)}},a=d=>{try{c(n.throw(d))}catch(h){s(h)}},c=d=>d.done?i(d.value):Promise.resolve(d.value).then(r,a);c((n=n.apply(t,e)).next())});function NS(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Nt={},LS={get exports(){return Nt},set exports(t){Nt=t}},pa=typeof Reflect=="object"?Reflect:null,Om=pa&&typeof pa.apply=="function"?pa.apply:function(t,e,n){return Function.prototype.apply.call(t,e,n)},cd;pa&&typeof pa.ownKeys=="function"?cd=pa.ownKeys:Object.getOwnPropertySymbols?cd=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:cd=function(t){return Object.getOwnPropertyNames(t)};function xS(t){console&&console.warn&&console.warn(t)}var gv=Number.isNaN||function(t){return t!==t};function we(){we.init.call(this)}LS.exports=we;Nt.once=FS;we.EventEmitter=we;we.prototype._events=void 0;we.prototype._eventsCount=0;we.prototype._maxListeners=void 0;var Dm=10;function Al(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(we,"defaultMaxListeners",{enumerable:!0,get:function(){return Dm},set:function(t){if(typeof t!="number"||t<0||gv(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Dm=t}});we.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};we.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||gv(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function vv(t){return t._maxListeners===void 0?we.defaultMaxListeners:t._maxListeners}we.prototype.getMaxListeners=function(){return vv(this)};we.prototype.emit=function(t){for(var e=[],n=1;n<arguments.length;n++)e.push(arguments[n]);var i=t==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var r;if(e.length>0&&(r=e[0]),r instanceof Error)throw r;var a=new Error("Unhandled error."+(r?" ("+r.message+")":""));throw a.context=r,a}var c=s[t];if(c===void 0)return!1;if(typeof c=="function")Om(c,this,e);else for(var d=c.length,h=bv(c,d),n=0;n<d;++n)Om(h[n],this,e);return!0};function yv(t,e,n,i){var s,r,a;if(Al(n),r=t._events,r===void 0?(r=t._events=Object.create(null),t._eventsCount=0):(r.newListener!==void 0&&(t.emit("newListener",e,n.listener?n.listener:n),r=t._events),a=r[e]),a===void 0)a=r[e]=n,++t._eventsCount;else if(typeof a=="function"?a=r[e]=i?[n,a]:[a,n]:i?a.unshift(n):a.push(n),s=vv(t),s>0&&a.length>s&&!a.warned){a.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=a.length,xS(c)}return t}we.prototype.addListener=function(t,e){return yv(this,t,e,!1)};we.prototype.on=we.prototype.addListener;we.prototype.prependListener=function(t,e){return yv(this,t,e,!0)};function VS(){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 Ev(t,e,n){var i={fired:!1,wrapFn:void 0,target:t,type:e,listener:n},s=VS.bind(i);return s.listener=n,i.wrapFn=s,s}we.prototype.once=function(t,e){return Al(e),this.on(t,Ev(this,t,e)),this};we.prototype.prependOnceListener=function(t,e){return Al(e),this.prependListener(t,Ev(this,t,e)),this};we.prototype.removeListener=function(t,e){var n,i,s,r,a;if(Al(e),i=this._events,i===void 0)return this;if(n=i[t],n===void 0)return this;if(n===e||n.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete i[t],i.removeListener&&this.emit("removeListener",t,n.listener||e));else if(typeof n!="function"){for(s=-1,r=n.length-1;r>=0;r--)if(n[r]===e||n[r].listener===e){a=n[r].listener,s=r;break}if(s<0)return this;s===0?n.shift():US(n,s),n.length===1&&(i[t]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",t,a||e)}return this};we.prototype.off=we.prototype.removeListener;we.prototype.removeAllListeners=function(t){var e,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){var s=Object.keys(n),r;for(i=0;i<s.length;++i)r=s[i],r!=="removeListener"&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=n[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(i=e.length-1;i>=0;i--)this.removeListener(t,e[i]);return this};function Sv(t,e,n){var i=t._events;if(i===void 0)return[];var s=i[e];return s===void 0?[]:typeof s=="function"?n?[s.listener||s]:[s]:n?BS(s):bv(s,s.length)}we.prototype.listeners=function(t){return Sv(this,t,!0)};we.prototype.rawListeners=function(t){return Sv(this,t,!1)};we.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Tv.call(t,e)};we.prototype.listenerCount=Tv;function Tv(t){var e=this._events;if(e!==void 0){var n=e[t];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}we.prototype.eventNames=function(){return this._eventsCount>0?cd(this._events):[]};function bv(t,e){for(var n=new Array(e),i=0;i<e;++i)n[i]=t[i];return n}function US(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function BS(t){for(var e=new Array(t.length),n=0;n<e.length;++n)e[n]=t[n].listener||t[n];return e}function FS(t,e){return new Promise(function(n,i){function s(a){t.removeListener(e,r),i(a)}function r(){typeof t.removeListener=="function"&&t.removeListener("error",s),n([].slice.call(arguments))}kv(t,e,r,{once:!0}),e!=="error"&&jS(t,s,{once:!0})})}function jS(t,e,n){typeof t.on=="function"&&kv(t,"error",e,n)}function kv(t,e,n,i){if(typeof t.on=="function")i.once?t.once(e,n):t.on(e,n);else if(typeof t.addEventListener=="function")t.addEventListener(e,function s(r){i.once&&t.removeEventListener(e,s),n(r)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var oe;(function(t){t[t.MAJOR_EVENT=0]="MAJOR_EVENT",t[t.MINOR_EVENT=1]="MINOR_EVENT"})(oe||(oe={}));var G;(function(t){t.PRECALL_TEST_BEGIN="precall_begin",t.PRECALL_TEST_COMPLETE="precall_end",t.CALL_JOIN_BEGIN="call_join",t.NET_QUALITY_TEST_BEGIN="net_quality_test_begin",t.NET_QUALITY_TEST_END="net_quality_test_end",t.WEBSOCKET_CONNECTED="websocket_connected",t.TRANSPORT_CONNECTED="transport_connected",t.AUDIO_ON="audio_on",t.AUDIO_OFF="audio_off",t.VIDEO_ON="video_on",t.VIDEO_OFF="video_off",t.PARTICIPANT_ROLE="participant_role",t.PING_STAT="ping_stat",t.DISCONNECT="disconnect",t.RECONNECT_ATTEMPT="reconnect_attempt",t.SCREENSHARE_START_REQUESTED="screenshare_start_requested",t.SCREENSHARE_STARTED="screenshare_started",t.SCREENSHARE_STOPPED="screenshare_stopped",t.TAB_CHANGE="tab_change",t.BROWSER_BACKGROUNDED="browser_backgrounded",t.BROWSER_FOREGROUNDED="browser_foregrounded",t.DOMINANT_SPEAKER="dominant_speaker",t.AUDIO_DEVICES_UPDATES="audio_devices_updates",t.VIDEO_DEVICES_UPDATES="video_devices_updates",t.SPEAKER_DEVICES_UPDATES="speaker_devices_updates",t.SELECTED_MICROHPONE_UPDATE="selected_microphone_update",t.SELECTED_CAMERA_UPDATE="selected_camera_update",t.SELECTED_SPEAKER_UPDATE="selected_speaker_update",t.EXPECTED_VIDEO_RESOLUTION="expected_video_resolution",t.EXPECTED_SCREENSHARE_RESOLUTION="expected_screenshare_resolution",t.MEDIA_PERMISSION="media_permission",t.LEGACY_SWITCH="legacy_switch",t.AUDIO_PLAY_FAILED="audio_play_failed",t.VIDEO_PLAY_FAILED="video_play_failed",t.AUDIO_TRACK_MUTED="audio_track_muted",t.VIDEO_TRACK_MUTED="video_track_muted",t.IVS_PLAYER_REBUFFERING="ivs_player_rebuffering",t.IVS_PLAYER_AUDIO_BLOCKED="ivs_player_audio_blocked",t.IVS_PLAYER_PLAYBACK_BLOCKED="ivs_player_playback_blocked",t.IVS_PLAYER_ERROR="ivs_player_error",t.IVS_PLAYER_RECOVERABLE_ERROR="ivs_player_recoverable_error",t.IVS_PLAYER_WORKER_ERROR="ivs_player_worker_error",t.IVS_PLAYER_NETWORK_UNAVAILABLE="ivs_player_network_unavailable",t.LIVESTREAM_LATENCY="livestream_latency",t.IVS_PLAYER_ANALYTICS_EVENT="ivs_player_analytics_event",t.IVS_PLAYER_PLAYBACK_RATE_CHANGED="ivs_player_playback_rate_changed",t.IVS_PLAYER_QUALITY_CHANGED="ivs_player_quality_changed",t.IVS_PLAYER_INITIALIZED="ivs_player_initialized"})(G||(G={}));const WS=new Map([[G.PRECALL_TEST_BEGIN,oe.MINOR_EVENT],[G.PRECALL_TEST_COMPLETE,oe.MINOR_EVENT],[G.CALL_JOIN_BEGIN,oe.MAJOR_EVENT],[G.NET_QUALITY_TEST_BEGIN,oe.MINOR_EVENT],[G.NET_QUALITY_TEST_END,oe.MINOR_EVENT],[G.WEBSOCKET_CONNECTED,oe.MINOR_EVENT],[G.TRANSPORT_CONNECTED,oe.MAJOR_EVENT],[G.AUDIO_ON,oe.MINOR_EVENT],[G.AUDIO_OFF,oe.MINOR_EVENT],[G.VIDEO_ON,oe.MINOR_EVENT],[G.VIDEO_OFF,oe.MINOR_EVENT],[G.PARTICIPANT_ROLE,oe.MINOR_EVENT],[G.PING_STAT,oe.MAJOR_EVENT],[G.DISCONNECT,oe.MAJOR_EVENT],[G.RECONNECT_ATTEMPT,oe.MAJOR_EVENT],[G.SCREENSHARE_START_REQUESTED,oe.MINOR_EVENT],[G.SCREENSHARE_STARTED,oe.MINOR_EVENT],[G.SCREENSHARE_STOPPED,oe.MINOR_EVENT],[G.TAB_CHANGE,oe.MINOR_EVENT],[G.BROWSER_BACKGROUNDED,oe.MINOR_EVENT],[G.BROWSER_FOREGROUNDED,oe.MINOR_EVENT],[G.DOMINANT_SPEAKER,oe.MINOR_EVENT],[G.AUDIO_DEVICES_UPDATES,oe.MINOR_EVENT],[G.VIDEO_DEVICES_UPDATES,oe.MINOR_EVENT],[G.SPEAKER_DEVICES_UPDATES,oe.MINOR_EVENT],[G.SELECTED_MICROHPONE_UPDATE,oe.MINOR_EVENT],[G.SELECTED_CAMERA_UPDATE,oe.MINOR_EVENT],[G.SELECTED_SPEAKER_UPDATE,oe.MINOR_EVENT],[G.MEDIA_PERMISSION,oe.MINOR_EVENT],[G.LEGACY_SWITCH,oe.MINOR_EVENT],[G.AUDIO_PLAY_FAILED,oe.MINOR_EVENT],[G.VIDEO_PLAY_FAILED,oe.MINOR_EVENT],[G.AUDIO_TRACK_MUTED,oe.MINOR_EVENT],[G.VIDEO_TRACK_MUTED,oe.MINOR_EVENT],[G.IVS_PLAYER_REBUFFERING,oe.MAJOR_EVENT],[G.IVS_PLAYER_AUDIO_BLOCKED,oe.MAJOR_EVENT],[G.IVS_PLAYER_PLAYBACK_BLOCKED,oe.MAJOR_EVENT],[G.IVS_PLAYER_ERROR,oe.MAJOR_EVENT],[G.IVS_PLAYER_RECOVERABLE_ERROR,oe.MAJOR_EVENT],[G.IVS_PLAYER_WORKER_ERROR,oe.MAJOR_EVENT],[G.IVS_PLAYER_NETWORK_UNAVAILABLE,oe.MAJOR_EVENT],[G.LIVESTREAM_LATENCY,oe.MAJOR_EVENT],[G.IVS_PLAYER_ANALYTICS_EVENT,oe.MINOR_EVENT],[G.IVS_PLAYER_PLAYBACK_RATE_CHANGED,oe.MINOR_EVENT],[G.IVS_PLAYER_QUALITY_CHANGED,oe.MINOR_EVENT],[G.IVS_PLAYER_INITIALIZED,oe.MINOR_EVENT],[G.EXPECTED_VIDEO_RESOLUTION,oe.MINOR_EVENT],[G.EXPECTED_SCREENSHARE_RESOLUTION,oe.MINOR_EVENT]]);class HS{constructor(){y(this,"events"),this.events=[]}add(e){this.events.push(e)}flush(){return{entries:this.events.splice(0,25)}}}class qS extends Nt{constructor({logger:e,peerId:n,apiHostnames:i}){super(),y(this,"logger"),y(this,"peerId"),y(this,"eventStore"),y(this,"apiEndpoint"),this.logger=e,this.peerId=n,this.apiEndpoint=`https://${i.daCollector}/api/v1/message`,this.eventStore=new HS}sendEventsChunkToServer(e){return p(this,null,function*(){var n;const i={payload:e,peerId:this.peerId};try{return yield fetch(this.apiEndpoint,{method:"POST",body:JSON.stringify(i)}),!0}catch(s){return this.logger.error("callStats::sendEventsChunkToServer::catch",{error:s}),(n=e.entries)==null||n.forEach(r=>{this.eventStore.add(r)}),!1}})}callEvent(e){e.timestamp=new Date,this.eventStore.add(e),this.emit(e.event,e.metaData),WS.get(e.event)===oe.MAJOR_EVENT&&this.flush()}flush(){return p(this,null,function*(){var e;const n=this.eventStore.flush();return(e=n==null?void 0:n.entries)!=null&&e.length?(yield this.sendEventsChunkToServer(n),!0):!1})}}var Nm;(function(t){t.CHROMIUM="chromum",t.FIREFOX="firefox",t.SAFARI="safari"})(Nm||(Nm={}));const Go={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var kn;(function(t){t.AUDIO="AUDIO",t.VIDEO="VIDEO",t.SPEAKER="SPEAKER",t.SCREENSHARE="SCREENSHARE"})(kn||(kn={}));var Lm;(function(t){t[t.INIT=0]="INIT",t[t.ACCEPTED=1]="ACCEPTED",t[t.DENIED=2]="DENIED",t[t.SYS_DENIED=3]="SYS_DENIED",t[t.FAILED=4]="FAILED",t[t.NOTFOUND=5]="NOTFOUND",t[t.NOT_APPLICABLE=6]="NOT_APPLICABLE"})(Lm||(Lm={}));function Es(t){return t?t.split(".").slice(0,2).concat(["0","0"]).join("."):""}function Xd({packetsLost:t,packetsSent:e}){return e>0?t*100/e:0}function Zd({packetsLost:t,packetsReceived:e}){return e+t>0?t*100/(e+t):0}const wv=240,_v=720,Iv=8,Cv=3,Ml=10,Ol=.02,Dl=.03;function Ci({stat:t,weight:e,rangeMin:n,rangeMax:i,rangeRankingDirection:s}){return t==null?e:n===i?s==="UP"?t<=n?e:0:t>=i?e:0:s==="UP"?(1-Math.max(Math.min(i,Math.abs(t))-n,0)/(i-n))*e:s==="DOWN"?Math.max(Math.min(i,Math.abs(t))-n,0)/(i-n)*e:e}function Rv({isLowQualityVideo:t,isVideoStuck:e,isVideoLagging:n,jitterQuality:i,packetsLostQuality:s}){const r=.8*((t?.85:1)*(n?.7:1)*(e?.5:1))+.2*(i*s);return Math.round((r+Number.EPSILON)*100)/100}function Pv({packetsLost:t,packetsSent:e}){return e>0?t*100/e:0}function Av({packetsLost:t,packetsSent:e,jitter:n}){const i=Ci({stat:Pv({packetsLost:t,packetsSent:e}),weight:.7,rangeMin:0,rangeMax:Ml,rangeRankingDirection:"UP"}),s=Ci({stat:n,weight:.3,rangeMin:Ol,rangeMax:Dl,rangeRankingDirection:"UP"});return i+s}function GS({frameWidth:t,isScreenShare:e}){return t<(e?_v:wv)}function $S({framesPerSecond:t,isScreenShare:e}){return t<(e?Cv:Iv)}function JS({framesEncoded:t}){return t===0}function Mv({frameWidth:t,framesPerSecond:e,packetsLost:n,packetsSent:i,jitter:s,isScreenShare:r,framesEncoded:a}){const c=Ci({stat:Pv({packetsLost:n,packetsSent:i}),weight:1,rangeMin:0,rangeMax:Ml,rangeRankingDirection:"UP"}),d=Ci({stat:s,weight:1,rangeMin:Ol,rangeMax:Dl,rangeRankingDirection:"UP"}),h=GS({frameWidth:t,isScreenShare:r}),u=$S({framesPerSecond:e,isScreenShare:r}),g=JS({framesEncoded:a,isScreenShare:r});return Rv({isLowQualityVideo:h,isVideoLagging:u,isVideoStuck:g,jitterQuality:d,packetsLostQuality:c})}function Ov({packetsLost:t,packetsReceived:e}){return e+t>0?t*100/(e+t):0}function Dv({concealmentEvents:t,packetsLost:e,packetsReceived:n,jitter:i}){const s=Ci({stat:t,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),r=.5,a=Ci({stat:Ov({packetsLost:e,packetsReceived:n}),weight:r,rangeMin:0,rangeMax:Ml,rangeRankingDirection:"UP"}),c=Ci({stat:i,weight:.3,rangeMin:Ol,rangeMax:Dl,rangeRankingDirection:"UP"});return s+a+c}function KS({framesDecoded:t}){return t===0}function zS({framesPerSecond:t,isScreenShare:e}){return t<(e?Cv:Iv)}function YS({frameWidth:t,isScreenShare:e}){return t<(e?_v:wv)}function Nv({frameWidth:t,framesPerSecond:e,packetsLost:n,packetsReceived:i,jitter:s,isScreenShare:r,framesDecoded:a}){const c=Ci({stat:Ov({packetsLost:n,packetsReceived:i}),weight:1,rangeMin:0,rangeMax:Ml,rangeRankingDirection:"UP"}),d=Ci({stat:s,weight:1,rangeMin:Ol,rangeMax:Dl,rangeRankingDirection:"UP"}),h=YS({frameWidth:t,isScreenShare:r}),u=zS({framesPerSecond:e,isScreenShare:r}),g=KS({framesDecoded:a,isScreenShare:r});return Rv({isLowQualityVideo:h,isVideoLagging:u,isVideoStuck:g,jitterQuality:d,packetsLostQuality:c})}class Ri{constructor(e){y(this,"pc1"),y(this,"pc2"),y(this,"constrainVideoBitrateKbps"),y(this,"constrainOfferToRemoveVideoFec",!1),y(this,"iceCandidateFilter");const n=new RTCPeerConnection(e),i=new RTCPeerConnection(e);this.pc1=n,this.pc2=i,this.iceCandidateFilter=Ri.noFilter,this.pc1.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc2)),this.pc2.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc1))}static parseCandidate(e){const n="candidate:",i=e.indexOf(n)+n.length,s=e.substr(i).split(" ");return{type:s[7],protocol:s[2],address:s[4]}}static isNotHostCandidate(e){return e.type!=="host"}static isHost(e){return e.type==="host"}static isRelay(e){return e.type==="relay"}static isReflexive(e){return e.type==="srflx"}static noFilter(e){return!0}onIceCandidate(e,n){if(n.candidate){const i=Ri.parseCandidate(n.candidate.candidate);this.iceCandidateFilter(i)&&e.addIceCandidate(n.candidate)}}setIceCandidateFilter(e){this.iceCandidateFilter=e}constrainVideoBitrate(e){this.constrainVideoBitrateKbps=e}disableVideoFec(){this.constrainOfferToRemoveVideoFec=!0}gotOffer(e){this.constrainOfferToRemoveVideoFec&&(e.sdp=e.sdp.replace(/(m=video 1 [^\r]+)(116 117)(\r\n)/g,`$1\r
10
+ `),e.sdp=e.sdp.replace(/a=rtpmap:116 red\/90000\r\n/g,""),e.sdp=e.sdp.replace(/a=rtpmap:117 ulpfec\/90000\r\n/g,""),e.sdp=e.sdp.replace(/a=rtpmap:98 rtx\/90000\r\n/g,""),e.sdp=e.sdp.replace(/a=fmtp:98 apt=116\r\n/g,"")),this.pc1.setLocalDescription(e),this.pc2.setRemoteDescription(e),this.pc2.createAnswer().then(this.gotAnswer.bind(this),this.reportFatal.bind(this))}gotAnswer(e){this.constrainVideoBitrateKbps&&(e.sdp=e.sdp.replace(/a=mid:video\r\n/g,`a=mid:video\r
11
+ b=AS:${this.constrainVideoBitrateKbps}\r
12
+ `)),this.pc2.setLocalDescription(e),this.pc1.setRemoteDescription(e)}establishConnection(){this.pc1.createOffer().then(this.gotOffer.bind(this),this.reportFatal.bind(this))}reportFatal(e){console.error("Error:",e)}getRoundTripTime(){return p(this,null,function*(){const[e,n]=yield Promise.all([this.pc1.getStats(),this.pc2.getStats()]);let i,s;if(e.forEach(r=>{r.type==="candidate-pair"&&r.nominated===!0&&r.bytesSent>0&&(i=r)}),n.forEach(r=>{r.type==="candidate-pair"&&r.nominated===!0&&r.bytesReceived>0&&(s=r)}),i&&s)try{if(i.currentRoundTripTime&&s.currentRoundTripTime)return{rtt:i.currentRoundTripTime,backendRTT:s.currentRoundTripTime};const r=(s.lastPacketReceivedTimestamp-i.lastPacketSentTimestamp)/1e3;return{rtt:r,backendRTT:r}}catch(r){return}})}close(){this.pc1.close(),this.pc2.close()}}class Lv extends Nt{constructor(e){super(),y(this,"call"),y(this,"timeOut"),this.call=new Ri(e)}start(e=1e4){this.call.establishConnection(),this.timeOut=setTimeout(this.testFailed.bind(this),e)}testComplete(e){clearTimeout(this.timeOut),this.call.close(),this.emit("done",e)}testFailed(e){this.call.close(),this.emit("failed",e)}}const QS=8,XS=1/1e3;class ZS extends Lv{constructor(e){super(e),y(this,"senderChannel"),y(this,"recieveChannel"),y(this,"startTime"),y(this,"lastBitrateMeasureTime"),y(this,"sentPayloadBytes",0),y(this,"recievedPayloadBytes",0),y(this,"lastReceivedPayloadBytes",0),y(this,"stopSending",!1),y(this,"testProgress",0),y(this,"samplePacket",""),y(this,"finalBitrateSum",0),y(this,"bitRateSampels",0),y(this,"maxNumberOfPacketsToSend",0),y(this,"bytesToKeepBuffered",0),y(this,"testDurationSeconds",5),this.call.setIceCandidateFilter(Ri.isNotHostCandidate),this.senderChannel=this.call.pc1.createDataChannel(null);for(let n=0;n<1024*256;n+=1)this.samplePacket+="h";this.maxNumberOfPacketsToSend=1,this.bytesToKeepBuffered=1024*this.maxNumberOfPacketsToSend,this.testDurationSeconds=4,this.senderChannel.addEventListener("open",this.sendingStep.bind(this)),this.call.pc2.addEventListener("datachannel",this.onRecieverChannel.bind(this))}sendingStep(){const e=new Date;this.startTime||(this.startTime=e,this.lastBitrateMeasureTime=e);for(let i=0;i!==this.maxNumberOfPacketsToSend&&!(this.senderChannel.bufferedAmount>=this.bytesToKeepBuffered);i+=1){this.sentPayloadBytes+=this.samplePacket.length;try{this.senderChannel.send(this.samplePacket)}catch(s){}}const n=e.getTime()-this.startTime.getTime();n>=1e3*this.testDurationSeconds?(this.stopSending=!0,this.testProgress=100):(this.testProgress=n/(10*this.testDurationSeconds),setTimeout(this.sendingStep.bind(this),1))}onMessageRecieved(e){this.recievedPayloadBytes+=e.data.length;const n=new Date,i=n.getTime()-this.lastBitrateMeasureTime.getTime();if(i>=1e3){const s=(this.recievedPayloadBytes-this.lastReceivedPayloadBytes)*QS/(i/1e3);this.finalBitrateSum+=s,this.bitRateSampels+=1,this.lastReceivedPayloadBytes=this.recievedPayloadBytes,this.lastBitrateMeasureTime=n}if(this.stopSending&&this.sentPayloadBytes===this.recievedPayloadBytes){const s=this.finalBitrateSum/this.bitRateSampels;this.testComplete({throughput:Math.round(s*XS)})}}testComplete(e){this.call.getRoundTripTime().then(({rtt:n,backendRTT:i})=>super.testComplete({RTT:n,backendRTT:i,throughput:e.throughput}))}onRecieverChannel(e){this.recieveChannel=e.channel,this.recieveChannel.addEventListener("message",this.onMessageRecieved.bind(this))}}class Np extends Lv{constructor(e,n=Ri.noFilter){super(e),y(this,"ch1"),y(this,"ch2"),this.call.setIceCandidateFilter(n);const i=this.call.pc1.createDataChannel(null);this.ch1=i,i.addEventListener("open",()=>{i.send("hello")}),i.addEventListener("message",this.onCh1Recieve.bind(this)),this.call.pc2.addEventListener("datachannel",this.dataChannelHandler.bind(this))}onCh1Recieve(e){e.data!=="world"?this.hangup("Invalid data transmitted."):this.testComplete({connectivity:!0})}onCh2Recieve(e){if(e.data!=="hello")this.hangup("Invalid data transmitted.");else try{this.ch2.send("world")}catch(n){}}dataChannelHandler(e){const n=e.channel;this.ch2=n,n.addEventListener("message",this.onCh2Recieve.bind(this))}hangup(e){this.testFailed(e)}}class eT extends Np{constructor(e){super(e,Ri.isHost)}}class tT extends Np{constructor(e){super(e,Ri.isRelay)}}class nT extends Np{constructor(e){super(e,Ri.isReflexive)}}class iT{constructor(){y(this,"ipInformation",null)}getIPDetails(e){return p(this,arguments,function*({peerId:n,apiHostnames:i,logger:s}){var r,a,c;if(!this.ipInformation){try{const d=`https://${i.location}`,h=yield(yield fetch(d)).json();if(((r=h.loc)==null?void 0:r.length)>5)return this.ipInformation=h,(a=this.ipInformation)!=null&&a.ip&&(this.ipInformation.ip=Es(this.ipInformation.ip)),h;throw Error("Insufficient data")}catch(d){s.error("callstats::ipDetails:: failed to fetch ip using location service",{error:d})}try{const d=yield fetch(`https://${i.locationLegacy}/?token=3c493932b0624c&peerId=${n}`,{method:"POST"});this.ipInformation=yield d.json(),(c=this.ipInformation)!=null&&c.ip&&(this.ipInformation.ip=Es(this.ipInformation.ip))}catch(d){s.error("callstats::ipDetails:: failed to fetch ip using legacy location service",{error:d})}}return this.ipInformation})}resetCache(){this.ipInformation=null}}const Lp=new iT,xm=[{urls:"turn:turn.dyte.in:443?transport=tcp",username:"dyte",credential:"dytein",credentialType:"password"},{urls:"turn:turn.dyte.in:3478?transport=udp",username:"dyte",credential:"dytein",credentialType:"password"}];function Vm(t){const[e,n]=t.split(",");return{coords:{latitude:Number(e),longitude:Number(n)}}}class xv{constructor(){y(this,"transport"),y(this,"candidatePair"),y(this,"outboundVideoRtp",new Map),y(this,"inboundVideoRtp",new Map),y(this,"outboundAudioRtp",new Map),y(this,"inboundAudioRtp",new Map),y(this,"remoteInboundRtp",new Map),y(this,"producerStreamMap",new Map),y(this,"consumerStreamMap",new Map),y(this,"staleProducerStreamMap",!1),y(this,"staleConsumerStreamMap",!1)}}class Vv extends Nt{constructor(){super(),y(this,"observer"),y(this,"outboundProducerMap",new Map),y(this,"inboundConsumerMap",new Map),y(this,"consumerPeerIdMap",new Map),y(this,"pausedConsumerMap",new Map),y(this,"pausedProducerMap",new Map),y(this,"overallProducingTransportsStatsMap",{}),y(this,"overallConsumingTransportsStatsMap",{}),y(this,"overallConsumersStatsMap",{}),y(this,"overallProducersStatsMap",{}),y(this,"videoProducerToStatsMap",new Map),y(this,"audioProducerToStatsMap",new Map),y(this,"videoConsumerToStatsMap",new Map),y(this,"audioConsumerToStatsMap",new Map),y(this,"consumerIdsWithFreezedVideo",new Set),y(this,"consumerIdsWithFreezedAudio",new Set),y(this,"producerIdsWithFreezedVideo",new Set),y(this,"producerIdsWithFreezedAudio",new Set),y(this,"freezedProducingTransportIds",new Set),y(this,"freezedConsumingTransportIds",new Set),y(this,"screenShareProducers",new Set),y(this,"screenShareConsumers",new Set),y(this,"ipDetails"),y(this,"callStatsInstance"),this.observer=new Nt}registerProducer(e){return p(this,null,function*(){yield this.generateProducerStreamMap(e),e.on("close",this.deregisterProducer.bind(this,e)),e.on("pause",this.pauseProducer.bind(this,e.id)),e.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)})}pauseProducer(e){this.pausedProducerMap.set(e,{lastReportCalculated:!1})}resumeProducer(e){this.pausedProducerMap.delete(e)}processInboundConsumerVideoStats(e,n,i){var s,r;const a=((r=(s=this==null?void 0:this.callStatsInstance)==null?void 0:s.consumerSharedMediaStatesMap)==null?void 0:r.get(e))||{};n.totalVideoPacketsReceived===i.packetsReceived?(this.consumerIdsWithFreezedVideo.add(e),this.callStatsInstance&&a.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","pause",e))):(n.totalVideoPacketsReceived=i.packetsReceived,this.consumerIdsWithFreezedVideo.has(e)&&(this.consumerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&a.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","resume",e))))}processInboundConsumerAudioStats(e,n,i){var s,r;const a=((r=(s=this==null?void 0:this.callStatsInstance)==null?void 0:s.consumerSharedMediaStatesMap)==null?void 0:r.get(e))||{};n.totalAudioPacketsReceived===i.packetsReceived?(this.consumerIdsWithFreezedAudio.add(e),this.callStatsInstance&&a.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","pause",e))):(n.totalAudioPacketsReceived=i.packetsReceived,this.consumerIdsWithFreezedAudio.has(e)&&(this.consumerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&a.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","resume",e))))}processOutboundProducerVideoStats(e,n,i){var s;const r=((s=this==null?void 0:this.callStatsInstance)==null?void 0:s.currentUserMediaStates)||{};n.totalVideoPacketsSent===i.packetsSent?(this.producerIdsWithFreezedVideo.add(e),this.callStatsInstance&&r.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","pause",e))):(n.totalVideoPacketsSent=i.packetsSent,this.producerIdsWithFreezedVideo.has(e)&&(this.producerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&r.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","resume",e))))}processOutboundProducerAudioStats(e,n,i){var s;const r=((s=this==null?void 0:this.callStatsInstance)==null?void 0:s.currentUserMediaStates)||{};n.totalAudioPacketsSent===i.packetsSent?(this.producerIdsWithFreezedAudio.add(e),this.callStatsInstance&&r.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","pause",e))):(n.totalAudioPacketsSent=i.packetsSent,this.producerIdsWithFreezedAudio.has(e)&&(this.producerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&r.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","resume",e))))}processProducingTransportStats(e,n,i){var s;const r=((s=this==null?void 0:this.callStatsInstance)==null?void 0:s.currentUserMediaStates)||{},{audio:a,video:c,screen:d}=r,h=a||c||d;n.totalPacketsSent===i.packetsSent?(this.freezedProducingTransportIds.add(e),this.callStatsInstance&&h&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","pause",e))):(n.totalPacketsSent=i.packetsSent,this.freezedProducingTransportIds.has(e)&&(this.freezedProducingTransportIds.delete(e),this.callStatsInstance&&h&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","resume",e))))}processConsumingTransportStats(e,n,i){var s,r;const a=!!Array.from(((r=(s=this==null?void 0:this.callStatsInstance)==null?void 0:s.consumerSharedMediaStatesMap)==null?void 0:r.values())||[]).reduce((c,d)=>c||d.audio||d.video||d.screen,!1);n.totalPacketsReceived===i.packetsSent?(this.freezedConsumingTransportIds.add(e),this.callStatsInstance&&a&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","pause",e))):(n.totalPacketsReceived=i.packetsSent,this.freezedConsumingTransportIds.has(e)&&(this.freezedConsumingTransportIds.delete(e),this.callStatsInstance&&a&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","resume",e))))}registerConsumer(e){return p(this,null,function*(){yield this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.on("close",this.deregisterConsumer.bind(this,e)),e.on("pause",this.pauseConsumer.bind(this,e.id)),e.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)})}pauseConsumer(e){this.pausedConsumerMap.set(e,{lastReportCalculated:!1})}resumeConsumer(e){this.pausedConsumerMap.delete(e)}generateProducerStreamMap(e,n=!1){return p(this,null,function*(){const i=yield e.getStats(),s=n?this.getProducerStatsFromReport(this.parseRTCReport(i,["outbound-rtp","remote-inbound-rtp"],!1,e.id))[0]:void 0;for(const r of i.values())switch(r.type){case"outbound-rtp":{this.outboundProducerMap.set(r.id,e.id);break}}return s})}generateConsumerStreamMap(e,n=!1){return p(this,null,function*(){const i=yield e.getStats(),s=n?this.getConsumerStatsFromReport(this.parseRTCReport(i,["inbound-rtp"],!1,e.id))[0]:void 0;for(const r of i.values())switch(r.type){case"inbound-rtp":{this.inboundConsumerMap.set(r.id,e.id);break}}return s})}deregisterProducer(e){this.outboundProducerMap.forEach((n,i)=>{n===e.id&&this.outboundProducerMap.delete(i)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.inboundConsumerMap.forEach((n,i)=>{n===e.id&&this.inboundConsumerMap.delete(i)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var n;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(n=e.relayProtocol)!=null?n:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}getWorkingSimulcastVideoStats(e){return e.find(n=>{const i=n.framesEncoded>0,s=n.packetsSent>0,r=n.frameWidth&&n.frameHeight;return i&&s&&!!r})||e[e.length-1]}parseRTCReport(e,n=[],i=!1,s=void 0,r=void 0){var a,c,d,h,u,g,E,b,w,M,D,F,Y;const X=e,A=new xv,$=n.length?new Set(n):void 0,me=[],Ie=[],fe=[],Je=new Map,ht=new Map;for(const V of X.values()){if($){if($.size===0)break;if($.has(V.type))i&&$.delete(V.type);else continue}switch(V.type){case"local-candidate":{me.push(this.getIceCandidateStats(V));break}case"remote-candidate":{Ie.push(this.getIceCandidateStats(V));break}case"candidate-pair":{const{nominated:I}=V,{selected:P}=V,K=V,ye={nominated:I!=null?I:P,currentRoundTripTime:K.currentRoundTripTime,totalRoundTripTime:K.totalRoundTripTime,bytesReceived:K.bytesReceived,bytesSent:K.bytesSent,availableOutgoingBitrate:K.availableOutgoingBitrate,availableIncomingBitrate:K.availableIncomingBitrate,lastPacketReceivedTimestamp:K.lastPacketReceivedTimestamp,lastPacketSentTimestamp:K.lastPacketSentTimestamp,localCandidateId:K.localCandidateId,remoteCandidateId:K.remoteCandidateId,bytesDiscardedOnSend:K.bytesDiscardedOnSend,packetsSent:K.packetsSent,packetsReceived:K.packetsReceived,packetsDiscardedOnSend:K.packetsDiscardedOnSend};fe.push(ye),(V.nominated===!0||V.selected===!0)&&(A.candidatePair=ye);break}case"transport":{const I=V;r&&(r.producing&&(this.overallProducingTransportsStatsMap[r.id]||(this.overallProducingTransportsStatsMap[r.id]={totalPacketsSent:0})),r.consuming&&(this.overallConsumingTransportsStatsMap[r.id]||(this.overallConsumingTransportsStatsMap[r.id]={totalPacketsReceived:0})));const P={bytesReceived:I.bytesReceived,bytesSent:I.bytesSent,packetsSent:I.packetsSent,packetsReceived:I.packetsReceived,dtlsCipher:I.dtlsCipher,dtlsState:I.dtlsState,iceRole:I.iceRole};if(A.transport=P,r){if(r.producing){const K=this.overallProducingTransportsStatsMap[r.id];this.processProducingTransportStats(r.id,K,P)}if(r.consuming){const K=this.overallConsumingTransportsStatsMap[r.id];this.processConsumingTransportStats(r.id,K,P)}}break}case"remote-inbound-rtp":{const I=V,P={jitter:I.jitter,fractionLost:I.fractionLost,roundTripTime:I.roundTripTime,roundTripTimeMeasurements:I.roundTripTimeMeasurements,totalRoundTripTime:I.totalRoundTripTime,packetsLost:I.packetsLost};A.remoteInboundRtp.set(I.localId,P);break}case"outbound-rtp":{const I=V,P=s||this.outboundProducerMap.get(V.id),K=this.pausedProducerMap.get(P);if(K){if(K.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const ye=this.overallProducersStatsMap[P];if(["video","audio"].includes(I.mediaType)||["video","audio"].includes(I.kind)){if(!this.outboundProducerMap.has(V.id)){A.staleProducerStreamMap=!0;break}const Xe=this.callStatsInstance.producers.get(P);if(((a=Xe==null?void 0:Xe.track)==null?void 0:a.readyState)==="ended")break;A.producerStreamMap.has(P)||A.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const q={bytesSent:I.bytesSent,packetsSent:I.packetsSent,nackCount:I.nackCount,ssrc:I.ssrc,mid:I.mid,active:I.active,codecId:I.codecId,headerBytesSent:I.headerBytesSent||0,totalPacketSendDelay:I.totalPacketSendDelay||0};if(I.mediaType==="video"||I.kind==="video"){const N=I,Ze=H({frameHeight:N.frameHeight,frameWidth:N.frameWidth,framesEncoded:N.framesEncoded,framesDropped:N.framesDropped,framesPerSecond:N.framesPerSecond,framesSent:N.framesSent,keyFramesEncoded:N.keyFramesEncoded,firCount:N.firCount,encoderImplementation:N.encoderImplementation,hugeFramesSent:N.hugeFramesSent,pliCount:N.pliCount,qpSum:N.qpSum,qualityLimitationDurations:N.qualityLimitationDurations,qualityLimitationReason:N.qualityLimitationReason,qualityLimitationResolutionChanges:N.qualityLimitationResolutionChanges,totalEncodeTime:N.targetBitrate,totalPacketSendDelay:N.totalPacketSendDelay,retransmittedBytesSent:N.retransmittedBytesSent,retransmittedPacketsSent:N.retransmittedPacketsSent,scalabilityMode:N.scalabilityMode,powerEfficientEncoder:N.powerEfficientEncoder},q);A.outboundVideoRtp.set(V.id,Ze),A.producerStreamMap.get(P).outboundVideoRtpId.push(V.id),this.processOutboundProducerVideoStats(P,ye,Ze)}else if(I.mediaType==="audio"||I.kind==="audio"){const N=I,Ze=H({retransmittedBytesSent:N.retransmittedBytesSent,retransmittedPacketsSent:N.retransmittedPacketsSent},q);A.outboundAudioRtp.set(V.id,Ze),A.producerStreamMap.get(P).outboundAudioRtpId.push(V.id),this.processOutboundProducerAudioStats(P,ye,Ze)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${I.mediaType} kind: ${I.kind}`);break}case"inbound-rtp":{const I=V,P=s||this.inboundConsumerMap.get(V.id),K=this.pausedConsumerMap.get(P);if(K){if(K.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(I.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const ye=this.overallConsumersStatsMap[P];if(["video","audio"].includes(I.mediaType)||["video","audio"].includes(I.kind)){if(!this.inboundConsumerMap.has(V.id)){A.staleConsumerStreamMap=!0;break}A.consumerStreamMap.has(P)||A.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Xe={bytesReceived:I.bytesReceived,packetsReceived:I.packetsReceived,packetsLost:I.packetsLost>=0?I.packetsLost:0,jitter:I.jitter,nackCount:I.nackCount,jitterBufferDelay:I.jitterBufferDelay,jitterBufferEmittedCount:I.jitterBufferEmittedCount,lastPacketReceivedTimestamp:I.lastPacketReceivedTimestamp,ssrc:I.ssrc,mid:I.mid,codecId:I.codecId,headerBytesReceived:I.headerBytesReceived||0,packetsDiscarded:I.packetsDiscarded||0,jitterBufferMinimumDelay:I.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:I.jitterBufferTargetDelay||0};if(I.mediaType==="video"||I.kind==="video"){const q=I,N=H({frameHeight:q.frameHeight,frameWidth:q.frameWidth,framesDecoded:q.framesDecoded,framesDropped:q.framesDropped,framesPerSecond:q.framesPerSecond,framesReceived:q.framesReceived,keyFramesDecoded:q.keyFramesDecoded,firCount:q.firCount,decoderImplementation:q.decoderImplementation,pliCount:q.pliCount,totalProcessingDelay:q.totalProcessingDelay,qpSum:q.qpSum||0,totalAssemblyTime:q.totalAssemblyTime||0,totalDecodeTime:q.totalDecodeTime||0,totalFreezesDuration:q.totalFreezesDuration||0,totalInterFrameDelay:q.totalInterFrameDelay||0,totalPausesDuration:q.totalPausesDuration||0,totalSquaredInterFrameDelay:q.totalSquaredInterFrameDelay||0,freezeCount:q.freezeCount||0,pauseCount:q.pauseCount||0,powerEfficientDecoder:q.powerEfficientDecoder},Xe);N.score=Nv({frameWidth:N.frameWidth||0,framesDecoded:(N.framesDecoded||0)-(((c=this.videoConsumerToStatsMap.get(P))==null?void 0:c.framesDecoded)||0),framesPerSecond:N.framesPerSecond||0,packetsLost:(N.packetsLost||0)-(((d=this.videoConsumerToStatsMap.get(P))==null?void 0:d.packetsLost)||0),packetsReceived:(N.packetsReceived||0)-(((h=this.videoConsumerToStatsMap.get(P))==null?void 0:h.packetsReceived)||0),jitter:N.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),ht.set(P,{score:+(N.score*10).toFixed(),frameWidth:N.frameWidth||0,frameHeight:N.frameHeight||0,framesPerSecond:N.framesPerSecond||0,packetsLostPercentage:Zd({packetsLost:(N.packetsLost||0)-(((u=this.videoConsumerToStatsMap.get(P))==null?void 0:u.packetsLost)||0),packetsReceived:(N.packetsReceived||0)-(((g=this.videoConsumerToStatsMap.get(P))==null?void 0:g.packetsReceived)||0)}),jitter:N.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((N.bytesReceived||0)-(((E=this.videoConsumerToStatsMap.get(P))==null?void 0:E.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,N),A.inboundVideoRtp.set(V.id,N),A.consumerStreamMap.get(P).inboundVideoRtpId.push(V.id),this.processInboundConsumerVideoStats(P,ye,N)}else if(I.mediaType==="audio"||I.kind==="audio"){const q=I,N=H({audioLevel:q.audioLevel,concealedSamples:q.concealedSamples,concealmentEvents:q.concealmentEvents,totalAudioEnergy:q.totalAudioEnergy,totalSamplesDuration:q.totalSamplesDuration,totalSamplesReceived:q.totalSamplesReceived,fecPacketsDiscarded:q.fecPacketsDiscarded||0,fecPacketsReceived:q.fecPacketsReceived||0,insertedSamplesForDeceleration:q.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:q.removedSamplesForAcceleration||0,silentConcealedSamples:q.silentConcealedSamples||0,playoutId:q.playoutId},Xe);N.score=Dv({concealmentEvents:(N.concealmentEvents||0)-(((b=this.audioConsumerToStatsMap.get(P))==null?void 0:b.concealmentEvents)||0),packetsLost:(N.packetsLost||0)-(((w=this.audioConsumerToStatsMap.get(P))==null?void 0:w.packetsLost)||0),packetsReceived:(N.packetsReceived||0)-(((M=this.audioConsumerToStatsMap.get(P))==null?void 0:M.packetsReceived)||0),jitter:N.jitter||0}),ht.set(P,{score:+(N.score*10).toFixed(),packetsLostPercentage:Zd({packetsLost:(N.packetsLost||0)-(((D=this.audioConsumerToStatsMap.get(P))==null?void 0:D.packetsLost)||0),packetsReceived:(N.packetsReceived||0)-(((F=this.audioConsumerToStatsMap.get(P))==null?void 0:F.packetsReceived)||0)}),jitter:N.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((N.bytesReceived||0)-(((Y=this.audioConsumerToStatsMap.get(P))==null?void 0:Y.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,N),A.inboundAudioRtp.set(V.id,N),A.consumerStreamMap.get(P).inboundAudioRtpId.push(V.id),this.processInboundConsumerAudioStats(P,ye,N)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${I.mediaType} kind: ${I.kind}`);break}}}if(A.producerStreamMap.forEach((V,I)=>{var P,K,ye,Xe,q,N,Ze,Rn,Ps,As,Ms,Fe,at,Ni,Li,xi,Vi,Ui,En,hi,Bi,Os,Fi;if(V.outboundVideoRtpId.length>0){const ge=[];V.outboundVideoRtpId.forEach(Oa=>{ge.push(A.outboundVideoRtp.get(Oa))});const pe=this.getWorkingSimulcastVideoStats(ge);pe.score=Mv({frameWidth:pe.frameWidth||0,framesPerSecond:pe.framesPerSecond||0,jitter:((P=pe.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(I),packetsSent:(pe.packetsSent||0)-(((K=this.videoProducerToStatsMap.get(I))==null?void 0:K.packetsSent)||0),packetsLost:(((ye=pe.remoteData)==null?void 0:ye.packetsLost)||0)-(((q=(Xe=this.videoProducerToStatsMap.get(I))==null?void 0:Xe.remoteData)==null?void 0:q.packetsLost)||0),framesEncoded:(pe.framesEncoded||0)-(((N=this.videoProducerToStatsMap.get(I))==null?void 0:N.framesEncoded)||0)}),Je.set(I,{score:+(pe.score*10).toFixed(),frameWidth:pe.frameWidth||0,frameHeight:pe.frameHeight||0,framesPerSecond:pe.framesPerSecond||0,jitter:((Ze=pe.remoteData)==null?void 0:Ze.jitter)||0,isScreenShare:this.screenShareProducers.has(I),packetsLostPercentage:Xd({packetsSent:(pe.packetsSent||0)-(((Rn=this.videoProducerToStatsMap.get(I))==null?void 0:Rn.packetsSent)||0),packetsLost:(((Ps=pe.remoteData)==null?void 0:Ps.packetsLost)||0)-(((Ms=(As=this.videoProducerToStatsMap.get(I))==null?void 0:As.remoteData)==null?void 0:Ms.packetsLost)||0)}),bitrate:((pe.bytesSent||0)-(((Fe=this.videoProducerToStatsMap.get(I))==null?void 0:Fe.bytesSent)||0))*8/7,cpuLimitations:pe.qualityLimitationReason==="cpu",bandwidthLimitations:pe.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(I,pe)}else if(V.outboundAudioRtpId.length>0){const ge=A.outboundAudioRtp.get(V.outboundAudioRtpId[0]);ge.score=Av({packetsSent:(ge.packetsSent||0)-(((at=this.audioProducerToStatsMap.get(I))==null?void 0:at.packetsSent)||0),packetsLost:(((Ni=ge.remoteData)==null?void 0:Ni.packetsLost)||0)-(((xi=(Li=this.audioProducerToStatsMap.get(I))==null?void 0:Li.remoteData)==null?void 0:xi.packetsLost)||0),jitter:((Vi=ge.remoteData)==null?void 0:Vi.jitter)||0}),Je.set(I,{score:+(ge.score*10).toFixed(),bitrate:((ge.bytesSent||0)-(((Ui=this.audioProducerToStatsMap.get(I))==null?void 0:Ui.bytesSent)||0))*8/7,packetsLostPercentage:Xd({packetsSent:(ge.packetsSent||0)-(((En=this.audioProducerToStatsMap.get(I))==null?void 0:En.packetsSent)||0),packetsLost:(((hi=ge.remoteData)==null?void 0:hi.packetsLost)||0)-(((Os=(Bi=this.audioProducerToStatsMap.get(I))==null?void 0:Bi.remoteData)==null?void 0:Os.packetsLost)||0)}),jitter:((Fi=ge.remoteData)==null?void 0:Fi.jitter)||0,isScreenShare:this.screenShareProducers.has(I)}),this.audioProducerToStatsMap.set(I,ge)}}),fe.forEach(V=>{const I=me.find(K=>K.id===V.localCandidateId?(V.localCandidateId=K.id,K):null),P=Ie.find(K=>K.id===V.remoteCandidateId?(V.remoteCandidateId=K.id,K):null);I&&(V.localCandidateType=I.type,V.localCandidateAddress=Es(I.address),V.localCandidatePort=I.port,V.localCandidateProtocol=I.protocol,V.localCandidateUrl=I.url,V.localCandidateNetworkType=I.networkType,V.localCandidateRelatedAddress=Es(I.relatedAddress),V.localCandidateRelatedPort=I.relatedPort),P&&(V.remoteCandidateType=P.type,V.remoteCandidateAddress=Es(P.address),V.remoteCandidatePort=P.port,V.remoteCandidateProtocol=P.protocol,V.remoteCandidateUrl=P.url)}),A.candidatePair&&(A.transport?(A.transport.totalRoundTripTime=A.candidatePair.totalRoundTripTime,A.transport.availableOutgoingBitrate=A.candidatePair.availableOutgoingBitrate,A.transport.availableIncomingBitrate=A.candidatePair.availableIncomingBitrate,A.transport.roundTripTime=A.candidatePair.currentRoundTripTime):A.transport={bytesReceived:A.candidatePair.bytesReceived,bytesSent:A.candidatePair.bytesSent,totalRoundTripTime:A.candidatePair.totalRoundTripTime,availableOutgoingBitrate:A.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:A.candidatePair.availableIncomingBitrate,roundTripTime:A.candidatePair.currentRoundTripTime}),A.transport&&(A.transport.candidatePairs=fe),A.transport&&!A.transport.roundTripTime){let V=0,I=0;A.remoteInboundRtp.forEach((P,K)=>{P.roundTripTime&&P.roundTripTime>V&&(V=P.roundTripTime,I=P.totalRoundTripTime)}),A.transport.roundTripTime=V,A.transport.totalRoundTripTime=I}if(ht.size>0)try{this.observer.emit("consumer_score",ht)}catch(V){}if(Je.size>0)try{this.observer.emit("producer_score",Je)}catch(V){}return A}getProducersReport(e){return p(this,null,function*(){const n=e.map(i=>this.generateProducerStreamMap(i,!0));return n.length>0?Promise.all(n):void 0})}getConsumersReport(e){return p(this,null,function*(){const n=e.map(i=>this.generateConsumerStreamMap(i,!0));return n.length>0?Promise.all(n):void 0})}getTransportReport(e){return p(this,null,function*(){return e.getStats()})}getProcessedStats(e,n,i){return p(this,null,function*(){const s=yield this.getTransportReport(e),r={producing:i,consuming:n,id:e.id},a=s,c=this.parseRTCReport(a,["transport","candidate-pair","inbound-rtp","outbound-rtp","remote-inbound-rtp","local-candidate","remote-candidate"],!1,void 0,r);if(!c)return;const d={stats:c.transport,transportId:e.id,consuming:n,producing:i},h=c.staleProducerStreamMap?void 0:this.getProducerStatsFromReport(c),u=c.staleConsumerStreamMap?void 0:this.getConsumerStatsFromReport(c);return{transportReport:d,producerReport:h,consumerReport:u}})}getProducerStatsFromReport(e){const n=[];try{e.producerStreamMap.forEach((i,s)=>{var r,a;n.push({producerId:s,videoStats:i.outboundVideoRtpId.map(c=>e.outboundVideoRtp.get(c)),audioStats:i.outboundAudioRtpId.map(c=>e.outboundAudioRtp.get(c)),appData:((a=(r=this.callStatsInstance.producers)==null?void 0:r.get(s))==null?void 0:a.appData)||null})})}catch(i){this.callStatsInstance.logger.error("callStats::measurements::getProducerStatsFromReport",{error:{reason:i.reason,message:i.message}})}return n}getConsumerStatsFromReport(e){const n=[];try{e.consumerStreamMap.forEach((i,s)=>{const{peerId:r,producerId:a,appData:c}=this.consumerPeerIdMap.get(s);n.push({consumerId:s,peerId:r,producerId:a,appData:c,videoStats:i.inboundVideoRtpId.map(d=>e.inboundVideoRtp.get(d)),audioStats:i.inboundAudioRtpId.map(d=>e.inboundAudioRtp.get(d))})})}catch(i){console.error("getConsumersReport: ",i,e)}return n}getUserLocation(){return p(this,null,function*(){return new Promise((e,n)=>{try{navigator.geolocation?navigator.geolocation.getCurrentPosition(i=>{e(i)}):n()}catch(i){n(i)}})})}getConnectivity(e){return p(this,null,function*(){try{const n={iceServers:e||xm},i=new Promise((h,u)=>{try{const g=new eT(n);g.addListener("done",h),g.addListener("failed",()=>{h({connectivity:!1})}),g.start(2e3)}catch(g){u(g)}}),s=new Promise((h,u)=>{try{const g=new tT(n);g.addListener("done",h),g.addListener("failed",()=>{h({connectivity:!1})}),g.start(2e3)}catch(g){u(g)}}),r=new Promise((h,u)=>{try{const g=new nT(n);g.addListener("done",h),g.addListener("failed",()=>{h({connectivity:!1})}),g.start(2e3)}catch(g){u(g)}}),[a,c,d]=yield Promise.all([i,s,r]);return{host:a==null?void 0:a.connectivity,relay:c==null?void 0:c.connectivity,reflexive:d==null?void 0:d.connectivity}}catch(n){return{host:!1,relay:!1,reflexive:!1}}})}getThroughput(e){return p(this,null,function*(){try{const n=yield new Promise((i,s)=>{try{const r={iceServers:e||xm},a=new ZS(r);a.addListener("done",i),a.addListener("failed",s),a.start(1e4)}catch(r){s(r)}});return{throughput:n.throughput,fractionalLoss:0,RTT:n.RTT,jitter:0,backendRTT:n.backendRTT}}catch(n){return}})}getIPDetails(){return p(this,null,function*(){var e,n;try{return this.ipDetails||(this.ipDetails=yield Lp.getIPDetails({peerId:(e=this.callStatsInstance)==null?void 0:e.peerId,apiHostnames:(n=this.callStatsInstance)==null?void 0:n.apiHostnames,logger:this.callStatsInstance.logger})),this.ipDetails}catch(i){return}})}getNetworkQuality(e){return p(this,null,function*(){const[n,i]=yield Promise.all([this.getConnectivity(e),this.getThroughput(e)]);return{connectivity:n,throughput:i==null?void 0:i.throughput,fractionalLoss:i==null?void 0:i.fractionalLoss,RTT:i==null?void 0:i.RTT,jitter:i==null?void 0:i.jitter,backendRTT:i==null?void 0:i.backendRTT}})}getNetworkInfo(e,n=!1){return p(this,null,function*(){var i,s;if(n){const d=yield this.getIPDetails();return{ipDetails:d,effectiveNetworkType:(i=navigator.connection)==null?void 0:i.effectiveType,location:d!=null&&d.loc?Vm(d==null?void 0:d.loc):void 0}}const[r,a,c]=yield Promise.all([this.getConnectivity(e),this.getThroughput(e),this.getIPDetails()]);return{ipDetails:c,effectiveNetworkType:(s=navigator.connection)==null?void 0:s.effectiveType,location:c!=null&&c.loc?Vm(c==null?void 0:c.loc):void 0,turnConnectivity:r?r.host||r.relay||r.reflexive:!1,connectivity:r,throughput:a==null?void 0:a.throughput,fractionalLoss:a==null?void 0:a.fractionalLoss,RTT:a==null?void 0:a.RTT,jitter:a==null?void 0:a.jitter,backendRTT:a==null?void 0:a.backendRTT}})}}class sT extends Vv{}class Uv extends Vv{constructor(){super(...arguments),y(this,"producerMap",new Map),y(this,"consumerMap",new Map)}registerProducer(e){return p(this,null,function*(){this.producerMap.set(e.id,e),yield this.generateProducerStreamMap(e),e.on("close",this.deregisterProducer.bind(this,e)),e.on("pause",this.pauseProducer.bind(this,e.id)),e.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)})}registerConsumer(e){return p(this,null,function*(){this.consumerMap.set(e.id,e),yield this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.on("close",this.deregisterConsumer.bind(this,e)),e.on("pause",this.pauseConsumer.bind(this,e.id)),e.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)})}generateConsumerStreamMap(e,n=!1){return p(this,null,function*(){const i=yield e.getStats(),s=this.parseRTCReport(i,["inbound-rtp"],!1,e.id),r=[...s.consumerStreamMap.values()][0],a=n?this.getConsumerStatsFromParsedConsumerStats(s,r,e.id):void 0;for(const c of i.values())switch(c.type){case"inbound-rtp":{this.inboundConsumerMap.set(c.id,e.id);break}}return a})}deregisterProducer(e){this.producerMap.delete(e.id),this.outboundProducerMap.forEach((n,i)=>{n===e.id&&this.outboundProducerMap.delete(i)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.consumerMap.delete(e.id),this.inboundConsumerMap.forEach((n,i)=>{n===e.id&&this.inboundConsumerMap.delete(i)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var n;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(n=e.relayProtocol)!=null?n:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}parseRTCReport(e,n=[],i=!1,s=void 0,r=void 0){var a,c,d,h,u,g,E,b,w,M,D,F,Y;const X=e,A=new xv,$=n.length?new Set(n):void 0,me=[],Ie=[],fe=[],Je=new Map,ht=new Map;for(const V of X.values()){if($){if($.size===0)break;if($.has(V.type))i&&$.delete(V.type);else continue}switch(V.type){case"local-candidate":{me.push(this.getIceCandidateStats(V));break}case"remote-candidate":{Ie.push(this.getIceCandidateStats(V));break}case"candidate-pair":{const{nominated:I}=V,{selected:P}=V,K=V,ye={nominated:I!=null?I:P,currentRoundTripTime:K.currentRoundTripTime,totalRoundTripTime:K.totalRoundTripTime,bytesReceived:K.bytesReceived,bytesSent:K.bytesSent,availableOutgoingBitrate:K.availableOutgoingBitrate,availableIncomingBitrate:K.availableIncomingBitrate,lastPacketReceivedTimestamp:K.lastPacketReceivedTimestamp,lastPacketSentTimestamp:K.lastPacketSentTimestamp,localCandidateId:K.localCandidateId,remoteCandidateId:K.remoteCandidateId,bytesDiscardedOnSend:K.bytesDiscardedOnSend,packetsSent:K.packetsSent,packetsReceived:K.packetsReceived,packetsDiscardedOnSend:K.packetsDiscardedOnSend};fe.push(ye),(V.nominated===!0||V.selected===!0)&&(A.candidatePair=ye);break}case"transport":{const I=V;r&&(r.producing&&(this.overallProducingTransportsStatsMap[r.id]||(this.overallProducingTransportsStatsMap[r.id]={totalPacketsSent:0})),r.consuming&&(this.overallConsumingTransportsStatsMap[r.id]||(this.overallConsumingTransportsStatsMap[r.id]={totalPacketsReceived:0})));const P={bytesReceived:I.bytesReceived,bytesSent:I.bytesSent,packetsSent:I.packetsSent,packetsReceived:I.packetsReceived,dtlsCipher:I.dtlsCipher,dtlsState:I.dtlsState,iceRole:I.iceRole};if(A.transport=P,r){if(r.producing){const K=this.overallProducingTransportsStatsMap[r.id];this.processProducingTransportStats(r.id,K,P)}if(r.consuming){const K=this.overallConsumingTransportsStatsMap[r.id];this.processConsumingTransportStats(r.id,K,P)}}break}case"remote-inbound-rtp":{const I=V,P={jitter:I.jitter,fractionLost:I.fractionLost,roundTripTime:I.roundTripTime,roundTripTimeMeasurements:I.roundTripTimeMeasurements,totalRoundTripTime:I.totalRoundTripTime,packetsLost:I.packetsLost};A.remoteInboundRtp.set(I.localId,P);break}case"outbound-rtp":{const I=V,P=s||this.outboundProducerMap.get(V.id),K=this.pausedProducerMap.get(P);if(K){if(K.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const ye=this.overallProducersStatsMap[P];if(["video","audio"].includes(I.mediaType)||["video","audio"].includes(I.kind)){if(!this.outboundProducerMap.has(V.id)){A.staleProducerStreamMap=!0;break}const Xe=this.callStatsInstance.producers.get(P);if(((a=Xe==null?void 0:Xe.track)==null?void 0:a.readyState)==="ended")break;A.producerStreamMap.has(P)||A.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const q={bytesSent:I.bytesSent,packetsSent:I.packetsSent,nackCount:I.nackCount,ssrc:I.ssrc,mid:I.mid,active:I.active,codecId:I.codecId,headerBytesSent:I.headerBytesSent||0,totalPacketSendDelay:I.totalPacketSendDelay||0};if(I.mediaType==="video"||I.kind==="video"){const N=I,Ze=H({frameHeight:N.frameHeight,frameWidth:N.frameWidth,framesEncoded:N.framesEncoded,framesDropped:N.framesDropped?N.framesDropped:N.droppedFrames,framesPerSecond:N.framesPerSecond?N.framesPerSecond:N.framerateMean,framesSent:N.framesSent,keyFramesEncoded:N.keyFramesEncoded,firCount:N.firCount,encoderImplementation:N.encoderImplementation,hugeFramesSent:N.hugeFramesSent,pliCount:N.pliCount,qpSum:N.qpSum,qualityLimitationReason:N.qualityLimitationReason,qualityLimitationDurations:N.qualityLimitationDurations,qualityLimitationResolutionChanges:N.qualityLimitationResolutionChanges,totalEncodeTime:N.totalEncodeTime,totalPacketSendDelay:N.totalEncodeTime,retransmittedBytesSent:N.retransmittedBytesSent,retransmittedPacketsSent:N.retransmittedPacketsSent,scalabilityMode:N.scalabilityMode,powerEfficientEncoder:N.powerEfficientEncoder},q);A.outboundVideoRtp.set(V.id,Ze),A.producerStreamMap.get(P).outboundVideoRtpId.push(V.id),this.processOutboundProducerVideoStats(P,ye,Ze)}else if(I.mediaType==="audio"||I.kind==="audio"){const N=I,Ze=H({retransmittedBytesSent:N.retransmittedBytesSent,retransmittedPacketsSent:N.retransmittedPacketsSent},q);A.outboundAudioRtp.set(V.id,Ze),A.producerStreamMap.get(P).outboundAudioRtpId.push(V.id),this.processOutboundProducerAudioStats(P,ye,Ze)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${I.mediaType} kind: ${I.kind}`);break}case"inbound-rtp":{const I=V,P=s||this.inboundConsumerMap.get(V.id),K=this.pausedConsumerMap.get(P);if(K){if(K.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(I.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const ye=this.overallConsumersStatsMap[P];if(["video","audio"].includes(I.mediaType)||["video","audio"].includes(I.kind)){if(!this.inboundConsumerMap.has(V.id)){A.staleConsumerStreamMap=!0;break}A.consumerStreamMap.has(P)||A.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Xe={bytesReceived:I.bytesReceived,packetsReceived:I.packetsReceived,packetsLost:I.packetsLost>=0?I.packetsLost:0,jitter:I.jitter,nackCount:I.nackCount,jitterBufferDelay:I.jitterBufferDelay,jitterBufferEmittedCount:I.jitterBufferEmittedCount,lastPacketReceivedTimestamp:I.lastPacketReceivedTimestamp,ssrc:I.ssrc,mid:I.mid,codecId:I.codecId,headerBytesReceived:I.headerBytesReceived||0,packetsDiscarded:I.packetsDiscarded||0,jitterBufferMinimumDelay:I.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:I.jitterBufferTargetDelay||0};if(I.mediaType==="video"||I.kind==="video"){const q=I,N=H({frameHeight:q.frameHeight,frameWidth:q.frameWidth,framesDecoded:q.framesDecoded,framesDropped:q.framesDropped?q.framesDropped:q.droppedFrames,framesPerSecond:q.framesPerSecond?q.framesPerSecond:q.framerateMean,framesReceived:q.framesReceived,keyFramesDecoded:q.keyFramesDecoded,firCount:q.firCount,decoderImplementation:q.decoderImplementation,pliCount:q.pliCount,totalProcessingDelay:q.totalProcessingDelay,qpSum:q.qpSum||0,totalAssemblyTime:q.totalAssemblyTime||0,totalDecodeTime:q.totalDecodeTime||0,totalFreezesDuration:q.totalFreezesDuration||0,totalInterFrameDelay:q.totalInterFrameDelay||0,totalPausesDuration:q.totalPausesDuration||0,totalSquaredInterFrameDelay:q.totalSquaredInterFrameDelay||0,freezeCount:q.freezeCount||0,pauseCount:q.pauseCount||0,powerEfficientDecoder:q.powerEfficientDecoder},Xe);N.score=Nv({frameWidth:N.frameWidth||0,framesDecoded:(N.framesDecoded||0)-(((c=this.videoConsumerToStatsMap.get(P))==null?void 0:c.framesDecoded)||0),framesPerSecond:N.framesPerSecond||0,packetsLost:(N.packetsLost||0)-(((d=this.videoConsumerToStatsMap.get(P))==null?void 0:d.packetsLost)||0),packetsReceived:(N.packetsReceived||0)-(((h=this.videoConsumerToStatsMap.get(P))==null?void 0:h.packetsReceived)||0),jitter:N.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),ht.set(P,{score:+(N.score*10).toFixed(),frameWidth:N.frameWidth||0,frameHeight:N.frameHeight||0,framesPerSecond:N.framesPerSecond||0,packetsLostPercentage:Zd({packetsLost:(N.packetsLost||0)-(((u=this.videoConsumerToStatsMap.get(P))==null?void 0:u.packetsLost)||0),packetsReceived:(N.packetsReceived||0)-(((g=this.videoConsumerToStatsMap.get(P))==null?void 0:g.packetsReceived)||0)}),jitter:N.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((N.bytesReceived||0)-(((E=this.videoConsumerToStatsMap.get(P))==null?void 0:E.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,N),A.inboundVideoRtp.set(V.id,N),A.consumerStreamMap.get(P).inboundVideoRtpId.push(V.id),this.processInboundConsumerVideoStats(P,ye,N)}else if(I.mediaType==="audio"||I.kind==="audio"){const q=I,N=H({audioLevel:q.audioLevel,concealedSamples:q.concealedSamples,concealmentEvents:q.concealmentEvents,totalAudioEnergy:q.totalAudioEnergy,totalSamplesDuration:q.totalSamplesDuration,totalSamplesReceived:q.totalSamplesReceived,fecPacketsDiscarded:q.fecPacketsDiscarded||0,fecPacketsReceived:q.fecPacketsReceived||0,insertedSamplesForDeceleration:q.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:q.removedSamplesForAcceleration||0,silentConcealedSamples:q.silentConcealedSamples||0,playoutId:q.playoutId},Xe);N.score=Dv({concealmentEvents:(N.concealmentEvents||0)-(((b=this.audioConsumerToStatsMap.get(P))==null?void 0:b.concealmentEvents)||0),packetsLost:(N.packetsLost||0)-(((w=this.audioConsumerToStatsMap.get(P))==null?void 0:w.packetsLost)||0),packetsReceived:(N.packetsReceived||0)-(((M=this.audioConsumerToStatsMap.get(P))==null?void 0:M.packetsReceived)||0),jitter:N.jitter||0}),ht.set(P,{score:+(N.score*10).toFixed(),packetsLostPercentage:Zd({packetsLost:(N.packetsLost||0)-(((D=this.audioConsumerToStatsMap.get(P))==null?void 0:D.packetsLost)||0),packetsReceived:(N.packetsReceived||0)-(((F=this.audioConsumerToStatsMap.get(P))==null?void 0:F.packetsReceived)||0)}),jitter:N.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((N.bytesReceived||0)-(((Y=this.audioConsumerToStatsMap.get(P))==null?void 0:Y.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,N),A.inboundAudioRtp.set(V.id,N),A.consumerStreamMap.get(P).inboundAudioRtpId.push(V.id),this.processInboundConsumerAudioStats(P,ye,N)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${I.mediaType} kind: ${I.kind}`);break}}}if(A.producerStreamMap.forEach((V,I)=>{var P,K,ye,Xe,q,N,Ze,Rn,Ps,As,Ms,Fe,at,Ni,Li,xi,Vi,Ui,En,hi,Bi,Os,Fi;if(V.outboundVideoRtpId.length>0){const ge=[];V.outboundVideoRtpId.forEach(Oa=>{ge.push(A.outboundVideoRtp.get(Oa))});const pe=this.getWorkingSimulcastVideoStats(ge);pe.score=Mv({frameWidth:pe.frameWidth||0,framesPerSecond:pe.framesPerSecond||0,jitter:((P=pe.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(I),packetsSent:(pe.packetsSent||0)-(((K=this.videoProducerToStatsMap.get(I))==null?void 0:K.packetsSent)||0),packetsLost:(((ye=pe.remoteData)==null?void 0:ye.packetsLost)||0)-(((q=(Xe=this.videoProducerToStatsMap.get(I))==null?void 0:Xe.remoteData)==null?void 0:q.packetsLost)||0),framesEncoded:(pe.framesEncoded||0)-(((N=this.videoProducerToStatsMap.get(I))==null?void 0:N.framesEncoded)||0)}),Je.set(I,{score:+(pe.score*10).toFixed(),frameWidth:pe.frameWidth||0,frameHeight:pe.frameHeight||0,framesPerSecond:pe.framesPerSecond||0,jitter:((Ze=pe.remoteData)==null?void 0:Ze.jitter)||0,isScreenShare:this.screenShareProducers.has(I),packetsLostPercentage:Xd({packetsSent:(pe.packetsSent||0)-(((Rn=this.videoProducerToStatsMap.get(I))==null?void 0:Rn.packetsSent)||0),packetsLost:(((Ps=pe.remoteData)==null?void 0:Ps.packetsLost)||0)-(((Ms=(As=this.videoProducerToStatsMap.get(I))==null?void 0:As.remoteData)==null?void 0:Ms.packetsLost)||0)}),bitrate:((pe.bytesSent||0)-(((Fe=this.videoProducerToStatsMap.get(I))==null?void 0:Fe.bytesSent)||0))*8/7,cpuLimitations:pe.qualityLimitationReason==="cpu",bandwidthLimitations:pe.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(I,pe)}else if(V.outboundAudioRtpId.length>0){const ge=A.outboundAudioRtp.get(V.outboundAudioRtpId[0]);ge.score=Av({packetsSent:(ge.packetsSent||0)-(((at=this.audioProducerToStatsMap.get(I))==null?void 0:at.packetsSent)||0),packetsLost:(((Ni=ge.remoteData)==null?void 0:Ni.packetsLost)||0)-(((xi=(Li=this.audioProducerToStatsMap.get(I))==null?void 0:Li.remoteData)==null?void 0:xi.packetsLost)||0),jitter:((Vi=ge.remoteData)==null?void 0:Vi.jitter)||0}),Je.set(I,{score:+(ge.score*10).toFixed(),bitrate:((ge.bytesSent||0)-(((Ui=this.audioProducerToStatsMap.get(I))==null?void 0:Ui.bytesSent)||0))*8/7,packetsLostPercentage:Xd({packetsSent:(ge.packetsSent||0)-(((En=this.audioProducerToStatsMap.get(I))==null?void 0:En.packetsSent)||0),packetsLost:(((hi=ge.remoteData)==null?void 0:hi.packetsLost)||0)-(((Os=(Bi=this.audioProducerToStatsMap.get(I))==null?void 0:Bi.remoteData)==null?void 0:Os.packetsLost)||0)}),jitter:((Fi=ge.remoteData)==null?void 0:Fi.jitter)||0,isScreenShare:this.screenShareProducers.has(I)}),this.audioProducerToStatsMap.set(I,ge)}}),fe.forEach(V=>{const I=me.find(K=>K.id===V.localCandidateId?(V.localCandidateId=K.id,K):null),P=Ie.find(K=>K.id===V.remoteCandidateId?(V.remoteCandidateId=K.id,K):null);I&&(V.localCandidateType=I.type,V.localCandidateAddress=Es(I.address),V.localCandidatePort=I.port,V.localCandidateProtocol=I.protocol,V.localCandidateUrl=I.url,V.localCandidateNetworkType=I.networkType,V.localCandidateRelatedAddress=Es(I.relatedAddress),V.localCandidateRelatedPort=I.relatedPort),P&&(V.remoteCandidateType=P.type,V.remoteCandidateAddress=Es(P.address),V.remoteCandidatePort=P.port,V.remoteCandidateProtocol=P.protocol,V.remoteCandidateUrl=P.url)}),A.candidatePair&&(A.transport?(A.transport.bytesReceived=A.candidatePair.bytesReceived,A.transport.bytesSent=A.candidatePair.bytesSent,A.transport.totalRoundTripTime=A.candidatePair.totalRoundTripTime,A.transport.availableOutgoingBitrate=A.candidatePair.availableOutgoingBitrate,A.transport.availableIncomingBitrate=A.candidatePair.availableIncomingBitrate,A.transport.roundTripTime=A.candidatePair.currentRoundTripTime):A.transport={bytesReceived:A.candidatePair.bytesReceived,bytesSent:A.candidatePair.bytesSent,totalRoundTripTime:A.candidatePair.totalRoundTripTime,availableOutgoingBitrate:A.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:A.candidatePair.availableIncomingBitrate,roundTripTime:A.candidatePair.currentRoundTripTime}),A.transport&&(A.transport.candidatePairs=fe),A.transport&&!A.transport.roundTripTime){let V=0,I=0;A.remoteInboundRtp.forEach((P,K)=>{P.roundTripTime&&P.roundTripTime>V&&(V=P.roundTripTime,I=P.totalRoundTripTime)}),A.transport.roundTripTime=V,A.transport.totalRoundTripTime=I}if(ht.size>0)try{this.observer.emit("consumer_score",ht)}catch(V){}if(Je.size>0)try{this.observer.emit("producer_score",Je)}catch(V){}return A}getProducerStatsFromReport(e){const n=[];try{e.producerStreamMap.forEach((i,s)=>{const r=this.producerMap.get(s),a=r.track.getSettings(),c=i.outboundVideoRtpId.map(h=>{const u=e.outboundVideoRtp.get(h);return u.frameHeight||(u.frameHeight=a.height,u.frameWidth=a.width,u.framesPerSecond=a.frameRate),u}),d={producerId:s,appData:r.appData,videoStats:c,audioStats:i.outboundAudioRtpId.map(h=>e.outboundAudioRtp.get(h))};n.push(d)})}catch(i){console.error("getProducersReport: ",i,e)}return n}getConsumerStatsFromParsedConsumerStats(e,n,i){let s;try{const{peerId:r,producerId:a,appData:c}=this.consumerPeerIdMap.get(i),d=n==null?void 0:n.inboundVideoRtpId.map(h=>{const u=this.consumerMap.get(i).track.getSettings(),g=e.inboundVideoRtp.get(h);return g.frameHeight||(g.frameHeight=u.height,g.frameWidth=u.width,g.framesPerSecond=u.frameRate),g});s={consumerId:i,peerId:r,producerId:a,appData:c,videoStats:d,audioStats:n==null?void 0:n.inboundAudioRtpId.map(h=>e.inboundAudioRtp.get(h))}}catch(r){console.error("getConsumerStatsFromParsedConsumerStats: ",r,e)}return s}getConsumerStatsFromReport(e){const n=[];try{e.consumerStreamMap.forEach((i,s)=>{n.push(this.getConsumerStatsFromParsedConsumerStats(e,i,s))})}catch(i){console.error("getConsumerStatsFromReport: ",i,e)}return n}}class rT extends Uv{}function el(t,e,n,i){if(t!=null&&t.logger&&t.logger.error("Callstats::handleError",{error:i}),typeof n=="function"&&i instanceof e)n.call(null,i,t);else throw i}function Um(t,e,n){const i=t.value;return t.value=function(...s){try{const r=i.apply(this,s);return r&&r instanceof Promise?r.catch(a=>{el(this,e,n,a)}):r}catch(r){el(this,e,n,r)}return null},t}const le=(t,e)=>(n,i,s)=>{const r=s.value;return s.value=function(...a){try{const c=r.apply(this,a);return c&&c instanceof Promise?c.catch(d=>{el(this,t,e,d)}):c}catch(c){el(this,t,e,c)}return null},s},aT=(t,e)=>(n,i,s)=>{if(s)return Um(s,t,e);for(const r of Reflect.ownKeys(n.prototype).filter(a=>a!=="constructor")){const a=Object.getOwnPropertyDescriptor(n.prototype,r);a.value instanceof Function&&Object.defineProperty(n.prototype,r,Um(a,t,e))}};var ce=globalThis&&globalThis.__decorate||function(t,e,n,i){var s=arguments.length,r=s<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,n):i,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(t,e,n,i);else for(var c=t.length-1;c>=0;c--)(a=t[c])&&(r=(s<3?a(r):s>3?a(e,n,r):a(e,n))||r);return s>3&&r&&Object.defineProperty(e,n,r),r};const de=console;let ae=class extends Nt{constructor(t="https://api.testingv3.dyte.in",e="Blink",n=Go.PROD,i,s,r,a){switch(super(),y(this,"observer"),y(this,"eventHandler"),y(this,"measurements"),y(this,"producingTransport"),y(this,"consumingTransport"),y(this,"producers",new Map),y(this,"consumers",new Map),y(this,"iceServers"),y(this,"connectionInfoPromise"),y(this,"pingStatsTimeout"),y(this,"logger"),y(this,"env"),y(this,"apiHostnames"),y(this,"peerId"),y(this,"consumerSharedMediaStatesMap",new Map),y(this,"currentUserMediaStates",{}),this.env=n,this.apiHostnames=a,this.logger=s,this.peerId=r,this.eventHandler=new qS({logger:s,peerId:r,apiHostnames:a}),this.logger.debug("callStats::engineName: ",{engineName:e}),e){case"Blink":this.measurements=new sT;break;case"Gecko":this.measurements=new Uv;break;case"WebKit":this.measurements=new rT;break;default:throw Error(`Unknown engineName! ${e}`)}this.measurements.callStatsInstance=this,this.registerProducer=this.registerProducer.bind(this),this.registerConsumer=this.registerConsumer.bind(this),this.observer=new Nt,this.measurements.observer.on("consumer_score",c=>{s.debug(`callStats::consumer_score ${[...c.entries()]}`),this.eventHandler.emit("consumer_score",c)}),this.measurements.observer.on("producer_score",c=>{s.debug(`callStats::producer_score ${[...c.entries()]}`),this.eventHandler.emit("producer_score",c)})}registerIceServers(t){this.iceServers=t}registerConsumer(t){var e;this.consumerSharedMediaStatesMap.has(t.id)||this.consumerSharedMediaStatesMap.set(t.id,{}),this.consumers.set(t.id,t),this.measurements.registerConsumer(t),this.logger.debug("callStats::registerConsumer",{consumerId:t.id,consumerkind:t.kind,isScreenShare:!!((e=t.appData)!=null&&e.screenShare)}),t.on("close",this.deRegisterConsumer.bind(this,t))}registerProducer(t){var e;this.producers.set(t.id,t),this.measurements.registerProducer(t),this.logger.debug("callStats::registerProducer",{producerId:t.id,producerKind:t.kind,isScreenShare:!!((e=t.appData)!=null&&e.screenShare)}),t.on("close",this.deRegisterProducer.bind(this,t))}sendConsumerSharedMediaStateEvent(t,e){this.consumerSharedMediaStatesMap.has(t)||this.consumerSharedMediaStatesMap.set(t,{});const n=this.consumerSharedMediaStatesMap.get(t);this.consumerSharedMediaStatesMap.set(t,Object.assign(n,e))}registerProducingTransport(t){var e;this.producingTransport=t,t.observer.on("close",this.disconnectProducingTransport.bind(this,t)),t.observer.on("disconnect",this.disconnectProducingTransport.bind(this,t)),Array.from(((e=t._producers)==null?void 0:e.values())||[]).forEach(n=>{this.registerProducer(n)}),t.observer.on("newproducer",this.registerProducer)}registerConsumingTransport(t){var e;this.consumingTransport=t,t.observer.on("close",this.disconnectConsumingTransport.bind(this,t)),t.observer.on("disconnect",this.disconnectConsumingTransport.bind(this,t)),Array.from(((e=t._consumers)==null?void 0:e.values())||[]).forEach(n=>{this.registerConsumer(n)}),t.observer.on("newconsumer",this.registerConsumer)}deRegisterConsumer(t){this.consumers.delete(t.id)}deRegisterProducer(t){var e;this.producers.delete(t.id),this.logger.debug("callStats::deRegisterProducer",{producerId:t.id,producerKind:t.kind,isScreenShare:!!((e=t.appData)!=null&&e.screenShare)})}disconnectConsumingTransport(){this.consumingTransport=void 0}disconnectProducingTransport(){this.producingTransport=void 0}callEvent(t){this.eventHandler.callEvent(t)}sendPreCallTestBeginEvent(t=!1,e){this.connectionInfoPromise=this.measurements.getNetworkInfo(this.iceServers,t),this.eventHandler.callEvent({event:G.PRECALL_TEST_BEGIN,timestamp:e}),this.connectionInfoPromise&&this.connectionInfoPromise.then(n=>{this.eventHandler.callEvent({event:G.PRECALL_TEST_COMPLETE,metaData:{connectionInfo:n},timestamp:e})})}sendScreenShareToggleEvent(t,e=null,n){this.currentUserMediaStates.screen=t,this.eventHandler.callEvent({event:t?G.SCREENSHARE_STARTED:G.SCREENSHARE_STOPPED,metaData:{ssrc:e},timestamp:n})}sendScreenShareRequestedEvent(t){this.eventHandler.callEvent({event:G.SCREENSHARE_START_REQUESTED,timestamp:t})}sendActiveSpeakerEvent(t,e){this.eventHandler.callEvent({event:G.DOMINANT_SPEAKER,metaData:{peerId:t},timestamp:e})}devices(t,e,n){this.eventHandler.callEvent({event:t===kn.AUDIO&&G.AUDIO_DEVICES_UPDATES||t===kn.VIDEO&&G.VIDEO_DEVICES_UPDATES||t===kn.SPEAKER&&G.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:e},timestamp:n})}selectedDevice(t,e,n){this.eventHandler.callEvent({event:t===kn.AUDIO&&G.SELECTED_MICROHPONE_UPDATE||t===kn.VIDEO&&G.SELECTED_CAMERA_UPDATE||t===kn.SPEAKER&&G.SELECTED_SPEAKER_UPDATE,metaData:{device:e},timestamp:n})}mediaPermission(t,e,n){this.eventHandler.callEvent({event:G.MEDIA_PERMISSION,metaData:{deviceType:t,permission:e},timestamp:n})}mediaPlaybackFailed(t,e){this.eventHandler.callEvent({event:t===kn.AUDIO&&G.AUDIO_PLAY_FAILED||t===kn.VIDEO&&G.VIDEO_PLAY_FAILED,metaData:{deviceType:t},timestamp:e})}mediaTrackMuted(t,e){this.eventHandler.callEvent({event:t===kn.AUDIO&&G.AUDIO_TRACK_MUTED||t===kn.VIDEO&&G.VIDEO_TRACK_MUTED,metaData:{deviceType:t},timestamp:e})}tabChanged(t,e){this.eventHandler.callEvent({event:G.TAB_CHANGE,metaData:{isMeetingsTabActive:t},timestamp:e})}browserBackgrounded(t){this.eventHandler.callEvent({event:G.BROWSER_BACKGROUNDED,timestamp:t})}browserForegrounded(t){this.eventHandler.callEvent({event:G.BROWSER_FOREGROUNDED,timestamp:t})}legacySwitch(t,e){this.eventHandler.callEvent({event:G.LEGACY_SWITCH,metadata:{on:t},timestamp:e})}getPreCallTestResults(){return p(this,null,function*(){return this.connectionInfoPromise})}sendCallJoinBeginEvent(t,e){t=ee(H({},t),{meetingEnv:this.env}),t.deviceInfo=ee(H({},t.deviceInfo),{userAgent:navigator.userAgent,cpus:navigator.hardwareConcurrency,memory:navigator.deviceMemory}),this.eventHandler.callEvent({event:G.CALL_JOIN_BEGIN,metaData:{peerMetaData:t},timestamp:e})}sendNetworkQualityTestBeginEvent(t,e){this.eventHandler.callEvent({event:G.NET_QUALITY_TEST_BEGIN,timestamp:e}),new Promise((n,i)=>p(this,null,function*(){const s=[];try{for(const r of t)try{if(r.iceServers&&r.iceServers.length>0){const a=yield this.measurements.getNetworkQuality(r.iceServers);s.push(ee(H({},r),{networkResults:a}))}}catch(a){console.warn("Error handling ",a)}n({regionData:s})}catch(r){console.warn("Error in callstats, ",r),i(r)}})).then(n=>{this.eventHandler.callEvent({event:G.NET_QUALITY_TEST_END,timestamp:e,metaData:n})})}sendWebSocketConnectedEvent(t){this.eventHandler.callEvent({event:G.WEBSOCKET_CONNECTED,timestamp:t})}sendTransportConnectedEvent(t){this.eventHandler.callEvent({event:G.TRANSPORT_CONNECTED,timestamp:t})}sendAudioToggleEvent(t,e){this.currentUserMediaStates.audio=t;let n;t?n=G.AUDIO_ON:n=G.AUDIO_OFF,this.eventHandler.callEvent({event:n,timestamp:e})}sendVideoToggleEvent(t,e){this.currentUserMediaStates.video=t;let n;t?n=G.VIDEO_ON:n=G.VIDEO_OFF,this.eventHandler.callEvent({event:n,timestamp:e})}sendParticipantRoleToggleEvent(t,e){this.eventHandler.callEvent({event:G.PARTICIPANT_ROLE,timestamp:e,metaData:t})}startPingStats(t=7e3){this.sendPingStatsEvent(!1,new Date),this.pingStatsTimeout=setInterval(this.sendPingStatsEvent.bind(this),t)}stopPingStats(){clearInterval(this.pingStatsTimeout)}sendPingStatsEvent(t=!0,e){return p(this,null,function*(){let n,i;if(this.producingTransport&&(n=yield this.measurements.getProcessedStats(this.producingTransport,!1,!0),!n||!(n!=null&&n.producerReport))){this.logger.debug("callStats::sendPingStatsEvent::staleProducingTransport",{disclaimer:"Stale producer? Regenerating Stream Maps!"});const r=yield this.measurements.getProducersReport([...this.producers.values()]);n&&r?n.producerReport=r:(n=yield this.measurements.getProcessedStats(this.producingTransport,!1,!0),(!n||!(n!=null&&n.producerReport))&&this.logger.debug("callStats::sendPingStatsEvent::noProducingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}if(this.consumingTransport&&(i=yield this.measurements.getProcessedStats(this.consumingTransport,!0,!1),!i||!i.consumerReport)){this.logger.debug("callStats::sendPingStatsEvent::staleConsumingTransport",{disclaimer:"Stale consumer? Regenerating Stream Maps!"});const r=yield this.measurements.getConsumersReport([...this.consumers.values()]);i&&r?i.consumerReport=r:(i=yield this.measurements.getProcessedStats(this.consumingTransport,!0,!1),(!i||!i.consumerReport)&&this.logger.debug("callStats::sendPingStatsEvent::noConsumingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}const s={producingTransportStats:n?n==null?void 0:n.transportReport:void 0,consumingTransportStats:i?i==null?void 0:i.transportReport:void 0,producerStats:[].concat((n==null?void 0:n.producerReport)||[]).concat((i==null?void 0:i.producerReport)||[]),consumerStats:[].concat((i==null?void 0:i.consumerReport)||[]).concat((n==null?void 0:n.consumerReport)||[])};if(t&&s.producerStats.length===0&&s.consumerStats.length===0){yield this.eventHandler.flush();return}this.eventHandler.callEvent({event:G.PING_STAT,metaData:s,timestamp:e})})}sendIVSPlayerRebufferEvent(t){this.eventHandler.callEvent({event:G.IVS_PLAYER_REBUFFERING,timestamp:t})}sendIVSPlayerAudioBlockEvent(t){this.eventHandler.callEvent({event:G.IVS_PLAYER_AUDIO_BLOCKED,timestamp:t})}sendIVSPlayerPlaybackBlockedEvent(t){this.eventHandler.callEvent({event:G.IVS_PLAYER_PLAYBACK_BLOCKED,timestamp:t})}sendIVSPlayerNetworkUnavailableEvent(t){this.eventHandler.callEvent({event:G.IVS_PLAYER_NETWORK_UNAVAILABLE,timestamp:t})}sendIVSPlayerInitializedEvent(t){this.eventHandler.callEvent({event:G.IVS_PLAYER_INITIALIZED,timestamp:t})}sendIVSPlayerWorkerErrorEvent(t){this.eventHandler.callEvent({event:G.IVS_PLAYER_WORKER_ERROR,timestamp:t})}sendIVSPlayerErrorEvent(t,e){this.eventHandler.callEvent({event:G.IVS_PLAYER_ERROR,timestamp:e,metaData:t})}sendIVSPlayerRecoverableErrorEvent(t,e){this.eventHandler.callEvent({event:G.IVS_PLAYER_RECOVERABLE_ERROR,timestamp:e,metaData:t})}sendIVSPlayerAnalyticsEvent(t,e){this.eventHandler.callEvent({event:G.IVS_PLAYER_ANALYTICS_EVENT,timestamp:e,metaData:t})}sendIVSPlayerPlaybackRateChangedEvent(t,e){this.eventHandler.callEvent({event:G.IVS_PLAYER_PLAYBACK_RATE_CHANGED,timestamp:e,metaData:{updatedPlaybackRate:t}})}sendIVSPlayerQualityChanged(t,e){this.eventHandler.callEvent({event:G.IVS_PLAYER_QUALITY_CHANGED,timestamp:e,metaData:t})}sendPlayerLiveLatency(t,e){this.eventHandler.callEvent({event:G.LIVESTREAM_LATENCY,timestamp:e,metaData:{latency:t}})}sendDisconnectEvent(t){this.eventHandler.callEvent({event:G.DISCONNECT,timestamp:t})}sendReconnectEvent(t){this.eventHandler.callEvent({event:G.RECONNECT_ATTEMPT,timestamp:t})}expectedVideoResolution(t,e,n){this.eventHandler.callEvent({event:G.EXPECTED_VIDEO_RESOLUTION,timestamp:n,metaData:{frameWidth:t,frameHeight:e}})}expectedScreenshareResolution(t,e,n){this.eventHandler.callEvent({event:G.EXPECTED_SCREENSHARE_RESOLUTION,timestamp:n,metaData:{frameWidth:t,frameHeight:e}})}};ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"registerIceServers",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"registerConsumer",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"registerProducer",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendConsumerSharedMediaStateEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"registerProducingTransport",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"registerConsumingTransport",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"deRegisterConsumer",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"deRegisterProducer",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"disconnectConsumingTransport",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"disconnectProducingTransport",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendPreCallTestBeginEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendScreenShareToggleEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendScreenShareRequestedEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendActiveSpeakerEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"devices",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"selectedDevice",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"mediaPermission",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"mediaPlaybackFailed",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"mediaTrackMuted",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"tabChanged",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"browserBackgrounded",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"browserForegrounded",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"legacySwitch",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"getPreCallTestResults",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendCallJoinBeginEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendNetworkQualityTestBeginEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendWebSocketConnectedEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendTransportConnectedEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendAudioToggleEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendVideoToggleEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendParticipantRoleToggleEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"startPingStats",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"stopPingStats",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendPingStatsEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendIVSPlayerRebufferEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendIVSPlayerAudioBlockEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendIVSPlayerPlaybackBlockedEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendIVSPlayerNetworkUnavailableEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendIVSPlayerInitializedEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendIVSPlayerWorkerErrorEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendIVSPlayerErrorEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendIVSPlayerRecoverableErrorEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendIVSPlayerAnalyticsEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendIVSPlayerQualityChanged",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendPlayerLiveLatency",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendDisconnectEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendReconnectEvent",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"expectedVideoResolution",null);ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"expectedScreenshareResolution",null);ae=ce([aT(TypeError,(t,e)=>de.error(e,t))],ae);const oT=ae;class cT extends Nt{constructor(){super(...arguments),y(this,"stats"),y(this,"peerId"),y(this,"backend"),y(this,"iceServers"),y(this,"initialized",!1),y(this,"stalled",!1),y(this,"ipInformation"),y(this,"logger")}initialize(e){return p(this,arguments,function*({peerId:n,engineName:i,env:s=Go.PROD,iceServers:r,apiBase:a="https://api.cluster.dyte.in",flags:c,logger:d=console,apiHostnames:h,skipConnectivityChecks:u=!1}){var g,E,b;try{this.peerId=n,this.logger=d,this.ipInformation=yield Lp.getIPDetails({peerId:n,apiHostnames:h,logger:d}),this.backend=new oT(a,i,s,c,d,n,h),this.iceServers=r,(g=this.backend)==null||g.registerIceServers(this.iceServers),this.initialized=!0,(b=(E=this.backend)==null?void 0:E.eventHandler)==null||b.emit("initialized",this.ipInformation),this.emit("initialized",this.ipInformation),this.startPreCallTest(u)}catch(w){this.logger.error("callStats::CallStatsIntegration: ",{error:w}),this.stallCallStats()}})}configureSendTransport(e){this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.registerProducingTransport(e)})}configureRecvTransport(e){this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.registerConsumingTransport(e)})}candidateRegionalNetworkQualityTest(e){return p(this,null,function*(){const n=new Date;this.onSafeInitialization(()=>{var i;try{(i=this.backend)==null||i.sendNetworkQualityTestBeginEvent(e,n)}catch(s){this.logger.error("callStats::sendNetworkQualityTestBeginEvent",{error:{reason:s.reason}})}})})}roomJoined(e){return p(this,null,function*(){const n=new Date;this.onSafeInitialization(()=>{var i,s;(i=this.backend)==null||i.sendCallJoinBeginEvent(e,n),this.backend,(s=this.backend)==null||s.startPingStats()})})}audioOff(){const e=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendAudioToggleEvent(!1,e)})}audioOn(){const e=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendAudioToggleEvent(!0,e)})}videoOff(){const e=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendVideoToggleEvent(!1,e)})}videoOn(){const e=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendVideoToggleEvent(!0,e)})}callEnded(){const e=new Date;this.onSafeInitialization(()=>{var n,i;(n=this.backend)==null||n.stopPingStats(),(i=this.backend)==null||i.sendDisconnectEvent(e)})}screenShareStart(e){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendScreenShareToggleEvent(!0,e,n)})}consumerSharedMediaState(e,n){this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendConsumerSharedMediaStateEvent(e,n)})}screenShareStop(e){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendScreenShareToggleEvent(!1,e,n)})}screenShareRequested(){const e=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendScreenShareRequestedEvent(e)})}activeSpeaker(e){if(e!==this.peerId)return;const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendActiveSpeakerEvent(e,n)})}devices(e,n){const i=new Date;this.onSafeInitialization(()=>{var s;(s=this.backend)==null||s.devices(e,n,i)})}selectedDevice(e,n){const i=new Date;this.onSafeInitialization(()=>{var s;(s=this.backend)==null||s.selectedDevice(e,n,i)})}mediaPermission(e,n){const i=new Date;this.onSafeInitialization(()=>{var s;(s=this.backend)==null||s.mediaPermission(e,n,i)})}mediaPlaybackFailed(e){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.mediaPlaybackFailed(e,n)})}mediaTrackMuted(e){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.mediaTrackMuted(e,n)})}tabChanged(e=!1){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.tabChanged(e,n)})}browserBackgrounded(){const e=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.browserBackgrounded(e)})}browserForegrounded(){const e=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.browserForegrounded(e)})}legacySwitch(e){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.legacySwitch(e,n)})}startPreCallTest(e=!1){return p(this,null,function*(){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendPreCallTestBeginEvent(e,n)})})}onPreCallTestResults(e){return this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.eventHandler.once("precall_end",e)}),e}onReceivingConsumerAudioStatus(e){this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.eventHandler.on("consumer_audio_status",e)})}onReceivingConsumerVideoStatus(e){this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.eventHandler.on("consumer_video_status",e)})}onReceivingProducerAudioStatus(e){this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.eventHandler.on("producer_audio_status",e)})}onReceivingProducerVideoStatus(e){this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.eventHandler.on("producer_video_status",e)})}onReceivingProducingTransportStatus(e){this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.eventHandler.on("producing_transport_status",e)})}onReceivingConsumingTransportStatus(e){this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.eventHandler.on("consuming_transport_status",e)})}onProducerScore(e){this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.eventHandler.on("producer_score",e)})}onConsumerScore(e){this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.eventHandler.on("consumer_score",e)})}onSafeInitialization(e){if(this.initialized)e(this.ipInformation,!1);else if(!this.stalled){const n=i=>{e(i,!0)};return this.once("initialized",n),n}return()=>{}}removeInitializationListener(e){this.removeListener("initialized",e)}stallCallStats(){this.stalled=!0,this.removeAllListeners("initialized")}ivsPlayerEvent(e,n){const i=new Date;this.onSafeInitialization(()=>{var s,r,a,c,d,h,u,g,E,b,w;switch(e){case"PlayerRebuffering":(s=this.backend)==null||s.sendIVSPlayerRebufferEvent(i);break;case"PlayerAudioBlocked":(r=this.backend)==null||r.sendIVSPlayerAudioBlockEvent(i);break;case"PlayerPlaybackBlocked":(a=this.backend)==null||a.sendIVSPlayerPlaybackBlockedEvent(i);break;case"PlayerNetworkUnavailable":(c=this.backend)==null||c.sendIVSPlayerNetworkUnavailableEvent(i);break;case"PlayerInitialized":(d=this.backend)==null||d.sendIVSPlayerInitializedEvent(i);break;case"PlayerWorkerError":(h=this.backend)==null||h.sendIVSPlayerWorkerErrorEvent(i);break;case"PlayerError":(u=this.backend)==null||u.sendIVSPlayerErrorEvent(n,i);break;case"PlayerRecoverableError":(g=this.backend)==null||g.sendIVSPlayerRecoverableErrorEvent(n,i);break;case"PlayerAnalyticsEvent":(E=this.backend)==null||E.sendIVSPlayerAnalyticsEvent(n,i);break;case"PlayerPlaybackRateChanged":(b=this.backend)==null||b.sendIVSPlayerPlaybackRateChangedEvent(n,i);break;case"PlayerQualityChanged":(w=this.backend)==null||w.sendIVSPlayerQualityChanged(n,i);break}})}livestreamLatency(e){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendPlayerLiveLatency(e,n)})}expectedVideoResolution(e,n){const i=new Date;this.onSafeInitialization(()=>{var s;(s=this.backend)==null||s.expectedVideoResolution(e,n,i)})}expectedScreenshareResolution(e,n){const i=new Date;this.onSafeInitialization(()=>{var s;(s=this.backend)==null||s.expectedScreenshareResolution(e,n,i)})}}const ne=new cT;ne.setMaxListeners(30);function dT(t){const{length:e}=this,n=t>=0?t:e+t;return n<0||n>=e?void 0:this[n]}Array.prototype.at||Object.assign(Array.prototype,{at:dT});function lT(t){const{length:e}=this,n=t>=0?t:e+t;return n<0||n>=e?void 0:this[n]}String.prototype.at||Object.assign(String.prototype,{at:lT});function uT(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Bv={exports:{}},rt=Bv.exports={},ni,ii;function rh(){throw new Error("setTimeout has not been defined")}function ah(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?ni=setTimeout:ni=rh}catch(t){ni=rh}try{typeof clearTimeout=="function"?ii=clearTimeout:ii=ah}catch(t){ii=ah}})();function Fv(t){if(ni===setTimeout)return setTimeout(t,0);if((ni===rh||!ni)&&setTimeout)return ni=setTimeout,setTimeout(t,0);try{return ni(t,0)}catch(e){try{return ni.call(null,t,0)}catch(n){return ni.call(this,t,0)}}}function hT(t){if(ii===clearTimeout)return clearTimeout(t);if((ii===ah||!ii)&&clearTimeout)return ii=clearTimeout,clearTimeout(t);try{return ii(t)}catch(e){try{return ii.call(null,t)}catch(n){return ii.call(this,t)}}}var _i=[],ma=!1,cr,dd=-1;function pT(){!ma||!cr||(ma=!1,cr.length?_i=cr.concat(_i):dd=-1,_i.length&&jv())}function jv(){if(!ma){var t=Fv(pT);ma=!0;for(var e=_i.length;e;){for(cr=_i,_i=[];++dd<e;)cr&&cr[dd].run();dd=-1,e=_i.length}cr=null,ma=!1,hT(t)}}rt.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];_i.push(new Wv(t,e)),_i.length===1&&!ma&&Fv(jv)};function Wv(t,e){this.fun=t,this.array=e}Wv.prototype.run=function(){this.fun.apply(null,this.array)};rt.title="browser";rt.browser=!0;rt.env={};rt.argv=[];rt.version="";rt.versions={};function Mi(){}rt.on=Mi;rt.addListener=Mi;rt.once=Mi;rt.off=Mi;rt.removeListener=Mi;rt.removeAllListeners=Mi;rt.emit=Mi;rt.prependListener=Mi;rt.prependOnceListener=Mi;rt.listeners=function(t){return[]};rt.binding=function(t){throw new Error("process.binding is not supported")};rt.cwd=function(){return"/"};rt.chdir=function(t){throw new Error("process.chdir is not supported")};rt.umask=function(){return 0};var mT=Bv.exports;const dr=uT(mT);var oh={},fT={get exports(){return oh},set exports(t){oh=t}},tl={},gT={get exports(){return tl},set exports(t){tl=t}},Hv=function(t,e){return function(){return t.apply(e,arguments)}},vT=Hv,xp=Object.prototype.toString,Vp=function(t){return function(e){var n=xp.call(e);return t[n]||(t[n]=n.slice(8,-1).toLowerCase())}}(Object.create(null));function _s(t){return t=t.toLowerCase(),function(e){return Vp(e)===t}}function Nl(t){return Array.isArray(t)}function ch(t){return typeof t=="undefined"}function yT(t){return t!==null&&!ch(t)&&t.constructor!==null&&!ch(t.constructor)&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t)}var qv=_s("ArrayBuffer");function ET(t){var e;return typeof ArrayBuffer!="undefined"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&qv(t.buffer),e}function ST(t){return typeof t=="string"}function Gv(t){return typeof t=="number"}function $v(t){return t!==null&&typeof t=="object"}function ld(t){if(Vp(t)!=="object")return!1;var e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}function TT(t){return t&&Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}var bT=_s("Date"),kT=_s("File"),wT=_s("Blob"),_T=_s("FileList");function Up(t){return xp.call(t)==="[object Function]"}function IT(t){return $v(t)&&Up(t.pipe)}function CT(t){var e="[object FormData]";return t&&(typeof FormData=="function"&&t instanceof FormData||xp.call(t)===e||Up(t.toString)&&t.toString()===e)}var RT=_s("URLSearchParams");function PT(t){return t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}function AT(){var t;return typeof navigator!="undefined"&&((t=navigator.product)==="ReactNative"||t==="NativeScript"||t==="NS")?!1:typeof window!="undefined"&&typeof document!="undefined"}function Bp(t,e){if(!(t===null||typeof t=="undefined"))if(typeof t!="object"&&(t=[t]),Nl(t))for(var n=0,i=t.length;n<i;n++)e.call(null,t[n],n,t);else for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.call(null,t[s],s,t)}function dh(){var t={};function e(s,r){ld(t[r])&&ld(s)?t[r]=dh(t[r],s):ld(s)?t[r]=dh({},s):Nl(s)?t[r]=s.slice():t[r]=s}for(var n=0,i=arguments.length;n<i;n++)Bp(arguments[n],e);return t}function MT(t,e,n){return Bp(e,function(i,s){n&&typeof i=="function"?t[s]=vT(i,n):t[s]=i}),t}function OT(t){return t.charCodeAt(0)===65279&&(t=t.slice(1)),t}function DT(t,e,n,i){t.prototype=Object.create(e.prototype,i),t.prototype.constructor=t,n&&Object.assign(t.prototype,n)}function NT(t,e,n,i){var s,r,a,c={};if(e=e||{},t==null)return e;do{for(s=Object.getOwnPropertyNames(t),r=s.length;r-- >0;)a=s[r],(!i||i(a,t,e))&&!c[a]&&(e[a]=t[a],c[a]=!0);t=n!==!1&&Object.getPrototypeOf(t)}while(t&&(!n||n(t,e))&&t!==Object.prototype);return e}function LT(t,e,n){t=String(t),(n===void 0||n>t.length)&&(n=t.length),n-=e.length;var i=t.indexOf(e,n);return i!==-1&&i===n}function xT(t){if(!t)return null;if(Nl(t))return t;var e=t.length;if(!Gv(e))return null;for(var n=new Array(e);e-- >0;)n[e]=t[e];return n}var VT=function(t){return function(e){return t&&e instanceof t}}(typeof Uint8Array!="undefined"&&Object.getPrototypeOf(Uint8Array));function UT(t,e){for(var n=t&&t[Symbol.iterator],i=n.call(t),s;(s=i.next())&&!s.done;){var r=s.value;e.call(t,r[0],r[1])}}function BT(t,e){for(var n,i=[];(n=t.exec(e))!==null;)i.push(n);return i}var FT=_s("HTMLFormElement"),jT=function(t){return function(e,n){return t.call(e,n)}}(Object.prototype.hasOwnProperty),gt={isArray:Nl,isArrayBuffer:qv,isBuffer:yT,isFormData:CT,isArrayBufferView:ET,isString:ST,isNumber:Gv,isObject:$v,isPlainObject:ld,isEmptyObject:TT,isUndefined:ch,isDate:bT,isFile:kT,isBlob:wT,isFunction:Up,isStream:IT,isURLSearchParams:RT,isStandardBrowserEnv:AT,forEach:Bp,merge:dh,extend:MT,trim:PT,stripBOM:OT,inherits:DT,toFlatObject:NT,kindOf:Vp,kindOfTest:_s,endsWith:LT,toArray:xT,isTypedArray:VT,isFileList:_T,forEachEntry:UT,matchAll:BT,isHTMLForm:FT,hasOwnProperty:jT},vt={},Ll={};Ll.byteLength=qT;Ll.toByteArray=$T;Ll.fromByteArray=zT;var ri=[],wn=[],WT=typeof Uint8Array!="undefined"?Uint8Array:Array,du="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var Ar=0,HT=du.length;Ar<HT;++Ar)ri[Ar]=du[Ar],wn[du.charCodeAt(Ar)]=Ar;wn["-".charCodeAt(0)]=62;wn["_".charCodeAt(0)]=63;function Jv(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var i=n===e?0:4-n%4;return[n,i]}function qT(t){var e=Jv(t),n=e[0],i=e[1];return(n+i)*3/4-i}function GT(t,e,n){return(e+n)*3/4-n}function $T(t){var e,n=Jv(t),i=n[0],s=n[1],r=new WT(GT(t,i,s)),a=0,c=s>0?i-4:i,d;for(d=0;d<c;d+=4)e=wn[t.charCodeAt(d)]<<18|wn[t.charCodeAt(d+1)]<<12|wn[t.charCodeAt(d+2)]<<6|wn[t.charCodeAt(d+3)],r[a++]=e>>16&255,r[a++]=e>>8&255,r[a++]=e&255;return s===2&&(e=wn[t.charCodeAt(d)]<<2|wn[t.charCodeAt(d+1)]>>4,r[a++]=e&255),s===1&&(e=wn[t.charCodeAt(d)]<<10|wn[t.charCodeAt(d+1)]<<4|wn[t.charCodeAt(d+2)]>>2,r[a++]=e>>8&255,r[a++]=e&255),r}function JT(t){return ri[t>>18&63]+ri[t>>12&63]+ri[t>>6&63]+ri[t&63]}function KT(t,e,n){for(var i,s=[],r=e;r<n;r+=3)i=(t[r]<<16&16711680)+(t[r+1]<<8&65280)+(t[r+2]&255),s.push(JT(i));return s.join("")}function zT(t){for(var e,n=t.length,i=n%3,s=[],r=16383,a=0,c=n-i;a<c;a+=r)s.push(KT(t,a,a+r>c?c:a+r));return i===1?(e=t[n-1],s.push(ri[e>>2]+ri[e<<4&63]+"==")):i===2&&(e=(t[n-2]<<8)+t[n-1],s.push(ri[e>>10]+ri[e>>4&63]+ri[e<<2&63]+"=")),s.join("")}var Fp={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */Fp.read=function(t,e,n,i,s){var r,a,c=s*8-i-1,d=(1<<c)-1,h=d>>1,u=-7,g=n?s-1:0,E=n?-1:1,b=t[e+g];for(g+=E,r=b&(1<<-u)-1,b>>=-u,u+=c;u>0;r=r*256+t[e+g],g+=E,u-=8);for(a=r&(1<<-u)-1,r>>=-u,u+=i;u>0;a=a*256+t[e+g],g+=E,u-=8);if(r===0)r=1-h;else{if(r===d)return a?NaN:(b?-1:1)*(1/0);a=a+Math.pow(2,i),r=r-h}return(b?-1:1)*a*Math.pow(2,r-i)};Fp.write=function(t,e,n,i,s,r){var a,c,d,h=r*8-s-1,u=(1<<h)-1,g=u>>1,E=s===23?Math.pow(2,-24)-Math.pow(2,-77):0,b=i?0:r-1,w=i?1:-1,M=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(c=isNaN(e)?1:0,a=u):(a=Math.floor(Math.log(e)/Math.LN2),e*(d=Math.pow(2,-a))<1&&(a--,d*=2),a+g>=1?e+=E/d:e+=E*Math.pow(2,1-g),e*d>=2&&(a++,d/=2),a+g>=u?(c=0,a=u):a+g>=1?(c=(e*d-1)*Math.pow(2,s),a=a+g):(c=e*Math.pow(2,g-1)*Math.pow(2,s),a=0));s>=8;t[n+b]=c&255,b+=w,c/=256,s-=8);for(a=a<<s|c,h+=s;h>0;t[n+b]=a&255,b+=w,a/=256,h-=8);t[n+b-w]|=M*128};/*!
13
+ * The buffer module from node.js, for the browser.
14
+ *
15
+ * @author Feross Aboukhadijeh <https://feross.org>
16
+ * @license MIT
17
+ */(function(t){const e=Ll,n=Fp,i=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=u,t.SlowBuffer=$,t.INSPECT_MAX_BYTES=50;const s=2147483647;t.kMaxLength=s;const{Uint8Array:r,ArrayBuffer:a,SharedArrayBuffer:c}=globalThis;u.TYPED_ARRAY_SUPPORT=d(),!u.TYPED_ARRAY_SUPPORT&&typeof console!="undefined"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function d(){try{const l=new r(1),f={foo:function(){return 42}};return Object.setPrototypeOf(f,r.prototype),Object.setPrototypeOf(l,f),l.foo()===42}catch(l){return!1}}Object.defineProperty(u.prototype,"parent",{enumerable:!0,get:function(){if(u.isBuffer(this))return this.buffer}}),Object.defineProperty(u.prototype,"offset",{enumerable:!0,get:function(){if(u.isBuffer(this))return this.byteOffset}});function h(l){if(l>s)throw new RangeError('The value "'+l+'" is invalid for option "size"');const f=new r(l);return Object.setPrototypeOf(f,u.prototype),f}function u(l,f,v){if(typeof l=="number"){if(typeof f=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return w(l)}return g(l,f,v)}u.poolSize=8192;function g(l,f,v){if(typeof l=="string")return M(l,f);if(a.isView(l))return F(l);if(l==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof l);if(Yn(l,a)||l&&Yn(l.buffer,a)||typeof c!="undefined"&&(Yn(l,c)||l&&Yn(l.buffer,c)))return Y(l,f,v);if(typeof l=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const C=l.valueOf&&l.valueOf();if(C!=null&&C!==l)return u.from(C,f,v);const R=X(l);if(R)return R;if(typeof Symbol!="undefined"&&Symbol.toPrimitive!=null&&typeof l[Symbol.toPrimitive]=="function")return u.from(l[Symbol.toPrimitive]("string"),f,v);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof l)}u.from=function(l,f,v){return g(l,f,v)},Object.setPrototypeOf(u.prototype,r.prototype),Object.setPrototypeOf(u,r);function E(l){if(typeof l!="number")throw new TypeError('"size" argument must be of type number');if(l<0)throw new RangeError('The value "'+l+'" is invalid for option "size"')}function b(l,f,v){return E(l),l<=0?h(l):f!==void 0?typeof v=="string"?h(l).fill(f,v):h(l).fill(f):h(l)}u.alloc=function(l,f,v){return b(l,f,v)};function w(l){return E(l),h(l<0?0:A(l)|0)}u.allocUnsafe=function(l){return w(l)},u.allocUnsafeSlow=function(l){return w(l)};function M(l,f){if((typeof f!="string"||f==="")&&(f="utf8"),!u.isEncoding(f))throw new TypeError("Unknown encoding: "+f);const v=me(l,f)|0;let C=h(v);const R=C.write(l,f);return R!==v&&(C=C.slice(0,R)),C}function D(l){const f=l.length<0?0:A(l.length)|0,v=h(f);for(let C=0;C<f;C+=1)v[C]=l[C]&255;return v}function F(l){if(Yn(l,r)){const f=new r(l);return Y(f.buffer,f.byteOffset,f.byteLength)}return D(l)}function Y(l,f,v){if(f<0||l.byteLength<f)throw new RangeError('"offset" is outside of buffer bounds');if(l.byteLength<f+(v||0))throw new RangeError('"length" is outside of buffer bounds');let C;return f===void 0&&v===void 0?C=new r(l):v===void 0?C=new r(l,f):C=new r(l,f,v),Object.setPrototypeOf(C,u.prototype),C}function X(l){if(u.isBuffer(l)){const f=A(l.length)|0,v=h(f);return v.length===0||l.copy(v,0,0,f),v}if(l.length!==void 0)return typeof l.length!="number"||su(l.length)?h(0):D(l);if(l.type==="Buffer"&&Array.isArray(l.data))return D(l.data)}function A(l){if(l>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return l|0}function $(l){return+l!=l&&(l=0),u.alloc(+l)}u.isBuffer=function(l){return l!=null&&l._isBuffer===!0&&l!==u.prototype},u.compare=function(l,f){if(Yn(l,r)&&(l=u.from(l,l.offset,l.byteLength)),Yn(f,r)&&(f=u.from(f,f.offset,f.byteLength)),!u.isBuffer(l)||!u.isBuffer(f))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(l===f)return 0;let v=l.length,C=f.length;for(let R=0,U=Math.min(v,C);R<U;++R)if(l[R]!==f[R]){v=l[R],C=f[R];break}return v<C?-1:C<v?1:0},u.isEncoding=function(l){switch(String(l).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},u.concat=function(l,f){if(!Array.isArray(l))throw new TypeError('"list" argument must be an Array of Buffers');if(l.length===0)return u.alloc(0);let v;if(f===void 0)for(f=0,v=0;v<l.length;++v)f+=l[v].length;const C=u.allocUnsafe(f);let R=0;for(v=0;v<l.length;++v){let U=l[v];if(Yn(U,r))R+U.length>C.length?(u.isBuffer(U)||(U=u.from(U)),U.copy(C,R)):r.prototype.set.call(C,U,R);else if(u.isBuffer(U))U.copy(C,R);else throw new TypeError('"list" argument must be an Array of Buffers');R+=U.length}return C};function me(l,f){if(u.isBuffer(l))return l.length;if(a.isView(l)||Yn(l,a))return l.byteLength;if(typeof l!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof l);const v=l.length,C=arguments.length>2&&arguments[2]===!0;if(!C&&v===0)return 0;let R=!1;for(;;)switch(f){case"ascii":case"latin1":case"binary":return v;case"utf8":case"utf-8":return iu(l).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return v*2;case"hex":return v>>>1;case"base64":return Em(l).length;default:if(R)return C?-1:iu(l).length;f=(""+f).toLowerCase(),R=!0}}u.byteLength=me;function Ie(l,f,v){let C=!1;if((f===void 0||f<0)&&(f=0),f>this.length||((v===void 0||v>this.length)&&(v=this.length),v<=0)||(v>>>=0,f>>>=0,v<=f))return"";for(l||(l="utf8");;)switch(l){case"hex":return As(this,f,v);case"utf8":case"utf-8":return q(this,f,v);case"ascii":return Rn(this,f,v);case"latin1":case"binary":return Ps(this,f,v);case"base64":return Xe(this,f,v);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ms(this,f,v);default:if(C)throw new TypeError("Unknown encoding: "+l);l=(l+"").toLowerCase(),C=!0}}u.prototype._isBuffer=!0;function fe(l,f,v){const C=l[f];l[f]=l[v],l[v]=C}u.prototype.swap16=function(){const l=this.length;if(l%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let f=0;f<l;f+=2)fe(this,f,f+1);return this},u.prototype.swap32=function(){const l=this.length;if(l%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let f=0;f<l;f+=4)fe(this,f,f+3),fe(this,f+1,f+2);return this},u.prototype.swap64=function(){const l=this.length;if(l%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let f=0;f<l;f+=8)fe(this,f,f+7),fe(this,f+1,f+6),fe(this,f+2,f+5),fe(this,f+3,f+4);return this},u.prototype.toString=function(){const l=this.length;return l===0?"":arguments.length===0?q(this,0,l):Ie.apply(this,arguments)},u.prototype.toLocaleString=u.prototype.toString,u.prototype.equals=function(l){if(!u.isBuffer(l))throw new TypeError("Argument must be a Buffer");return this===l?!0:u.compare(this,l)===0},u.prototype.inspect=function(){let l="";const f=t.INSPECT_MAX_BYTES;return l=this.toString("hex",0,f).replace(/(.{2})/g,"$1 ").trim(),this.length>f&&(l+=" ... "),"<Buffer "+l+">"},i&&(u.prototype[i]=u.prototype.inspect),u.prototype.compare=function(l,f,v,C,R){if(Yn(l,r)&&(l=u.from(l,l.offset,l.byteLength)),!u.isBuffer(l))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof l);if(f===void 0&&(f=0),v===void 0&&(v=l?l.length:0),C===void 0&&(C=0),R===void 0&&(R=this.length),f<0||v>l.length||C<0||R>this.length)throw new RangeError("out of range index");if(C>=R&&f>=v)return 0;if(C>=R)return-1;if(f>=v)return 1;if(f>>>=0,v>>>=0,C>>>=0,R>>>=0,this===l)return 0;let U=R-C,J=v-f;const Pe=Math.min(U,J),_t=this.slice(C,R),je=l.slice(f,v);for(let Ae=0;Ae<Pe;++Ae)if(_t[Ae]!==je[Ae]){U=_t[Ae],J=je[Ae];break}return U<J?-1:J<U?1:0};function Je(l,f,v,C,R){if(l.length===0)return-1;if(typeof v=="string"?(C=v,v=0):v>2147483647?v=2147483647:v<-2147483648&&(v=-2147483648),v=+v,su(v)&&(v=R?0:l.length-1),v<0&&(v=l.length+v),v>=l.length){if(R)return-1;v=l.length-1}else if(v<0)if(R)v=0;else return-1;if(typeof f=="string"&&(f=u.from(f,C)),u.isBuffer(f))return f.length===0?-1:ht(l,f,v,C,R);if(typeof f=="number")return f=f&255,typeof r.prototype.indexOf=="function"?R?r.prototype.indexOf.call(l,f,v):r.prototype.lastIndexOf.call(l,f,v):ht(l,[f],v,C,R);throw new TypeError("val must be string, number or Buffer")}function ht(l,f,v,C,R){let U=1,J=l.length,Pe=f.length;if(C!==void 0&&(C=String(C).toLowerCase(),C==="ucs2"||C==="ucs-2"||C==="utf16le"||C==="utf-16le")){if(l.length<2||f.length<2)return-1;U=2,J/=2,Pe/=2,v/=2}function _t(Ae,ot){return U===1?Ae[ot]:Ae.readUInt16BE(ot*U)}let je;if(R){let Ae=-1;for(je=v;je<J;je++)if(_t(l,je)===_t(f,Ae===-1?0:je-Ae)){if(Ae===-1&&(Ae=je),je-Ae+1===Pe)return Ae*U}else Ae!==-1&&(je-=je-Ae),Ae=-1}else for(v+Pe>J&&(v=J-Pe),je=v;je>=0;je--){let Ae=!0;for(let ot=0;ot<Pe;ot++)if(_t(l,je+ot)!==_t(f,ot)){Ae=!1;break}if(Ae)return je}return-1}u.prototype.includes=function(l,f,v){return this.indexOf(l,f,v)!==-1},u.prototype.indexOf=function(l,f,v){return Je(this,l,f,v,!0)},u.prototype.lastIndexOf=function(l,f,v){return Je(this,l,f,v,!1)};function V(l,f,v,C){v=Number(v)||0;const R=l.length-v;C?(C=Number(C),C>R&&(C=R)):C=R;const U=f.length;C>U/2&&(C=U/2);let J;for(J=0;J<C;++J){const Pe=parseInt(f.substr(J*2,2),16);if(su(Pe))return J;l[v+J]=Pe}return J}function I(l,f,v,C){return Cc(iu(f,l.length-v),l,v,C)}function P(l,f,v,C){return Cc(_E(f),l,v,C)}function K(l,f,v,C){return Cc(Em(f),l,v,C)}function ye(l,f,v,C){return Cc(IE(f,l.length-v),l,v,C)}u.prototype.write=function(l,f,v,C){if(f===void 0)C="utf8",v=this.length,f=0;else if(v===void 0&&typeof f=="string")C=f,v=this.length,f=0;else if(isFinite(f))f=f>>>0,isFinite(v)?(v=v>>>0,C===void 0&&(C="utf8")):(C=v,v=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const R=this.length-f;if((v===void 0||v>R)&&(v=R),l.length>0&&(v<0||f<0)||f>this.length)throw new RangeError("Attempt to write outside buffer bounds");C||(C="utf8");let U=!1;for(;;)switch(C){case"hex":return V(this,l,f,v);case"utf8":case"utf-8":return I(this,l,f,v);case"ascii":case"latin1":case"binary":return P(this,l,f,v);case"base64":return K(this,l,f,v);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ye(this,l,f,v);default:if(U)throw new TypeError("Unknown encoding: "+C);C=(""+C).toLowerCase(),U=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Xe(l,f,v){return f===0&&v===l.length?e.fromByteArray(l):e.fromByteArray(l.slice(f,v))}function q(l,f,v){v=Math.min(l.length,v);const C=[];let R=f;for(;R<v;){const U=l[R];let J=null,Pe=U>239?4:U>223?3:U>191?2:1;if(R+Pe<=v){let _t,je,Ae,ot;switch(Pe){case 1:U<128&&(J=U);break;case 2:_t=l[R+1],(_t&192)===128&&(ot=(U&31)<<6|_t&63,ot>127&&(J=ot));break;case 3:_t=l[R+1],je=l[R+2],(_t&192)===128&&(je&192)===128&&(ot=(U&15)<<12|(_t&63)<<6|je&63,ot>2047&&(ot<55296||ot>57343)&&(J=ot));break;case 4:_t=l[R+1],je=l[R+2],Ae=l[R+3],(_t&192)===128&&(je&192)===128&&(Ae&192)===128&&(ot=(U&15)<<18|(_t&63)<<12|(je&63)<<6|Ae&63,ot>65535&&ot<1114112&&(J=ot))}}J===null?(J=65533,Pe=1):J>65535&&(J-=65536,C.push(J>>>10&1023|55296),J=56320|J&1023),C.push(J),R+=Pe}return Ze(C)}const N=4096;function Ze(l){const f=l.length;if(f<=N)return String.fromCharCode.apply(String,l);let v="",C=0;for(;C<f;)v+=String.fromCharCode.apply(String,l.slice(C,C+=N));return v}function Rn(l,f,v){let C="";v=Math.min(l.length,v);for(let R=f;R<v;++R)C+=String.fromCharCode(l[R]&127);return C}function Ps(l,f,v){let C="";v=Math.min(l.length,v);for(let R=f;R<v;++R)C+=String.fromCharCode(l[R]);return C}function As(l,f,v){const C=l.length;(!f||f<0)&&(f=0),(!v||v<0||v>C)&&(v=C);let R="";for(let U=f;U<v;++U)R+=CE[l[U]];return R}function Ms(l,f,v){const C=l.slice(f,v);let R="";for(let U=0;U<C.length-1;U+=2)R+=String.fromCharCode(C[U]+C[U+1]*256);return R}u.prototype.slice=function(l,f){const v=this.length;l=~~l,f=f===void 0?v:~~f,l<0?(l+=v,l<0&&(l=0)):l>v&&(l=v),f<0?(f+=v,f<0&&(f=0)):f>v&&(f=v),f<l&&(f=l);const C=this.subarray(l,f);return Object.setPrototypeOf(C,u.prototype),C};function Fe(l,f,v){if(l%1!==0||l<0)throw new RangeError("offset is not uint");if(l+f>v)throw new RangeError("Trying to access beyond buffer length")}u.prototype.readUintLE=u.prototype.readUIntLE=function(l,f,v){l=l>>>0,f=f>>>0,v||Fe(l,f,this.length);let C=this[l],R=1,U=0;for(;++U<f&&(R*=256);)C+=this[l+U]*R;return C},u.prototype.readUintBE=u.prototype.readUIntBE=function(l,f,v){l=l>>>0,f=f>>>0,v||Fe(l,f,this.length);let C=this[l+--f],R=1;for(;f>0&&(R*=256);)C+=this[l+--f]*R;return C},u.prototype.readUint8=u.prototype.readUInt8=function(l,f){return l=l>>>0,f||Fe(l,1,this.length),this[l]},u.prototype.readUint16LE=u.prototype.readUInt16LE=function(l,f){return l=l>>>0,f||Fe(l,2,this.length),this[l]|this[l+1]<<8},u.prototype.readUint16BE=u.prototype.readUInt16BE=function(l,f){return l=l>>>0,f||Fe(l,2,this.length),this[l]<<8|this[l+1]},u.prototype.readUint32LE=u.prototype.readUInt32LE=function(l,f){return l=l>>>0,f||Fe(l,4,this.length),(this[l]|this[l+1]<<8|this[l+2]<<16)+this[l+3]*16777216},u.prototype.readUint32BE=u.prototype.readUInt32BE=function(l,f){return l=l>>>0,f||Fe(l,4,this.length),this[l]*16777216+(this[l+1]<<16|this[l+2]<<8|this[l+3])},u.prototype.readBigUInt64LE=ji(function(l){l=l>>>0,ge(l,"offset");const f=this[l],v=this[l+7];(f===void 0||v===void 0)&&pe(l,this.length-8);const C=f+this[++l]*Oe(2,8)+this[++l]*Oe(2,16)+this[++l]*Oe(2,24),R=this[++l]+this[++l]*Oe(2,8)+this[++l]*Oe(2,16)+v*Oe(2,24);return BigInt(C)+(BigInt(R)<<BigInt(32))}),u.prototype.readBigUInt64BE=ji(function(l){l=l>>>0,ge(l,"offset");const f=this[l],v=this[l+7];(f===void 0||v===void 0)&&pe(l,this.length-8);const C=f*Oe(2,24)+this[++l]*Oe(2,16)+this[++l]*Oe(2,8)+this[++l],R=this[++l]*Oe(2,24)+this[++l]*Oe(2,16)+this[++l]*Oe(2,8)+v;return(BigInt(C)<<BigInt(32))+BigInt(R)}),u.prototype.readIntLE=function(l,f,v){l=l>>>0,f=f>>>0,v||Fe(l,f,this.length);let C=this[l],R=1,U=0;for(;++U<f&&(R*=256);)C+=this[l+U]*R;return R*=128,C>=R&&(C-=Math.pow(2,8*f)),C},u.prototype.readIntBE=function(l,f,v){l=l>>>0,f=f>>>0,v||Fe(l,f,this.length);let C=f,R=1,U=this[l+--C];for(;C>0&&(R*=256);)U+=this[l+--C]*R;return R*=128,U>=R&&(U-=Math.pow(2,8*f)),U},u.prototype.readInt8=function(l,f){return l=l>>>0,f||Fe(l,1,this.length),this[l]&128?(255-this[l]+1)*-1:this[l]},u.prototype.readInt16LE=function(l,f){l=l>>>0,f||Fe(l,2,this.length);const v=this[l]|this[l+1]<<8;return v&32768?v|4294901760:v},u.prototype.readInt16BE=function(l,f){l=l>>>0,f||Fe(l,2,this.length);const v=this[l+1]|this[l]<<8;return v&32768?v|4294901760:v},u.prototype.readInt32LE=function(l,f){return l=l>>>0,f||Fe(l,4,this.length),this[l]|this[l+1]<<8|this[l+2]<<16|this[l+3]<<24},u.prototype.readInt32BE=function(l,f){return l=l>>>0,f||Fe(l,4,this.length),this[l]<<24|this[l+1]<<16|this[l+2]<<8|this[l+3]},u.prototype.readBigInt64LE=ji(function(l){l=l>>>0,ge(l,"offset");const f=this[l],v=this[l+7];(f===void 0||v===void 0)&&pe(l,this.length-8);const C=this[l+4]+this[l+5]*Oe(2,8)+this[l+6]*Oe(2,16)+(v<<24);return(BigInt(C)<<BigInt(32))+BigInt(f+this[++l]*Oe(2,8)+this[++l]*Oe(2,16)+this[++l]*Oe(2,24))}),u.prototype.readBigInt64BE=ji(function(l){l=l>>>0,ge(l,"offset");const f=this[l],v=this[l+7];(f===void 0||v===void 0)&&pe(l,this.length-8);const C=(f<<24)+this[++l]*Oe(2,16)+this[++l]*Oe(2,8)+this[++l];return(BigInt(C)<<BigInt(32))+BigInt(this[++l]*Oe(2,24)+this[++l]*Oe(2,16)+this[++l]*Oe(2,8)+v)}),u.prototype.readFloatLE=function(l,f){return l=l>>>0,f||Fe(l,4,this.length),n.read(this,l,!0,23,4)},u.prototype.readFloatBE=function(l,f){return l=l>>>0,f||Fe(l,4,this.length),n.read(this,l,!1,23,4)},u.prototype.readDoubleLE=function(l,f){return l=l>>>0,f||Fe(l,8,this.length),n.read(this,l,!0,52,8)},u.prototype.readDoubleBE=function(l,f){return l=l>>>0,f||Fe(l,8,this.length),n.read(this,l,!1,52,8)};function at(l,f,v,C,R,U){if(!u.isBuffer(l))throw new TypeError('"buffer" argument must be a Buffer instance');if(f>R||f<U)throw new RangeError('"value" argument is out of bounds');if(v+C>l.length)throw new RangeError("Index out of range")}u.prototype.writeUintLE=u.prototype.writeUIntLE=function(l,f,v,C){if(l=+l,f=f>>>0,v=v>>>0,!C){const J=Math.pow(2,8*v)-1;at(this,l,f,v,J,0)}let R=1,U=0;for(this[f]=l&255;++U<v&&(R*=256);)this[f+U]=l/R&255;return f+v},u.prototype.writeUintBE=u.prototype.writeUIntBE=function(l,f,v,C){if(l=+l,f=f>>>0,v=v>>>0,!C){const J=Math.pow(2,8*v)-1;at(this,l,f,v,J,0)}let R=v-1,U=1;for(this[f+R]=l&255;--R>=0&&(U*=256);)this[f+R]=l/U&255;return f+v},u.prototype.writeUint8=u.prototype.writeUInt8=function(l,f,v){return l=+l,f=f>>>0,v||at(this,l,f,1,255,0),this[f]=l&255,f+1},u.prototype.writeUint16LE=u.prototype.writeUInt16LE=function(l,f,v){return l=+l,f=f>>>0,v||at(this,l,f,2,65535,0),this[f]=l&255,this[f+1]=l>>>8,f+2},u.prototype.writeUint16BE=u.prototype.writeUInt16BE=function(l,f,v){return l=+l,f=f>>>0,v||at(this,l,f,2,65535,0),this[f]=l>>>8,this[f+1]=l&255,f+2},u.prototype.writeUint32LE=u.prototype.writeUInt32LE=function(l,f,v){return l=+l,f=f>>>0,v||at(this,l,f,4,4294967295,0),this[f+3]=l>>>24,this[f+2]=l>>>16,this[f+1]=l>>>8,this[f]=l&255,f+4},u.prototype.writeUint32BE=u.prototype.writeUInt32BE=function(l,f,v){return l=+l,f=f>>>0,v||at(this,l,f,4,4294967295,0),this[f]=l>>>24,this[f+1]=l>>>16,this[f+2]=l>>>8,this[f+3]=l&255,f+4};function Ni(l,f,v,C,R){Fi(f,C,R,l,v,7);let U=Number(f&BigInt(4294967295));l[v++]=U,U=U>>8,l[v++]=U,U=U>>8,l[v++]=U,U=U>>8,l[v++]=U;let J=Number(f>>BigInt(32)&BigInt(4294967295));return l[v++]=J,J=J>>8,l[v++]=J,J=J>>8,l[v++]=J,J=J>>8,l[v++]=J,v}function Li(l,f,v,C,R){Fi(f,C,R,l,v,7);let U=Number(f&BigInt(4294967295));l[v+7]=U,U=U>>8,l[v+6]=U,U=U>>8,l[v+5]=U,U=U>>8,l[v+4]=U;let J=Number(f>>BigInt(32)&BigInt(4294967295));return l[v+3]=J,J=J>>8,l[v+2]=J,J=J>>8,l[v+1]=J,J=J>>8,l[v]=J,v+8}u.prototype.writeBigUInt64LE=ji(function(l,f=0){return Ni(this,l,f,BigInt(0),BigInt("0xffffffffffffffff"))}),u.prototype.writeBigUInt64BE=ji(function(l,f=0){return Li(this,l,f,BigInt(0),BigInt("0xffffffffffffffff"))}),u.prototype.writeIntLE=function(l,f,v,C){if(l=+l,f=f>>>0,!C){const Pe=Math.pow(2,8*v-1);at(this,l,f,v,Pe-1,-Pe)}let R=0,U=1,J=0;for(this[f]=l&255;++R<v&&(U*=256);)l<0&&J===0&&this[f+R-1]!==0&&(J=1),this[f+R]=(l/U>>0)-J&255;return f+v},u.prototype.writeIntBE=function(l,f,v,C){if(l=+l,f=f>>>0,!C){const Pe=Math.pow(2,8*v-1);at(this,l,f,v,Pe-1,-Pe)}let R=v-1,U=1,J=0;for(this[f+R]=l&255;--R>=0&&(U*=256);)l<0&&J===0&&this[f+R+1]!==0&&(J=1),this[f+R]=(l/U>>0)-J&255;return f+v},u.prototype.writeInt8=function(l,f,v){return l=+l,f=f>>>0,v||at(this,l,f,1,127,-128),l<0&&(l=255+l+1),this[f]=l&255,f+1},u.prototype.writeInt16LE=function(l,f,v){return l=+l,f=f>>>0,v||at(this,l,f,2,32767,-32768),this[f]=l&255,this[f+1]=l>>>8,f+2},u.prototype.writeInt16BE=function(l,f,v){return l=+l,f=f>>>0,v||at(this,l,f,2,32767,-32768),this[f]=l>>>8,this[f+1]=l&255,f+2},u.prototype.writeInt32LE=function(l,f,v){return l=+l,f=f>>>0,v||at(this,l,f,4,2147483647,-2147483648),this[f]=l&255,this[f+1]=l>>>8,this[f+2]=l>>>16,this[f+3]=l>>>24,f+4},u.prototype.writeInt32BE=function(l,f,v){return l=+l,f=f>>>0,v||at(this,l,f,4,2147483647,-2147483648),l<0&&(l=4294967295+l+1),this[f]=l>>>24,this[f+1]=l>>>16,this[f+2]=l>>>8,this[f+3]=l&255,f+4},u.prototype.writeBigInt64LE=ji(function(l,f=0){return Ni(this,l,f,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),u.prototype.writeBigInt64BE=ji(function(l,f=0){return Li(this,l,f,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function xi(l,f,v,C,R,U){if(v+C>l.length)throw new RangeError("Index out of range");if(v<0)throw new RangeError("Index out of range")}function Vi(l,f,v,C,R){return f=+f,v=v>>>0,R||xi(l,f,v,4),n.write(l,f,v,C,23,4),v+4}u.prototype.writeFloatLE=function(l,f,v){return Vi(this,l,f,!0,v)},u.prototype.writeFloatBE=function(l,f,v){return Vi(this,l,f,!1,v)};function Ui(l,f,v,C,R){return f=+f,v=v>>>0,R||xi(l,f,v,8),n.write(l,f,v,C,52,8),v+8}u.prototype.writeDoubleLE=function(l,f,v){return Ui(this,l,f,!0,v)},u.prototype.writeDoubleBE=function(l,f,v){return Ui(this,l,f,!1,v)},u.prototype.copy=function(l,f,v,C){if(!u.isBuffer(l))throw new TypeError("argument should be a Buffer");if(v||(v=0),!C&&C!==0&&(C=this.length),f>=l.length&&(f=l.length),f||(f=0),C>0&&C<v&&(C=v),C===v||l.length===0||this.length===0)return 0;if(f<0)throw new RangeError("targetStart out of bounds");if(v<0||v>=this.length)throw new RangeError("Index out of range");if(C<0)throw new RangeError("sourceEnd out of bounds");C>this.length&&(C=this.length),l.length-f<C-v&&(C=l.length-f+v);const R=C-v;return this===l&&typeof r.prototype.copyWithin=="function"?this.copyWithin(f,v,C):r.prototype.set.call(l,this.subarray(v,C),f),R},u.prototype.fill=function(l,f,v,C){if(typeof l=="string"){if(typeof f=="string"?(C=f,f=0,v=this.length):typeof v=="string"&&(C=v,v=this.length),C!==void 0&&typeof C!="string")throw new TypeError("encoding must be a string");if(typeof C=="string"&&!u.isEncoding(C))throw new TypeError("Unknown encoding: "+C);if(l.length===1){const U=l.charCodeAt(0);(C==="utf8"&&U<128||C==="latin1")&&(l=U)}}else typeof l=="number"?l=l&255:typeof l=="boolean"&&(l=Number(l));if(f<0||this.length<f||this.length<v)throw new RangeError("Out of range index");if(v<=f)return this;f=f>>>0,v=v===void 0?this.length:v>>>0,l||(l=0);let R;if(typeof l=="number")for(R=f;R<v;++R)this[R]=l;else{const U=u.isBuffer(l)?l:u.from(l,C),J=U.length;if(J===0)throw new TypeError('The value "'+l+'" is invalid for argument "value"');for(R=0;R<v-f;++R)this[R+f]=U[R%J]}return this};const En={};function hi(l,f,v){En[l]=class extends v{constructor(){super(),Object.defineProperty(this,"message",{value:f.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${l}]`,this.stack,delete this.name}get code(){return l}set code(C){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:C,writable:!0})}toString(){return`${this.name} [${l}]: ${this.message}`}}}hi("ERR_BUFFER_OUT_OF_BOUNDS",function(l){return l?`${l} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),hi("ERR_INVALID_ARG_TYPE",function(l,f){return`The "${l}" argument must be of type number. Received type ${typeof f}`},TypeError),hi("ERR_OUT_OF_RANGE",function(l,f,v){let C=`The value of "${l}" is out of range.`,R=v;return Number.isInteger(v)&&Math.abs(v)>Oe(2,32)?R=Bi(String(v)):typeof v=="bigint"&&(R=String(v),(v>Oe(BigInt(2),BigInt(32))||v<-Oe(BigInt(2),BigInt(32)))&&(R=Bi(R)),R+="n"),C+=` It must be ${f}. Received ${R}`,C},RangeError);function Bi(l){let f="",v=l.length;const C=l[0]==="-"?1:0;for(;v>=C+4;v-=3)f=`_${l.slice(v-3,v)}${f}`;return`${l.slice(0,v)}${f}`}function Os(l,f,v){ge(f,"offset"),(l[f]===void 0||l[f+v]===void 0)&&pe(f,l.length-(v+1))}function Fi(l,f,v,C,R,U){if(l>v||l<f){const J=typeof f=="bigint"?"n":"";let Pe;throw U>3?f===0||f===BigInt(0)?Pe=`>= 0${J} and < 2${J} ** ${(U+1)*8}${J}`:Pe=`>= -(2${J} ** ${(U+1)*8-1}${J}) and < 2 ** ${(U+1)*8-1}${J}`:Pe=`>= ${f}${J} and <= ${v}${J}`,new En.ERR_OUT_OF_RANGE("value",Pe,l)}Os(C,R,U)}function ge(l,f){if(typeof l!="number")throw new En.ERR_INVALID_ARG_TYPE(f,"number",l)}function pe(l,f,v){throw Math.floor(l)!==l?(ge(l,v),new En.ERR_OUT_OF_RANGE(v||"offset","an integer",l)):f<0?new En.ERR_BUFFER_OUT_OF_BOUNDS:new En.ERR_OUT_OF_RANGE(v||"offset",`>= ${v?1:0} and <= ${f}`,l)}const Oa=/[^+/0-9A-Za-z-_]/g;function wE(l){if(l=l.split("=")[0],l=l.trim().replace(Oa,""),l.length<2)return"";for(;l.length%4!==0;)l=l+"=";return l}function iu(l,f){f=f||1/0;let v;const C=l.length;let R=null;const U=[];for(let J=0;J<C;++J){if(v=l.charCodeAt(J),v>55295&&v<57344){if(!R){if(v>56319){(f-=3)>-1&&U.push(239,191,189);continue}else if(J+1===C){(f-=3)>-1&&U.push(239,191,189);continue}R=v;continue}if(v<56320){(f-=3)>-1&&U.push(239,191,189),R=v;continue}v=(R-55296<<10|v-56320)+65536}else R&&(f-=3)>-1&&U.push(239,191,189);if(R=null,v<128){if((f-=1)<0)break;U.push(v)}else if(v<2048){if((f-=2)<0)break;U.push(v>>6|192,v&63|128)}else if(v<65536){if((f-=3)<0)break;U.push(v>>12|224,v>>6&63|128,v&63|128)}else if(v<1114112){if((f-=4)<0)break;U.push(v>>18|240,v>>12&63|128,v>>6&63|128,v&63|128)}else throw new Error("Invalid code point")}return U}function _E(l){const f=[];for(let v=0;v<l.length;++v)f.push(l.charCodeAt(v)&255);return f}function IE(l,f){let v,C,R;const U=[];for(let J=0;J<l.length&&!((f-=2)<0);++J)v=l.charCodeAt(J),C=v>>8,R=v%256,U.push(R),U.push(C);return U}function Em(l){return e.toByteArray(wE(l))}function Cc(l,f,v,C){let R;for(R=0;R<C&&!(R+v>=f.length||R>=l.length);++R)f[R+v]=l[R];return R}function Yn(l,f){return l instanceof f||l!=null&&l.constructor!=null&&l.constructor.name!=null&&l.constructor.name===f.name}function su(l){return l!==l}const CE=function(){const l="0123456789abcdef",f=new Array(256);for(let v=0;v<16;++v){const C=v*16;for(let R=0;R<16;++R)f[C+R]=l[v]+l[R]}return f}();function ji(l){return typeof BigInt=="undefined"?RE:l}function RE(){throw new Error("BigInt not supported")}})(vt);const YT=vt.Buffer;vt.Blob;vt.BlobOptions;vt.Buffer;vt.File;vt.FileOptions;vt.INSPECT_MAX_BYTES;vt.SlowBuffer;vt.TranscodeEncoding;vt.atob;vt.btoa;vt.constants;vt.isAscii;vt.isUtf8;vt.kMaxLength;vt.kStringMaxLength;vt.resolveObjectURL;vt.transcode;var Kv=gt;function Sa(t,e,n,i,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),n&&(this.config=n),i&&(this.request=i),s&&(this.response=s)}Kv.inherits(Sa,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var zv=Sa.prototype,Yv={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(function(t){Yv[t]={value:t}});Object.defineProperties(Sa,Yv);Object.defineProperty(zv,"isAxiosError",{value:!0});Sa.from=function(t,e,n,i,s,r){var a=Object.create(zv);return Kv.toFlatObject(t,a,function(c){return c!==Error.prototype}),Sa.call(a,t.message,e,n,i,s),a.cause=t,a.name=t.name,r&&Object.assign(a,r),a};var Tr=Sa,lh={},QT={get exports(){return lh},set exports(t){lh=t}},XT=typeof self=="object"?self.FormData:window.FormData;(function(t){t.exports=XT})(QT);var Le=gt,ZT=Tr,eb=lh;function uh(t){return Le.isPlainObject(t)||Le.isArray(t)}function Qv(t){return Le.endsWith(t,"[]")?t.slice(0,-2):t}function Bm(t,e,n){return t?t.concat(e).map(function(i,s){return i=Qv(i),!n&&s?"["+i+"]":i}).join(n?".":""):e}function tb(t){return Le.isArray(t)&&!t.some(uh)}var nb=Le.toFlatObject(Le,{},null,function(t){return/^is[A-Z]/.test(t)});function ib(t){return t&&Le.isFunction(t.append)&&t[Symbol.toStringTag]==="FormData"&&t[Symbol.iterator]}function sb(t,e,n){if(!Le.isObject(t))throw new TypeError("target must be an object");e=e||new(eb||FormData),n=Le.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(w,M){return!Le.isUndefined(M[w])});var i=n.metaTokens,s=n.visitor||u,r=n.dots,a=n.indexes,c=n.Blob||typeof Blob!="undefined"&&Blob,d=c&&ib(e);if(!Le.isFunction(s))throw new TypeError("visitor must be a function");function h(w){if(w===null)return"";if(Le.isDate(w))return w.toISOString();if(!d&&Le.isBlob(w))throw new ZT("Blob is not supported. Use a Buffer instead.");return Le.isArrayBuffer(w)||Le.isTypedArray(w)?d&&typeof Blob=="function"?new Blob([w]):YT.from(w):w}function u(w,M,D){var F=w;if(w&&!D&&typeof w=="object"){if(Le.endsWith(M,"{}"))M=i?M:M.slice(0,-2),w=JSON.stringify(w);else if(Le.isArray(w)&&tb(w)||Le.isFileList(w)||Le.endsWith(M,"[]")&&(F=Le.toArray(w)))return M=Qv(M),F.forEach(function(Y,X){!Le.isUndefined(Y)&&e.append(a===!0?Bm([M],X,r):a===null?M:M+"[]",h(Y))}),!1}return uh(w)?!0:(e.append(Bm(D,M,r),h(w)),!1)}var g=[],E=Object.assign(nb,{defaultVisitor:u,convertValue:h,isVisitable:uh});function b(w,M){if(!Le.isUndefined(w)){if(g.indexOf(w)!==-1)throw Error("Circular reference detected in "+M.join("."));g.push(w),Le.forEach(w,function(D,F){var Y=!Le.isUndefined(D)&&s.call(e,D,Le.isString(F)?F.trim():F,M,E);Y===!0&&b(D,M?M.concat(F):[F])}),g.pop()}}if(!Le.isObject(t))throw new TypeError("data must be an object");return b(t),e}var xl=sb,rb=xl;function Fm(t){var e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'\(\)~]|%20|%00/g,function(n){return e[n]})}function Xv(t,e){this._pairs=[],t&&rb(t,this,e)}var Zv=Xv.prototype;Zv.append=function(t,e){this._pairs.push([t,e])};Zv.toString=function(t){var e=t?function(n){return t.call(this,n,Fm)}:Fm;return this._pairs.map(function(n){return e(n[0])+"="+e(n[1])},"").join("&")};var ey=Xv,ab=gt,ob=ey;function cb(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var ty=function(t,e,n){if(!e)return t;var i=t.indexOf("#");i!==-1&&(t=t.slice(0,i));var s=n&&n.encode||cb,r=n&&n.serialize,a;return r?a=r(e,n):a=ab.isURLSearchParams(e)?e.toString():new ob(e,n).toString(s),a&&(t+=(t.indexOf("?")===-1?"?":"&")+a),t},db=gt;function fc(){this.handlers=[]}fc.prototype.use=function(t,e,n){return this.handlers.push({fulfilled:t,rejected:e,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1};fc.prototype.eject=function(t){this.handlers[t]&&(this.handlers[t]=null)};fc.prototype.clear=function(){this.handlers&&(this.handlers=[])};fc.prototype.forEach=function(t){db.forEach(this.handlers,function(e){e!==null&&t(e)})};var lb=fc,ub=gt,ny=function(t,e){ub.forEach(t,function(n,i){i!==e&&i.toUpperCase()===e.toUpperCase()&&(t[e]=n,delete t[i])})},iy={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},dc={},hb={get exports(){return dc},set exports(t){dc=t}},pb=ey,mb=typeof URLSearchParams!="undefined"?URLSearchParams:pb,fb=FormData,gb={isBrowser:!0,classes:{URLSearchParams:mb,FormData:fb,Blob},protocols:["http","https","file","blob","url","data"]};(function(t){t.exports=gb})(hb);var vb=gt,yb=xl,jm=dc,Eb=function(t,e){return yb(t,new jm.classes.URLSearchParams,Object.assign({visitor:function(n,i,s,r){return jm.isNode&&vb.isBuffer(n)?(this.append(i,n.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)}},e))},Yi=gt;function Sb(t){return Yi.matchAll(/\w+|\[(\w*)]/g,t).map(function(e){return e[0]==="[]"?"":e[1]||e[0]})}function Tb(t){var e={},n=Object.keys(t),i,s=n.length,r;for(i=0;i<s;i++)r=n[i],e[r]=t[r];return e}function bb(t){function e(i,s,r,a){var c=i[a++],d=Number.isFinite(+c),h=a>=i.length;if(c=!c&&Yi.isArray(r)?r.length:c,h)return Yi.hasOwnProperty(r,c)?r[c]=[r[c],s]:r[c]=s,!d;(!r[c]||!Yi.isObject(r[c]))&&(r[c]=[]);var u=e(i,s,r[c],a);return u&&Yi.isArray(r[c])&&(r[c]=Tb(r[c])),!d}if(Yi.isFormData(t)&&Yi.isFunction(t.entries)){var n={};return Yi.forEachEntry(t,function(i,s){e(Sb(i),s,n,0)}),n}return null}var sy=bb,lu,Wm;function kb(){if(Wm)return lu;Wm=1;var t=Tr;return lu=function(e,n,i){var s=i.config.validateStatus;!i.status||!s||s(i.status)?e(i):n(new t("Request failed with status code "+i.status,[t.ERR_BAD_REQUEST,t.ERR_BAD_RESPONSE][Math.floor(i.status/100)-4],i.config,i.request,i))},lu}var uu,Hm;function wb(){if(Hm)return uu;Hm=1;var t=gt;return uu=t.isStandardBrowserEnv()?function(){return{write:function(e,n,i,s,r,a){var c=[];c.push(e+"="+encodeURIComponent(n)),t.isNumber(i)&&c.push("expires="+new Date(i).toGMTString()),t.isString(s)&&c.push("path="+s),t.isString(r)&&c.push("domain="+r),a===!0&&c.push("secure"),document.cookie=c.join("; ")},read:function(e){var n=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return n?decodeURIComponent(n[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}(),uu}var _b=function(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)},Ib=function(t,e){return e?t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):t},Cb=_b,Rb=Ib,ry=function(t,e){return t&&!Cb(e)?Rb(t,e):e},hu,qm;function Pb(){if(qm)return hu;qm=1;var t=gt,e=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];return hu=function(n){var i={},s,r,a;return n&&t.forEach(n.split(`
18
+ `),function(c){if(a=c.indexOf(":"),s=t.trim(c.slice(0,a)).toLowerCase(),r=t.trim(c.slice(a+1)),s){if(i[s]&&e.indexOf(s)>=0)return;s==="set-cookie"?i[s]=(i[s]?i[s]:[]).concat([r]):i[s]=i[s]?i[s]+", "+r:r}}),i},hu}var pu,Gm;function Ab(){if(Gm)return pu;Gm=1;var t=gt;return pu=t.isStandardBrowserEnv()?function(){var e=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a"),i;function s(r){var a=r;return e&&(n.setAttribute("href",a),a=n.href),n.setAttribute("href",a),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return i=s(window.location.href),function(r){var a=t.isString(r)?s(r):r;return a.protocol===i.protocol&&a.host===i.host}}():function(){return function(){return!0}}(),pu}var mu,$m;function Vl(){if($m)return mu;$m=1;var t=Tr,e=gt;function n(i,s,r){t.call(this,i==null?"canceled":i,t.ERR_CANCELED,s,r),this.name="CanceledError"}return e.inherits(n,t,{__CANCEL__:!0}),mu=n,mu}var Jm,Km;function Mb(){return Km||(Km=1,Jm=function(t){var e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}),Jm}var fu,zm;function Ob(){if(zm)return fu;zm=1;var t=gt,e=kb(),n=wb(),i=ty,s=ry,r=Pb(),a=Ab(),c=iy,d=Tr,h=Vl(),u=Mb(),g=dc;return fu=function(E){return new Promise(function(b,w){var M=E.data,D=E.headers,F=E.responseType,Y=E.withXSRFToken,X;function A(){E.cancelToken&&E.cancelToken.unsubscribe(X),E.signal&&E.signal.removeEventListener("abort",X)}t.isFormData(M)&&t.isStandardBrowserEnv()&&delete D["Content-Type"];var $=new XMLHttpRequest;if(E.auth){var me=E.auth.username||"",Ie=E.auth.password?unescape(encodeURIComponent(E.auth.password)):"";D.Authorization="Basic "+btoa(me+":"+Ie)}var fe=s(E.baseURL,E.url);$.open(E.method.toUpperCase(),i(fe,E.params,E.paramsSerializer),!0),$.timeout=E.timeout;function Je(){if($){var I="getAllResponseHeaders"in $?r($.getAllResponseHeaders()):null,P=!F||F==="text"||F==="json"?$.responseText:$.response,K={data:P,status:$.status,statusText:$.statusText,headers:I,config:E,request:$};e(function(ye){b(ye),A()},function(ye){w(ye),A()},K),$=null}}if("onloadend"in $?$.onloadend=Je:$.onreadystatechange=function(){!$||$.readyState!==4||$.status===0&&!($.responseURL&&$.responseURL.indexOf("file:")===0)||setTimeout(Je)},$.onabort=function(){$&&(w(new d("Request aborted",d.ECONNABORTED,E,$)),$=null)},$.onerror=function(){w(new d("Network Error",d.ERR_NETWORK,E,$)),$=null},$.ontimeout=function(){var I=E.timeout?"timeout of "+E.timeout+"ms exceeded":"timeout exceeded",P=E.transitional||c;E.timeoutErrorMessage&&(I=E.timeoutErrorMessage),w(new d(I,P.clarifyTimeoutError?d.ETIMEDOUT:d.ECONNABORTED,E,$)),$=null},t.isStandardBrowserEnv()&&(Y&&t.isFunction(Y)&&(Y=Y(E)),Y||Y!==!1&&a(fe))){var ht=E.xsrfHeaderName&&E.xsrfCookieName&&n.read(E.xsrfCookieName);ht&&(D[E.xsrfHeaderName]=ht)}"setRequestHeader"in $&&t.forEach(D,function(I,P){typeof M=="undefined"&&P.toLowerCase()==="content-type"?delete D[P]:$.setRequestHeader(P,I)}),t.isUndefined(E.withCredentials)||($.withCredentials=!!E.withCredentials),F&&F!=="json"&&($.responseType=E.responseType),typeof E.onDownloadProgress=="function"&&$.addEventListener("progress",E.onDownloadProgress),typeof E.onUploadProgress=="function"&&$.upload&&$.upload.addEventListener("progress",E.onUploadProgress),(E.cancelToken||E.signal)&&(X=function(I){$&&(w(!I||I.type?new h(null,E,$):I),$.abort(),$=null)},E.cancelToken&&E.cancelToken.subscribe(X),E.signal&&(E.signal.aborted?X():E.signal.addEventListener("abort",X))),!M&&M!==!1&&M!==0&&M!==""&&(M=null);var V=u(fe);if(V&&g.protocols.indexOf(V)===-1){w(new d("Unsupported protocol "+V+":",d.ERR_BAD_REQUEST,E));return}$.send(M)})},fu}var ft=gt,Ym=ny,Qm=Tr,Db=iy,Nb=xl,Lb=Eb,Xm=dc,xb=sy,Vb={"Content-Type":"application/x-www-form-urlencoded"};function Zm(t,e){!ft.isUndefined(t)&&ft.isUndefined(t["Content-Type"])&&(t["Content-Type"]=e)}function Ub(){var t;return(typeof XMLHttpRequest!="undefined"||typeof dr!="undefined"&&Object.prototype.toString.call(dr)==="[object process]")&&(t=Ob()),t}function Bb(t,e,n){if(ft.isString(t))try{return(e||JSON.parse)(t),ft.trim(t)}catch(i){if(i.name!=="SyntaxError")throw i}return(n||JSON.stringify)(t)}var Ul={transitional:Db,adapter:Ub(),transformRequest:[function(t,e){Ym(e,"Accept"),Ym(e,"Content-Type");var n=e&&e["Content-Type"]||"",i=n.indexOf("application/json")>-1,s=ft.isObject(t);s&&ft.isHTMLForm(t)&&(t=new FormData(t));var r=ft.isFormData(t);if(r)return i?JSON.stringify(xb(t)):t;if(ft.isArrayBuffer(t)||ft.isBuffer(t)||ft.isStream(t)||ft.isFile(t)||ft.isBlob(t))return t;if(ft.isArrayBufferView(t))return t.buffer;if(ft.isURLSearchParams(t))return Zm(e,"application/x-www-form-urlencoded;charset=utf-8"),t.toString();var a;if(s){if(n.indexOf("application/x-www-form-urlencoded")!==-1)return Lb(t,this.formSerializer).toString();if((a=ft.isFileList(t))||n.indexOf("multipart/form-data")>-1){var c=this.env&&this.env.FormData;return Nb(a?{"files[]":t}:t,c&&new c,this.formSerializer)}}return s||i?(Zm(e,"application/json"),Bb(t)):t}],transformResponse:[function(t){var e=this.transitional||Ul.transitional,n=e&&e.forcedJSONParsing,i=this.responseType==="json";if(t&&ft.isString(t)&&(n&&!this.responseType||i)){var s=e&&e.silentJSONParsing,r=!s&&i;try{return JSON.parse(t)}catch(a){if(r)throw a.name==="SyntaxError"?Qm.from(a,Qm.ERR_BAD_RESPONSE,this,null,this.response):a}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Xm.classes.FormData,Blob:Xm.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};ft.forEach(["delete","get","head"],function(t){Ul.headers[t]={}});ft.forEach(["post","put","patch"],function(t){Ul.headers[t]=ft.merge(Vb)});var jp=Ul,Fb=gt,jb=jp,Wb=function(t,e,n,i){var s=this||jb;return Fb.forEach(i,function(r){t=r.call(s,t,e,n)}),t},ef,tf;function ay(){return tf||(tf=1,ef=function(t){return!!(t&&t.__CANCEL__)}),ef}var nf=gt,gu=Wb,Hb=ay(),qb=jp,Gb=Vl(),sf=ny;function vu(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new Gb}var $b=function(t){vu(t),t.headers=t.headers||{},t.data=gu.call(t,t.data,t.headers,null,t.transformRequest),sf(t.headers,"Accept"),sf(t.headers,"Content-Type"),t.headers=nf.merge(t.headers.common||{},t.headers[t.method]||{},t.headers),nf.forEach(["delete","get","head","post","put","patch","common"],function(n){delete t.headers[n]});var e=t.adapter||qb.adapter;return e(t).then(function(n){return vu(t),n.data=gu.call(t,n.data,n.headers,n.status,t.transformResponse),n},function(n){return Hb(n)||(vu(t),n&&n.response&&(n.response.data=gu.call(t,n.response.data,n.response.headers,n.response.status,t.transformResponse))),Promise.reject(n)})},Vt=gt,oy=function(t,e){e=e||{};var n={};function i(h,u){return Vt.isPlainObject(h)&&Vt.isPlainObject(u)?Vt.merge(h,u):Vt.isEmptyObject(u)?Vt.merge({},h):Vt.isPlainObject(u)?Vt.merge({},u):Vt.isArray(u)?u.slice():u}function s(h){if(Vt.isUndefined(e[h])){if(!Vt.isUndefined(t[h]))return i(void 0,t[h])}else return i(t[h],e[h])}function r(h){if(!Vt.isUndefined(e[h]))return i(void 0,e[h])}function a(h){if(Vt.isUndefined(e[h])){if(!Vt.isUndefined(t[h]))return i(void 0,t[h])}else return i(void 0,e[h])}function c(h){if(h in e)return i(t[h],e[h]);if(h in t)return i(void 0,t[h])}var d={url:r,method:r,data:r,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:c};return Vt.forEach(Object.keys(t).concat(Object.keys(e)),function(h){var u=d[h]||s,g=u(h);Vt.isUndefined(g)&&u!==c||(n[h]=g)}),n},rf,af;function cy(){return af||(af=1,rf={version:"0.28.1"}),rf}var Jb=cy().version,hs=Tr,Wp={};["object","boolean","number","function","string","symbol"].forEach(function(t,e){Wp[t]=function(n){return typeof n===t||"a"+(e<1?"n ":" ")+t}});var of={};Wp.transitional=function(t,e,n){function i(s,r){return"[Axios v"+Jb+"] Transitional option '"+s+"'"+r+(n?". "+n:"")}return function(s,r,a){if(t===!1)throw new hs(i(r," has been removed"+(e?" in "+e:"")),hs.ERR_DEPRECATED);return e&&!of[r]&&(of[r]=!0,console.warn(i(r," has been deprecated since v"+e+" and will be removed in the near future"))),t?t(s,r,a):!0}};function Kb(t,e,n){if(typeof t!="object")throw new hs("options must be an object",hs.ERR_BAD_OPTION_VALUE);for(var i=Object.keys(t),s=i.length;s-- >0;){var r=i[s],a=e[r];if(a){var c=t[r],d=c===void 0||a(c,r,t);if(d!==!0)throw new hs("option "+r+" must be "+d,hs.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new hs("Unknown option "+r,hs.ERR_BAD_OPTION)}}var zb={assertOptions:Kb,validators:Wp},Hp=gt,Yb=ty,cf=lb,df=$b,Bl=oy,Qb=ry,hh=zb,Wi=hh.validators;function Ta(t){this.defaults=t,this.interceptors={request:new cf,response:new cf}}Ta.prototype.request=function(t,e){typeof t=="string"?(e=e||{},e.url=t):e=t||{},e=Bl(this.defaults,e),e.method?e.method=e.method.toLowerCase():this.defaults.method?e.method=this.defaults.method.toLowerCase():e.method="get";var n=e.transitional;n!==void 0&&hh.assertOptions(n,{silentJSONParsing:Wi.transitional(Wi.boolean),forcedJSONParsing:Wi.transitional(Wi.boolean),clarifyTimeoutError:Wi.transitional(Wi.boolean)},!1);var i=e.paramsSerializer;i!==void 0&&hh.assertOptions(i,{encode:Wi.function,serialize:Wi.function},!0),Hp.isFunction(i)&&(e.paramsSerializer={serialize:i});var s=[],r=!0;this.interceptors.request.forEach(function(E){typeof E.runWhen=="function"&&E.runWhen(e)===!1||(r=r&&E.synchronous,s.unshift(E.fulfilled,E.rejected))});var a=[];this.interceptors.response.forEach(function(E){a.push(E.fulfilled,E.rejected)});var c;if(!r){var d=[df,void 0];for(Array.prototype.unshift.apply(d,s),d=d.concat(a),c=Promise.resolve(e);d.length;)c=c.then(d.shift(),d.shift());return c}for(var h=e;s.length;){var u=s.shift(),g=s.shift();try{h=u(h)}catch(E){g(E);break}}try{c=df(h)}catch(E){return Promise.reject(E)}for(;a.length;)c=c.then(a.shift(),a.shift());return c};Ta.prototype.getUri=function(t){t=Bl(this.defaults,t);var e=Qb(t.baseURL,t.url);return Yb(e,t.params,t.paramsSerializer)};Hp.forEach(["delete","get","head","options"],function(t){Ta.prototype[t]=function(e,n){return this.request(Bl(n||{},{method:t,url:e,data:(n||{}).data}))}});Hp.forEach(["post","put","patch"],function(t){function e(n){return function(i,s,r){return this.request(Bl(r||{},{method:t,headers:n?{"Content-Type":"multipart/form-data"}:{},url:i,data:s}))}}Ta.prototype[t]=e(),Ta.prototype[t+"Form"]=e(!0)});var Xb=Ta,yu,lf;function Zb(){if(lf)return yu;lf=1;var t=Vl();function e(n){if(typeof n!="function")throw new TypeError("executor must be a function.");var i;this.promise=new Promise(function(r){i=r});var s=this;this.promise.then(function(r){if(s._listeners){for(var a=s._listeners.length;a-- >0;)s._listeners[a](r);s._listeners=null}}),this.promise.then=function(r){var a,c=new Promise(function(d){s.subscribe(d),a=d}).then(r);return c.cancel=function(){s.unsubscribe(a)},c},n(function(r,a,c){s.reason||(s.reason=new t(r,a,c),i(s.reason))})}return e.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},e.prototype.subscribe=function(n){if(this.reason){n(this.reason);return}this._listeners?this._listeners.push(n):this._listeners=[n]},e.prototype.unsubscribe=function(n){if(this._listeners){var i=this._listeners.indexOf(n);i!==-1&&this._listeners.splice(i,1)}},e.source=function(){var n,i=new e(function(s){n=s});return{token:i,cancel:n}},yu=e,yu}var uf,hf;function ek(){return hf||(hf=1,uf=function(t){return function(e){return t.apply(null,e)}}),uf}var Eu,pf;function tk(){if(pf)return Eu;pf=1;var t=gt;return Eu=function(e){return t.isObject(e)&&e.isAxiosError===!0},Eu}var ph=gt,nk=Hv,ud=Xb,ik=oy,sk=jp,rk=sy;function dy(t){var e=new ud(t),n=nk(ud.prototype.request,e);return ph.extend(n,ud.prototype,e),ph.extend(n,e),n.create=function(i){return dy(ik(t,i))},n}var Yt=dy(sk);Yt.Axios=ud;Yt.CanceledError=Vl();Yt.CancelToken=Zb();Yt.isCancel=ay();Yt.VERSION=cy().version;Yt.toFormData=xl;Yt.AxiosError=Tr;Yt.Cancel=Yt.CanceledError;Yt.all=function(t){return Promise.all(t)};Yt.spread=ek();Yt.isAxiosError=tk();Yt.formToJSON=function(t){return rk(ph.isHTMLForm(t)?new FormData(t):t)};gT.exports=Yt;tl.default=Yt;(function(t){t.exports=tl})(fT);const ak=NS(oh);function ok(){this.__data__=[],this.size=0}function gc(t,e){return t===e||t!==t&&e!==e}function Fl(t,e){for(var n=t.length;n--;)if(gc(t[n][0],e))return n;return-1}var ck=Array.prototype,dk=ck.splice;function lk(t){var e=this.__data__,n=Fl(e,t);if(n<0)return!1;var i=e.length-1;return n==i?e.pop():dk.call(e,n,1),--this.size,!0}function uk(t){var e=this.__data__,n=Fl(e,t);return n<0?void 0:e[n][1]}function hk(t){return Fl(this.__data__,t)>-1}function pk(t,e){var n=this.__data__,i=Fl(n,t);return i<0?(++this.size,n.push([t,e])):n[i][1]=e,this}function Oi(t){var e=-1,n=t==null?0:t.length;for(this.clear();++e<n;){var i=t[e];this.set(i[0],i[1])}}Oi.prototype.clear=ok;Oi.prototype.delete=lk;Oi.prototype.get=uk;Oi.prototype.has=hk;Oi.prototype.set=pk;function mk(){this.__data__=new Oi,this.size=0}function fk(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n}function gk(t){return this.__data__.get(t)}function vk(t){return this.__data__.has(t)}const Oc=globalThis||void 0||self;var yk=typeof Oc=="object"&&Oc&&Oc.Object===Object&&Oc;const ly=yk;var Ek=typeof self=="object"&&self&&self.Object===Object&&self,Sk=ly||Ek||Function("return this")();const $n=Sk;var Tk=$n.Symbol;const Ts=Tk;var uy=Object.prototype,bk=uy.hasOwnProperty,kk=uy.toString,Na=Ts?Ts.toStringTag:void 0;function wk(t){var e=bk.call(t,Na),n=t[Na];try{t[Na]=void 0;var i=!0}catch(r){}var s=kk.call(t);return i&&(e?t[Na]=n:delete t[Na]),s}var _k=Object.prototype,Ik=_k.toString;function Ck(t){return Ik.call(t)}var Rk="[object Null]",Pk="[object Undefined]",mf=Ts?Ts.toStringTag:void 0;function br(t){return t==null?t===void 0?Pk:Rk:mf&&mf in Object(t)?wk(t):Ck(t)}function Gn(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var Ak="[object AsyncFunction]",Mk="[object Function]",Ok="[object GeneratorFunction]",Dk="[object Proxy]";function qp(t){if(!Gn(t))return!1;var e=br(t);return e==Mk||e==Ok||e==Ak||e==Dk}var Nk=$n["__core-js_shared__"];const Su=Nk;var ff=function(){var t=/[^.]+$/.exec(Su&&Su.keys&&Su.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();function Lk(t){return!!ff&&ff in t}var xk=Function.prototype,Vk=xk.toString;function kr(t){if(t!=null){try{return Vk.call(t)}catch(e){}try{return t+""}catch(e){}}return""}var Uk=/[\\^$.*+?()[\]{}|]/g,Bk=/^\[object .+?Constructor\]$/,Fk=Function.prototype,jk=Object.prototype,Wk=Fk.toString,Hk=jk.hasOwnProperty,qk=RegExp("^"+Wk.call(Hk).replace(Uk,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Gk(t){if(!Gn(t)||Lk(t))return!1;var e=qp(t)?qk:Bk;return e.test(kr(t))}function $k(t,e){return t==null?void 0:t[e]}function wr(t,e){var n=$k(t,e);return Gk(n)?n:void 0}var Jk=wr($n,"Map");const lc=Jk;var Kk=wr(Object,"create");const uc=Kk;function zk(){this.__data__=uc?uc(null):{},this.size=0}function Yk(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var Qk="__lodash_hash_undefined__",Xk=Object.prototype,Zk=Xk.hasOwnProperty;function ew(t){var e=this.__data__;if(uc){var n=e[t];return n===Qk?void 0:n}return Zk.call(e,t)?e[t]:void 0}var tw=Object.prototype,nw=tw.hasOwnProperty;function iw(t){var e=this.__data__;return uc?e[t]!==void 0:nw.call(e,t)}var sw="__lodash_hash_undefined__";function rw(t,e){var n=this.__data__;return this.size+=this.has(t)?0:1,n[t]=uc&&e===void 0?sw:e,this}function vr(t){var e=-1,n=t==null?0:t.length;for(this.clear();++e<n;){var i=t[e];this.set(i[0],i[1])}}vr.prototype.clear=zk;vr.prototype.delete=Yk;vr.prototype.get=ew;vr.prototype.has=iw;vr.prototype.set=rw;function aw(){this.size=0,this.__data__={hash:new vr,map:new(lc||Oi),string:new vr}}function ow(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function jl(t,e){var n=t.__data__;return ow(e)?n[typeof e=="string"?"string":"hash"]:n.map}function cw(t){var e=jl(this,t).delete(t);return this.size-=e?1:0,e}function dw(t){return jl(this,t).get(t)}function lw(t){return jl(this,t).has(t)}function uw(t,e){var n=jl(this,t),i=n.size;return n.set(t,e),this.size+=n.size==i?0:1,this}function _r(t){var e=-1,n=t==null?0:t.length;for(this.clear();++e<n;){var i=t[e];this.set(i[0],i[1])}}_r.prototype.clear=aw;_r.prototype.delete=cw;_r.prototype.get=dw;_r.prototype.has=lw;_r.prototype.set=uw;var hw=200;function pw(t,e){var n=this.__data__;if(n instanceof Oi){var i=n.__data__;if(!lc||i.length<hw-1)return i.push([t,e]),this.size=++n.size,this;n=this.__data__=new _r(i)}return n.set(t,e),this.size=n.size,this}function li(t){var e=this.__data__=new Oi(t);this.size=e.size}li.prototype.clear=mk;li.prototype.delete=fk;li.prototype.get=gk;li.prototype.has=vk;li.prototype.set=pw;function mw(t,e){for(var n=-1,i=t==null?0:t.length;++n<i&&e(t[n],n,t)!==!1;);return t}var fw=function(){try{var t=wr(Object,"defineProperty");return t({},"",{}),t}catch(e){}}();const nl=fw;function Gp(t,e,n){e=="__proto__"&&nl?nl(t,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):t[e]=n}var gw=Object.prototype,vw=gw.hasOwnProperty;function hy(t,e,n){var i=t[e];(!(vw.call(t,e)&&gc(i,n))||n===void 0&&!(e in t))&&Gp(t,e,n)}function vc(t,e,n,i){var s=!n;n||(n={});for(var r=-1,a=e.length;++r<a;){var c=e[r],d=i?i(n[c],t[c],c,n,t):void 0;d===void 0&&(d=t[c]),s?Gp(n,c,d):hy(n,c,d)}return n}function yw(t,e){for(var n=-1,i=Array(t);++n<t;)i[n]=e(n);return i}function ui(t){return t!=null&&typeof t=="object"}var Ew="[object Arguments]";function gf(t){return ui(t)&&br(t)==Ew}var py=Object.prototype,Sw=py.hasOwnProperty,Tw=py.propertyIsEnumerable,bw=gf(function(){return arguments}())?gf:function(t){return ui(t)&&Sw.call(t,"callee")&&!Tw.call(t,"callee")};const il=bw;var kw=Array.isArray;const bs=kw;function ww(){return!1}var my=typeof exports=="object"&&exports&&!exports.nodeType&&exports,vf=my&&typeof module=="object"&&module&&!module.nodeType&&module,_w=vf&&vf.exports===my,yf=_w?$n.Buffer:void 0,Iw=yf?yf.isBuffer:void 0,Cw=Iw||ww;const ba=Cw;var Rw=9007199254740991,Pw=/^(?:0|[1-9]\d*)$/;function fy(t,e){var n=typeof t;return e=e==null?Rw:e,!!e&&(n=="number"||n!="symbol"&&Pw.test(t))&&t>-1&&t%1==0&&t<e}var Aw=9007199254740991;function gy(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=Aw}var Mw="[object Arguments]",Ow="[object Array]",Dw="[object Boolean]",Nw="[object Date]",Lw="[object Error]",xw="[object Function]",Vw="[object Map]",Uw="[object Number]",Bw="[object Object]",Fw="[object RegExp]",jw="[object Set]",Ww="[object String]",Hw="[object WeakMap]",qw="[object ArrayBuffer]",Gw="[object DataView]",$w="[object Float32Array]",Jw="[object Float64Array]",Kw="[object Int8Array]",zw="[object Int16Array]",Yw="[object Int32Array]",Qw="[object Uint8Array]",Xw="[object Uint8ClampedArray]",Zw="[object Uint16Array]",e_="[object Uint32Array]",Ue={};Ue[$w]=Ue[Jw]=Ue[Kw]=Ue[zw]=Ue[Yw]=Ue[Qw]=Ue[Xw]=Ue[Zw]=Ue[e_]=!0;Ue[Mw]=Ue[Ow]=Ue[qw]=Ue[Dw]=Ue[Gw]=Ue[Nw]=Ue[Lw]=Ue[xw]=Ue[Vw]=Ue[Uw]=Ue[Bw]=Ue[Fw]=Ue[jw]=Ue[Ww]=Ue[Hw]=!1;function t_(t){return ui(t)&&gy(t.length)&&!!Ue[br(t)]}function $p(t){return function(e){return t(e)}}var vy=typeof exports=="object"&&exports&&!exports.nodeType&&exports,$o=vy&&typeof module=="object"&&module&&!module.nodeType&&module,n_=$o&&$o.exports===vy,Tu=n_&&ly.process,i_=function(){try{var t=$o&&$o.require&&$o.require("util").types;return t||Tu&&Tu.binding&&Tu.binding("util")}catch(e){}}();const ka=i_;var Ef=ka&&ka.isTypedArray,s_=Ef?$p(Ef):t_;const Wl=s_;var r_=Object.prototype,a_=r_.hasOwnProperty;function yy(t,e){var n=bs(t),i=!n&&il(t),s=!n&&!i&&ba(t),r=!n&&!i&&!s&&Wl(t),a=n||i||s||r,c=a?yw(t.length,String):[],d=c.length;for(var h in t)(e||a_.call(t,h))&&!(a&&(h=="length"||s&&(h=="offset"||h=="parent")||r&&(h=="buffer"||h=="byteLength"||h=="byteOffset")||fy(h,d)))&&c.push(h);return c}var o_=Object.prototype;function Hl(t){var e=t&&t.constructor,n=typeof e=="function"&&e.prototype||o_;return t===n}function Ey(t,e){return function(n){return t(e(n))}}var c_=Ey(Object.keys,Object);const d_=c_;var l_=Object.prototype,u_=l_.hasOwnProperty;function Sy(t){if(!Hl(t))return d_(t);var e=[];for(var n in Object(t))u_.call(t,n)&&n!="constructor"&&e.push(n);return e}function yc(t){return t!=null&&gy(t.length)&&!qp(t)}function Jp(t){return yc(t)?yy(t):Sy(t)}function h_(t,e){return t&&vc(e,Jp(e),t)}function p_(t){var e=[];if(t!=null)for(var n in Object(t))e.push(n);return e}var m_=Object.prototype,f_=m_.hasOwnProperty;function g_(t){if(!Gn(t))return p_(t);var e=Hl(t),n=[];for(var i in t)i=="constructor"&&(e||!f_.call(t,i))||n.push(i);return n}function Ec(t){return yc(t)?yy(t,!0):g_(t)}function v_(t,e){return t&&vc(e,Ec(e),t)}var Ty=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Sf=Ty&&typeof module=="object"&&module&&!module.nodeType&&module,y_=Sf&&Sf.exports===Ty,Tf=y_?$n.Buffer:void 0,bf=Tf?Tf.allocUnsafe:void 0;function by(t,e){if(e)return t.slice();var n=t.length,i=bf?bf(n):new t.constructor(n);return t.copy(i),i}function ky(t,e){var n=-1,i=t.length;for(e||(e=Array(i));++n<i;)e[n]=t[n];return e}function E_(t,e){for(var n=-1,i=t==null?0:t.length,s=0,r=[];++n<i;){var a=t[n];e(a,n,t)&&(r[s++]=a)}return r}function wy(){return[]}var S_=Object.prototype,T_=S_.propertyIsEnumerable,kf=Object.getOwnPropertySymbols,b_=kf?function(t){return t==null?[]:(t=Object(t),E_(kf(t),function(e){return T_.call(t,e)}))}:wy;const Kp=b_;function k_(t,e){return vc(t,Kp(t),e)}function _y(t,e){for(var n=-1,i=e.length,s=t.length;++n<i;)t[s+n]=e[n];return t}var w_=Ey(Object.getPrototypeOf,Object);const zp=w_;var __=Object.getOwnPropertySymbols,I_=__?function(t){for(var e=[];t;)_y(e,Kp(t)),t=zp(t);return e}:wy;const Iy=I_;function C_(t,e){return vc(t,Iy(t),e)}function Cy(t,e,n){var i=e(t);return bs(t)?i:_y(i,n(t))}function mh(t){return Cy(t,Jp,Kp)}function R_(t){return Cy(t,Ec,Iy)}var P_=wr($n,"DataView");const fh=P_;var A_=wr($n,"Promise");const gh=A_;var M_=wr($n,"Set");const vh=M_;var O_=wr($n,"WeakMap");const yh=O_;var wf="[object Map]",D_="[object Object]",_f="[object Promise]",If="[object Set]",Cf="[object WeakMap]",Rf="[object DataView]",N_=kr(fh),L_=kr(lc),x_=kr(gh),V_=kr(vh),U_=kr(yh),Fs=br;(fh&&Fs(new fh(new ArrayBuffer(1)))!=Rf||lc&&Fs(new lc)!=wf||gh&&Fs(gh.resolve())!=_f||vh&&Fs(new vh)!=If||yh&&Fs(new yh)!=Cf)&&(Fs=function(t){var e=br(t),n=e==D_?t.constructor:void 0,i=n?kr(n):"";if(i)switch(i){case N_:return Rf;case L_:return wf;case x_:return _f;case V_:return If;case U_:return Cf}return e});const wa=Fs;var B_=Object.prototype,F_=B_.hasOwnProperty;function j_(t){var e=t.length,n=new t.constructor(e);return e&&typeof t[0]=="string"&&F_.call(t,"index")&&(n.index=t.index,n.input=t.input),n}var W_=$n.Uint8Array;const sl=W_;function Yp(t){var e=new t.constructor(t.byteLength);return new sl(e).set(new sl(t)),e}function H_(t,e){var n=e?Yp(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.byteLength)}var q_=/\w*$/;function G_(t){var e=new t.constructor(t.source,q_.exec(t));return e.lastIndex=t.lastIndex,e}var Pf=Ts?Ts.prototype:void 0,Af=Pf?Pf.valueOf:void 0;function $_(t){return Af?Object(Af.call(t)):{}}function Ry(t,e){var n=e?Yp(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.length)}var J_="[object Boolean]",K_="[object Date]",z_="[object Map]",Y_="[object Number]",Q_="[object RegExp]",X_="[object Set]",Z_="[object String]",eI="[object Symbol]",tI="[object ArrayBuffer]",nI="[object DataView]",iI="[object Float32Array]",sI="[object Float64Array]",rI="[object Int8Array]",aI="[object Int16Array]",oI="[object Int32Array]",cI="[object Uint8Array]",dI="[object Uint8ClampedArray]",lI="[object Uint16Array]",uI="[object Uint32Array]";function hI(t,e,n){var i=t.constructor;switch(e){case tI:return Yp(t);case J_:case K_:return new i(+t);case nI:return H_(t,n);case iI:case sI:case rI:case aI:case oI:case cI:case dI:case lI:case uI:return Ry(t,n);case z_:return new i;case Y_:case Z_:return new i(t);case Q_:return G_(t);case X_:return new i;case eI:return $_(t)}}var Mf=Object.create,pI=function(){function t(){}return function(e){if(!Gn(e))return{};if(Mf)return Mf(e);t.prototype=e;var n=new t;return t.prototype=void 0,n}}();const mI=pI;function Py(t){return typeof t.constructor=="function"&&!Hl(t)?mI(zp(t)):{}}var fI="[object Map]";function gI(t){return ui(t)&&wa(t)==fI}var Of=ka&&ka.isMap,vI=Of?$p(Of):gI;const yI=vI;var EI="[object Set]";function SI(t){return ui(t)&&wa(t)==EI}var Df=ka&&ka.isSet,TI=Df?$p(Df):SI;const bI=TI;var kI=1,wI=2,_I=4,Ay="[object Arguments]",II="[object Array]",CI="[object Boolean]",RI="[object Date]",PI="[object Error]",My="[object Function]",AI="[object GeneratorFunction]",MI="[object Map]",OI="[object Number]",Oy="[object Object]",DI="[object RegExp]",NI="[object Set]",LI="[object String]",xI="[object Symbol]",VI="[object WeakMap]",UI="[object ArrayBuffer]",BI="[object DataView]",FI="[object Float32Array]",jI="[object Float64Array]",WI="[object Int8Array]",HI="[object Int16Array]",qI="[object Int32Array]",GI="[object Uint8Array]",$I="[object Uint8ClampedArray]",JI="[object Uint16Array]",KI="[object Uint32Array]",Ne={};Ne[Ay]=Ne[II]=Ne[UI]=Ne[BI]=Ne[CI]=Ne[RI]=Ne[FI]=Ne[jI]=Ne[WI]=Ne[HI]=Ne[qI]=Ne[MI]=Ne[OI]=Ne[Oy]=Ne[DI]=Ne[NI]=Ne[LI]=Ne[xI]=Ne[GI]=Ne[$I]=Ne[JI]=Ne[KI]=!0;Ne[PI]=Ne[My]=Ne[VI]=!1;function hd(t,e,n,i,s,r){var a,c=e&kI,d=e&wI,h=e&_I;if(n&&(a=s?n(t,i,s,r):n(t)),a!==void 0)return a;if(!Gn(t))return t;var u=bs(t);if(u){if(a=j_(t),!c)return ky(t,a)}else{var g=wa(t),E=g==My||g==AI;if(ba(t))return by(t,c);if(g==Oy||g==Ay||E&&!s){if(a=d||E?{}:Py(t),!c)return d?C_(t,v_(a,t)):k_(t,h_(a,t))}else{if(!Ne[g])return s?t:{};a=hI(t,g,c)}}r||(r=new li);var b=r.get(t);if(b)return b;r.set(t,a),bI(t)?t.forEach(function(D){a.add(hd(D,e,n,D,t,r))}):yI(t)&&t.forEach(function(D,F){a.set(F,hd(D,e,n,F,t,r))});var w=h?d?R_:mh:d?Ec:Jp,M=u?void 0:w(t);return mw(M||t,function(D,F){M&&(F=D,D=t[F]),hy(a,F,hd(D,e,n,F,t,r))}),a}var zI=1,YI=4;function Qp(t){return hd(t,zI|YI)}var QI="[object Symbol]";function XI(t){return typeof t=="symbol"||ui(t)&&br(t)==QI}var ZI=Object.defineProperty,eC=(t,e)=>{for(var n in e)ZI(t,n,{get:e[n],enumerable:!0})},tC={};eC(tC,{permissions:()=>nC,theme:()=>iC});var zt=(t=>(t.GroupCall="GROUP_CALL",t.Webinar="WEBINAR",t.AudioRoom="AUDIO_ROOM",t.Livestream="LIVESTREAM",t.Chat="CHAT",t))(zt||{}),se=(t=>(t.Allowed="ALLOWED",t.NotAllowed="NOT_ALLOWED",t.CanRequest="CAN_REQUEST",t))(se||{}),nC={view_type:"GROUP_CALL",accept_waiting_requests:!1,accept_present_requests:!1,request_produce:!1,can_allow_participant_audio:!1,can_allow_participant_screensharing:!1,can_allow_participant_video:!1,can_spotlight:!1,request_kick_participant:!1,kick_participant:!1,pin_participant:!1,can_edit_display_name:!1,can_record:!1,can_livestream:!1,can_present:!0,waiting_room_type:"SKIP_ON_ACCEPT",recorder_type:"NONE",plugins:{can_close:!0,can_start:!0},polls:{can_create:!0,can_vote:!0,can_view:!0},produce:{video:{allow:!0,quality:"vga",frame_rate:24},audio:!0,screenshare:{allow:!0,quality:"hd",frame_rate:5}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1}},connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},reactions:!1,hidden_participant:!1,is_recorder:!1,show_participant_list:!0,can_change_participant_role:!1,can_change_theme:!1,max_screenshare_count:1},iC={setup_screen:{is_enabled:!0},alone_here:{is_enabled:!0},waiting_room:{is_enabled:!1,enable_preview:!0},control_bar:{is_enabled:!0,elements:{plugins:!0,screenshare:!0,invite:!0,participants:!0,chat:!0,reactions:!1,polls:!0,fullscreen:!0,layout:!0}},header:{is_enabled:!0,elements:{timer:!0,title:!0,participant_count:!0,change_layout:!0}},pip_mode:!0,auto_tune:!0,grid:{multi:{maxVideoCount:6,videoFit:"cover"},single:{maxVideoCount:6,videoFit:"cover"},defaultView:"multi"},controls:{pip_toggle:!1}},Dy="hXgU8Wc8pwuGNq9ms5q9Hh",Nf;typeof dr!="undefined"&&(Nf=dr==null?void 0:dr.env)!=null&&Nf.FLAGSMITH_ENVIRONMENT_KEY&&(Dy=dr.env.FLAGSMITH_ENVIRONMENT_KEY);function sC(t=[]){const e={};return t.forEach(n=>{e[n.feature.name]={enabled:n.enabled,value:n.feature_state_value}}),e}var rC=class{constructor(t=Dy){y(this,"flags",{}),y(this,"environmentKey",null),this.environmentKey=t}identifyAndFetchFlagsWithRetry(t){return p(this,arguments,function*({primaryEndpoint:e,secondaryEndpoint:n,forceEvaluate:i,timeout:s,uniqueIdentifier:r,traitsObj:a,logger:c}){const d=JSON.parse(JSON.stringify(a)),h=Object.entries(d).map(g=>({trait_key:g[0],trait_value:g[1]})),u=[e,n,n];for(const g of u)try{const E="_"+(Math.random()+1).toString(36).substring(2),b=yield ak.post(`https://${g}/api/v1/identities/`,{identifier:r+(i?E:""),traits:h},{headers:{"Content-Type":"application/json","X-Environment-Key":this.environmentKey},timeout:s});return sC(b.data.flags||[])}catch(E){c.error("Flagsmith identify failed!!",{error:E,url:g})}return{}})}identify(t){return p(this,arguments,function*(e,n={},i=!1,s=5e3,r="edge.api.flagsmith.com",a=console){return this.flags=yield this.identifyAndFetchFlagsWithRetry({traitsObj:n,uniqueIdentifier:e,forceEvaluate:i,timeout:s,primaryEndpoint:r,secondaryEndpoint:"edge.api.flagsmith.com",logger:a}),this.flags})}getValue(t){return this.flags&&this.flags[t]&&this.flags[t].value}hasFeature(t){return this.flags&&this.flags[t]&&this.flags[t].enabled}getAllFlags(){return this.flags}},re=new rC,Ny=[-2,-1,0,1,2],aC=[0,1,2,3,4];function oC(t){t=t.trim();let e="0",n="0",i="0";return t.length==4?(e="0x"+t[1]+t[1],n="0x"+t[2]+t[2],i="0x"+t[3]+t[3]):t.length>6&&(e="0x"+t[1]+t[2],n="0x"+t[3]+t[4],i="0x"+t[5]+t[6]),[+e,+n,+i]}var cC=(t,e,n)=>{let i,s,r;if(e==0)i=s=r=n;else{const a=(h,u,g)=>(g<0&&(g+=1),g>1&&(g-=1),g<.16666666666666666?h+(u-h)*6*g:g<.5?u:g<.6666666666666666?h+(u-h)*(.6666666666666666-g)*6:h),c=n<.5?n*(1+e):n+e-n*e,d=2*n-c;i=a(d,c,t+1/3),s=a(d,c,t),r=a(d,c,t-1/3)}return[Math.round(i*255),Math.round(s*255),Math.round(r*255)]},dC=(t,e,n)=>{t/=255,e/=255,n/=255;const i=Math.max(t,e,n),s=Math.min(t,e,n);let r,a;const c=(i+s)/2;if(i==s)r=a=0;else{const d=i-s;switch(a=c>.5?d/(2-i-s):d/(i+s),i){case t:r=(e-n)/d+(e<n?6:0);break;case e:r=(n-t)/d+2;break;case n:r=(t-e)/d+4;break}r/=6}return[r,a,c]},lC=(t,e,n)=>{const i=s=>s.toString(16).padStart(2,"0");return`#${i(t)}${i(e)}${i(n)}`},Ly=(t,e=Ny,n=.4)=>{const i=[],[s,r,a]=oC(t),[c,d,h]=dC(s,r,a),u=Math.round(h*100);u>70?n=.8:u>60?n=.9:u<10?n=.075:u<42&&(n=.3);const g=e.findIndex(D=>D===0);if(g===-1)throw new Error("Invalid reducer provided, it must contain atleast one zero");const E=5-g,b=g+1,w=(100-u)/E,M=u/b;for(const D of e){let F;D<0?F=u+D*M*n:D>0?F=u+D*w*n:F=u;const[Y,X,A]=cC(c,d,F/100);i.push(lC(Y,X,A))}return i},Lf={dark:{background:{1e3:"#252525",900:"#2F2F2F",800:"#323232",700:"#3E3E3E",600:"#4A4A4A"},text:"#F5F5F5","video-bg":"#1C1C1C"},light:{background:{1e3:"#FFFFFF",900:"#F5F5F5",800:"#EBEBEB",700:"#E0E0E0",600:"#D6D6D6"},text:"#111111","text-on-brand":"#ffffff","video-bg":"#DADADA"}},uC=t=>{const[e,n,i,s,r]=Ly(t,Ny);return{300:e,400:n,500:i,600:s,700:r}},hC=t=>{if(t==="#FFFFFF")return Lf.light.background;if(t==="#000000")return Lf.dark.background;const[e,n,i,s,r]=Ly(t,aC);return{1e3:e,900:n,800:i,700:s,600:r}},pC={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:uC("#2160FD"),background:hC("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function xy(){return Qp(pC)}var mC={permissions:{can_accept_production_requests:!1,can_edit_display_name:!0,accept_waiting_requests:!1,disable_participant_audio:!1,disable_participant_screensharing:!1,disable_participant_video:!1,can_spotlight:!1,kick_participant:!1,pin_participant:!1,can_record:!1,can_livestream:!1,waiting_room_type:"SKIP",plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:"ALLOWED",can_consume:"ALLOWED"},audio:{can_produce:"ALLOWED"},screenshare:{can_produce:"ALLOWED",can_consume:"ALLOWED"}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1},channel:{can_create:"ALL",can_delete:"ALL",can_update:"ALL",can_read_all:!1},message:{can_delete:"ALL",can_edit:"ALL",delete_cutoff_time_seconds:0,edit_cutoff_time_seconds:0}},hidden_participant:!1,is_recorder:!1,recorder_type:"NONE",show_participant_list:!0,transcription_enabled:!1,can_change_participant_permissions:!1,connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},stage_enabled:!1,stage_access:void 0,accept_stage_requests:!1},ui:{oldTheme:{setup_screen:{is_enabled:!1},alone_here:{is_enabled:!1},waiting_room:{is_enabled:!1,enable_preview:!0},control_bar:{is_enabled:!0,elements:{plugins:!0,screenshare:!0,invite:!1,participants:!0,chat:!0,reactions:!1,polls:!0,fullscreen:!0,layout:!0}},header:{is_enabled:!0,elements:{timer:!0,title:!0,participant_count:!0,change_layout:!0}},pip_mode:!0,auto_tune:!0,colors:{primary:"#2160FD",secondary:"#1A1A1A",text:"#EEEEEE",background:"#1A1A1A",textPrimary:"#EEEEEE",videoBackground:"#1A1A1A"},dimensions:{mode:"fillParent"},grid:{multi:{maxVideoCount:6,videoFit:"cover"},single:{maxVideoCount:6,videoFit:"cover"},defaultView:"MULTI"},controls:{pip_toggle:!1},plugins:[]},design_tokens:xy(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:24},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"hybrid"};function fC(){return Qp(mC)}var gC={permissions:{can_accept_production_requests:!1,can_edit_display_name:!0,accept_waiting_requests:!1,disable_participant_audio:!1,disable_participant_screensharing:!1,disable_participant_video:!1,can_spotlight:!1,kick_participant:!1,pin_participant:!1,can_record:!1,can_livestream:!1,waiting_room_type:"SKIP",plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:"ALLOWED"},audio:{can_produce:"ALLOWED"},screenshare:{can_produce:"ALLOWED"}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1}},hidden_participant:!1,is_recorder:!1,recorder_type:"NONE",show_participant_list:!0,transcription_enabled:!1,can_change_participant_permissions:!1,connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},stage_enabled:!1,stage_access:void 0,accept_stage_requests:!1},ui:{design_tokens:xy(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:24},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"2.0.0"};function Xp(){return Qp(gC)}var vC=/\s/;function yC(t){for(var e=t.length;e--&&vC.test(t.charAt(e)););return e}var EC=/^\s+/;function SC(t){return t&&t.slice(0,yC(t)+1).replace(EC,"")}var xf=0/0,TC=/^[-+]0x[0-9a-f]+$/i,bC=/^0b[01]+$/i,kC=/^0o[0-7]+$/i,wC=parseInt;function Vf(t){if(typeof t=="number")return t;if(XI(t))return xf;if(Gn(t)){var e=typeof t.valueOf=="function"?t.valueOf():t;t=Gn(e)?e+"":e}if(typeof t!="string")return t===0?t:+t;t=SC(t);var n=bC.test(t);return n||kC.test(t)?wC(t.slice(2),n?2:8):TC.test(t)?xf:+t}function Vy(t){return t}function _C(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)}var IC=800,CC=16,RC=Date.now;function PC(t){var e=0,n=0;return function(){var i=RC(),s=CC-(i-n);if(n=i,s>0){if(++e>=IC)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function AC(t){return function(){return t}}var MC=nl?function(t,e){return nl(t,"toString",{configurable:!0,enumerable:!1,value:AC(e),writable:!0})}:Vy;const OC=MC;var DC=PC(OC);const NC=DC;var Uf=Math.max;function LC(t,e,n){return e=Uf(e===void 0?t.length-1:e,0),function(){for(var i=arguments,s=-1,r=Uf(i.length-e,0),a=Array(r);++s<r;)a[s]=i[e+s];s=-1;for(var c=Array(e+1);++s<e;)c[s]=i[s];return c[e]=n(a),_C(t,this,c)}}function xC(t,e){return NC(LC(t,e,Vy),t+"")}function VC(t,e,n){if(!Gn(n))return!1;var i=typeof e;return(i=="number"?yc(n)&&fy(e,n.length):i=="string"&&e in n)?gc(n[e],t):!1}function UC(t){return xC(function(e,n){var i=-1,s=n.length,r=s>1?n[s-1]:void 0,a=s>2?n[2]:void 0;for(r=t.length>3&&typeof r=="function"?(s--,r):void 0,a&&VC(n[0],n[1],a)&&(r=s<3?void 0:r,s=1),e=Object(e);++i<s;){var c=n[i];c&&t(e,c,i,r)}return e})}var BC="[object Object]",FC=Function.prototype,jC=Object.prototype,Uy=FC.toString,WC=jC.hasOwnProperty,HC=Uy.call(Object);function qC(t){if(!ui(t)||br(t)!=BC)return!1;var e=zp(t);if(e===null)return!0;var n=WC.call(e,"constructor")&&e.constructor;return typeof n=="function"&&n instanceof n&&Uy.call(n)==HC}var GC="__lodash_hash_undefined__";function $C(t){return this.__data__.set(t,GC),this}function JC(t){return this.__data__.has(t)}function rl(t){var e=-1,n=t==null?0:t.length;for(this.__data__=new _r;++e<n;)this.add(t[e])}rl.prototype.add=rl.prototype.push=$C;rl.prototype.has=JC;function KC(t,e){for(var n=-1,i=t==null?0:t.length;++n<i;)if(e(t[n],n,t))return!0;return!1}function zC(t,e){return t.has(e)}var YC=1,QC=2;function By(t,e,n,i,s,r){var a=n&YC,c=t.length,d=e.length;if(c!=d&&!(a&&d>c))return!1;var h=r.get(t),u=r.get(e);if(h&&u)return h==e&&u==t;var g=-1,E=!0,b=n&QC?new rl:void 0;for(r.set(t,e),r.set(e,t);++g<c;){var w=t[g],M=e[g];if(i)var D=a?i(M,w,g,e,t,r):i(w,M,g,t,e,r);if(D!==void 0){if(D)continue;E=!1;break}if(b){if(!KC(e,function(F,Y){if(!zC(b,Y)&&(w===F||s(w,F,n,i,r)))return b.push(Y)})){E=!1;break}}else if(!(w===M||s(w,M,n,i,r))){E=!1;break}}return r.delete(t),r.delete(e),E}function XC(t){var e=-1,n=Array(t.size);return t.forEach(function(i,s){n[++e]=[s,i]}),n}function ZC(t){var e=-1,n=Array(t.size);return t.forEach(function(i){n[++e]=i}),n}var eR=1,tR=2,nR="[object Boolean]",iR="[object Date]",sR="[object Error]",rR="[object Map]",aR="[object Number]",oR="[object RegExp]",cR="[object Set]",dR="[object String]",lR="[object Symbol]",uR="[object ArrayBuffer]",hR="[object DataView]",Bf=Ts?Ts.prototype:void 0,bu=Bf?Bf.valueOf:void 0;function pR(t,e,n,i,s,r,a){switch(n){case hR:if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case uR:return!(t.byteLength!=e.byteLength||!r(new sl(t),new sl(e)));case nR:case iR:case aR:return gc(+t,+e);case sR:return t.name==e.name&&t.message==e.message;case oR:case dR:return t==e+"";case rR:var c=XC;case cR:var d=i&eR;if(c||(c=ZC),t.size!=e.size&&!d)return!1;var h=a.get(t);if(h)return h==e;i|=tR,a.set(t,e);var u=By(c(t),c(e),i,s,r,a);return a.delete(t),u;case lR:if(bu)return bu.call(t)==bu.call(e)}return!1}var mR=1,fR=Object.prototype,gR=fR.hasOwnProperty;function vR(t,e,n,i,s,r){var a=n&mR,c=mh(t),d=c.length,h=mh(e),u=h.length;if(d!=u&&!a)return!1;for(var g=d;g--;){var E=c[g];if(!(a?E in e:gR.call(e,E)))return!1}var b=r.get(t),w=r.get(e);if(b&&w)return b==e&&w==t;var M=!0;r.set(t,e),r.set(e,t);for(var D=a;++g<d;){E=c[g];var F=t[E],Y=e[E];if(i)var X=a?i(Y,F,E,e,t,r):i(F,Y,E,t,e,r);if(!(X===void 0?F===Y||s(F,Y,n,i,r):X)){M=!1;break}D||(D=E=="constructor")}if(M&&!D){var A=t.constructor,$=e.constructor;A!=$&&"constructor"in t&&"constructor"in e&&!(typeof A=="function"&&A instanceof A&&typeof $=="function"&&$ instanceof $)&&(M=!1)}return r.delete(t),r.delete(e),M}var yR=1,Ff="[object Arguments]",jf="[object Array]",Dc="[object Object]",ER=Object.prototype,Wf=ER.hasOwnProperty;function SR(t,e,n,i,s,r){var a=bs(t),c=bs(e),d=a?jf:wa(t),h=c?jf:wa(e);d=d==Ff?Dc:d,h=h==Ff?Dc:h;var u=d==Dc,g=h==Dc,E=d==h;if(E&&ba(t)){if(!ba(e))return!1;a=!0,u=!1}if(E&&!u)return r||(r=new li),a||Wl(t)?By(t,e,n,i,s,r):pR(t,e,d,n,i,s,r);if(!(n&yR)){var b=u&&Wf.call(t,"__wrapped__"),w=g&&Wf.call(e,"__wrapped__");if(b||w){var M=b?t.value():t,D=w?e.value():e;return r||(r=new li),s(M,D,n,i,r)}}return E?(r||(r=new li),vR(t,e,n,i,s,r)):!1}function Fy(t,e,n,i,s){return t===e?!0:t==null||e==null||!ui(t)&&!ui(e)?t!==t&&e!==e:SR(t,e,n,i,Fy,s)}function TR(t){return function(e,n,i){for(var s=-1,r=Object(e),a=i(e),c=a.length;c--;){var d=a[t?c:++s];if(n(r[d],d,r)===!1)break}return e}}var bR=TR();const kR=bR;var wR=function(){return $n.Date.now()};const ku=wR;var _R="Expected a function",IR=Math.max,CR=Math.min;function al(t,e,n){var i,s,r,a,c,d,h=0,u=!1,g=!1,E=!0;if(typeof t!="function")throw new TypeError(_R);e=Vf(e)||0,Gn(n)&&(u=!!n.leading,g="maxWait"in n,r=g?IR(Vf(n.maxWait)||0,e):r,E="trailing"in n?!!n.trailing:E);function b(me){var Ie=i,fe=s;return i=s=void 0,h=me,a=t.apply(fe,Ie),a}function w(me){return h=me,c=setTimeout(F,e),u?b(me):a}function M(me){var Ie=me-d,fe=me-h,Je=e-Ie;return g?CR(Je,r-fe):Je}function D(me){var Ie=me-d,fe=me-h;return d===void 0||Ie>=e||Ie<0||g&&fe>=r}function F(){var me=ku();if(D(me))return Y(me);c=setTimeout(F,M(me))}function Y(me){return c=void 0,E&&i?b(me):(i=s=void 0,a)}function X(){c!==void 0&&clearTimeout(c),h=0,i=d=s=c=void 0}function A(){return c===void 0?a:Y(ku())}function $(){var me=ku(),Ie=D(me);if(i=arguments,s=this,d=me,Ie){if(c===void 0)return w(d);if(g)return clearTimeout(c),c=setTimeout(F,e),b(d)}return c===void 0&&(c=setTimeout(F,e)),a}return $.cancel=X,$.flush=A,$}function Eh(t,e,n){(n!==void 0&&!gc(t[e],n)||n===void 0&&!(e in t))&&Gp(t,e,n)}function RR(t){return ui(t)&&yc(t)}function Sh(t,e){if(!(e==="constructor"&&typeof t[e]=="function")&&e!="__proto__")return t[e]}function PR(t){return vc(t,Ec(t))}function AR(t,e,n,i,s,r,a){var c=Sh(t,n),d=Sh(e,n),h=a.get(d);if(h){Eh(t,n,h);return}var u=r?r(c,d,n+"",t,e,a):void 0,g=u===void 0;if(g){var E=bs(d),b=!E&&ba(d),w=!E&&!b&&Wl(d);u=d,E||b||w?bs(c)?u=c:RR(c)?u=ky(c):b?(g=!1,u=by(d,!0)):w?(g=!1,u=Ry(d,!0)):u=[]:qC(d)||il(d)?(u=c,il(c)?u=PR(c):(!Gn(c)||qp(c))&&(u=Py(d))):g=!1}g&&(a.set(d,u),s(u,d,i,r,a),a.delete(d)),Eh(t,n,u)}function jy(t,e,n,i,s){t!==e&&kR(e,function(r,a){if(s||(s=new li),Gn(r))AR(t,e,a,n,jy,i,s);else{var c=i?i(Sh(t,a),r,a+"",t,e,s):void 0;c===void 0&&(c=r),Eh(t,a,c)}},Ec)}var MR="[object Map]",OR="[object Set]",DR=Object.prototype,NR=DR.hasOwnProperty;function LR(t){if(t==null)return!0;if(yc(t)&&(bs(t)||typeof t=="string"||typeof t.splice=="function"||ba(t)||Wl(t)||il(t)))return!t.length;var e=wa(t);if(e==MR||e==OR)return!t.size;if(Hl(t))return!Sy(t).length;for(var n in t)if(NR.call(t,n))return!1;return!0}function xR(t,e){return Fy(t,e)}var VR=UC(function(t,e,n){jy(t,e,n)});const Qi=VR;var Th=(t=>(t.PARTICIPANT="PARTICIPANT",t.PEER="PEER",t.CLIENT="CLIENT",t))(Th||{});const ue={PROPAGATE_KICK_ALL:"propagate_kick_across_rooms",REFRESH_ID_ON_DISCONNECTION:"refresh_id_on_disconnection",SIMULCAST:"simulcast",CHAT_SOCKET_SERVER:"chat_socket_server",POLL_SOCKET_SERVER:"poll_socket_server",PLUGIN_SOCKET_SERVER:"plugin_socket_server",NR_OTEL_WEB:"nr_otel_web",ICE_RESTART_ON_FAILED_STATE:"ice_restart_on_failed_state",ICE_RESTART_ON_DISCONNECTED_STATE:"ice_restart_on_disconnected_state",ENABLE_ICE_STATE_LOGGING:"enable_ice_state_logging",SUPPRESS_PEER_MUTE_UNMUTE_EMITS:"web_core_suppress_peer_mute_unmute_emits",SKIP_OTEL_TRACES:"skip_otel_traces",USE_USERIDS_IN_CHAT:"use_userids_in_chat",CUSTOM_PING_PONG:"custom_ping_pong",ENABLE_HIVE_SIMULCAST:"enable_hive_simulcast",ENABLE_HIVE_TRANSPORT_RECONNECTION_ON_ICE_FAILED:"enable_hive_transport_reconnection_on_ice_failed",ENABLE_HIVE_EXPERIMENTAL_FAIL_RECOVERY:"enable_hive_fail_recovery",ENABLE_HIVE_INFINITE_RETRIES:"enable_hive_infinite_retries",HIVE_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED:"hive_transport_force_relay_on_ice_failed",ENABLE_HIVE_CONSUME_OVER_DC:"enable_hive_consume_over_dc",ENABLE_CF_SIMULCAST:"enable_cf_simulcast",ENABLE_CF_TRANSPORT_RECONNECTION_ON_ICE_FAILED:"enable_cf_transport_reconnection_on_ice_failed",ENABLE_CF_EXPERIMENTAL_FAIL_RECOVERY:"enable_cf_fail_recovery",ENABLE_CF_INFINITE_RETRIES:"enable_cf_infinite_retries",CF_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED:"cf_transport_force_relay_on_ice_failed",BYPASS_LOG_EXCLUSION_LIST:"bypass_log_exclusion_list",LOG_LEVEL:"log_level",V1_PLUGINS:"v1_plugins",SCREENSHARE_DTX:"screenshare_dtx",SCREENSHARE_PRIORITY:"screenshare_priority",SCREENSHARE_MIN_BITRATE:"screenshare_minbitrate",SCREENSHARE_SIMULCAST:"screenshare_simulcast",DISABLE_WEBCAM_LAYERS_ON_SCREENSHARE:"disable_webcam_layers_on_screenshare",SCREENSHARE_FORCE_GOOG_CONFERENCE:"screenshare_force_goog_conference",LIVESTREAM:"feat_livestream",FETCH_RETRY:"fetch_retry",DISABLE_WEBCAM_SIMULCAST:"webcore_disable_webcam_simulcast",OVERRIDE_WEBCAM_SIMULCAST:"override_webcam_simulcast",SOCKET_POLLING:"socket_polling",FEAT_PAGINATED_CHAT:"feat_paginated_chat",VAL_MIN_FRAMERATE:"val_min_framerate",SCREEENSHARE_ERR_HACK:"screenshare_err_hack",SCREEENSHARE_CONSTRAINTS_RETRY:"screenshare_constraints_retry",TROUBLESHOOTING:"feat_troubleshooting",VIDEO_CONSTRAINTS:"video_constraints",SCREENSHARE_CONSTRAINTS:"screenshare_constraints",FEAT_CHAT_SDK:"feat_chat_sdk",FEAT_CHAT_SDK_SEARCH:"chat_search",OBS_QUALITY:"obs_quality",ALLOW_SAFARI_MEDIA_MIDDLEWARES:"allow_safari_media_middlewares",DYNAMIC_VIDEO_QUALITY:"dynamic_video_quality",EXP_RESHARE:"exp_reshare",LEAVE_STAGE_ON_END:"leave_stage_on_end",SKIP_SETTING_IN_USE_DEVICE:"skip_setting_in_use_device",PRECALL_BANDWIDTH_TEST:"precall_bandwidth_test",CONSUMER_BIND_NO_RETRY:"consumer_bind_no_retry",DEBUG_SOCKET_JOIN:"debug_socket_join",FORCE_RELAY:"force_relay",FORCE_VIDEO_CODEC:"force_video_codec",USE_EXPERIMENTAL_SFU_HANDLER:"use_experimental_sfu_handler",TRACK_HINT:"track_hint",OVERRIDE_HIVE_SIMULCAST_DYNAMIC:"override_hive_simulcast_dynamic",PRECREATE_PRODUCERS:"precreate_producers",DISABLE_OPUS_DTX_CF:"disable_opus_dtx_cf",ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS:"enable_audio_activity_debug_logs"};function pd(t){const e={};return typeof(t==null?void 0:t.code)=="number"&&(e.code=t.code),typeof(t==null?void 0:t.code)=="string"&&(e.code=t.code.substring(0,100)),typeof(t==null?void 0:t.name)=="string"&&(e.name=t.name.substring(0,500)),typeof(t==null?void 0:t.message)=="string"&&(e.message=t.message.substring(0,500)),typeof(t==null?void 0:t.reason)=="string"&&(e.reason=t.reason.substring(0,500)),typeof(t==null?void 0:t.stack)=="string"&&(e.stack=t.stack.substring(0,500)),e}function Wy(t){var e,n,i,s;const r=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((e=window.location.host)==null?void 0:e.includes("devel"))&&((n=window.location.host)==null?void 0:n.includes("dyte.io")),a=!!((s=(i=t==null?void 0:t.getValue("modules"))==null?void 0:i.devTools)!=null&&s.logs);return r||a}function UR(t){var e;if(re.hasFeature(ue.LOG_LEVEL)){let n=((e=re.getValue(ue.LOG_LEVEL))==null?void 0:e.toString())||"all";if(n=n.toLowerCase().trim(),n==="off")return!1;if(n!=="all"){const i=["debug","log","info","warn","error"],s=i.indexOf(t),r=i.indexOf(n);if(s<r)return!1}}return!0}function Hy(t,e,n={}){return Object.getOwnPropertyNames(t).forEach(i=>{var s;if([null,void 0,NaN].includes(t[i])||e&&(((s=e.match(/\./g))==null?void 0:s.length)||0)>=10)return;const r=e?`${e}.${i}`:i;typeof t[i]=="object"?Hy(t[i],r,n):["number","string","boolean"].includes(typeof t[i])&&(n[r]=t[i])}),n}function Hf(t,e,n={},i=""){const s={};try{const r=JSON.stringify(n),a=JSON.parse(r),c=Hy(a,i),d=JSON.stringify(c);if(d.length>5e3){const h=`Log named: "${e}" is trying to log an flattened object of size
19
+ ${d.length} chars that is beyond permitted limit of 5000 chars. Please optimize.`;throw Wy(t)&&console.error(h,{log:n,flattened:d}),new Error(h)}return JSON.parse(d)}catch(r){const a=pd(r);s[`${i}.error.message`]=a.message||"",s[`${i}.error.stack`]=a.stack||"",s[`${i}.error.reason`]=a.reason||"",s[`${i}.error.source`]="safelyFlattenObjForOpenTelemetry"}return s}const hc="chrome",qy="opera",Gy="firefox",$y="iexplorer",Jy="safari",Ky="nwjs",zy="electron",Yy="react-native",Zp="unknown",ol={Chrome:hc,Chromium:hc,Opera:qy,Firefox:Gy,"Internet Explorer":$y,Safari:Jy};function BR(){const{userAgent:t}=navigator,e={name:Zp,version:void 0};if(t.match(/Chrome/)&&!t.match(/Edge/))if(t.match(/Edg(A?)/)){const n=t.match(/Chrome\/([\d.]+)/)[1];Number.parseInt(n,10)>72&&(e.name=hc,e.version=n)}else e.name=hc,e.version=t.match(/Chrome\/([\d.]+)/)[1];return e}function FR(){const{userAgent:t}=navigator;if(t.match(/Electron/)){const e=t.match(/Electron\/([\d.]+)/)[1];return{name:zy,version:e}}return null}function jR(){const{userAgent:t}=navigator;if(t.match(/JitsiMeetNW/)){const e=t.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:Ky,version:e}}}function WR(){const t=navigator.userAgent.match(/\b(react[ \t_-]*native)(?:\/(\S+))?/i);let e;if(t||navigator.product==="ReactNative")return t&&t.length>2&&(t[1],e=t[2]),e||(e="unknown"),{name:Yy,version:e}}function HR(t){let e;const n=[WR,FR,jR];for(let s=0;s<n.length;s+=1)if(e=n[s](),e)return e;const i=t.getBrowserName();return i in ol?{name:ol[i],version:t.getBrowserVersion()}:(e=BR(),e||{name:Zp,version:void 0})}class qR{constructor(){y(this,"_bowser"),y(this,"_name"),y(this,"_version"),y(this,"getDeviceInfo",()=>({isMobile:this.isMobile(),browserName:this._bowser.getBrowserName(),osName:this._bowser.getOSName(),browserVersion:this._bowser.getBrowserVersion(),osVersionName:this._bowser.getOSVersion(),engineName:this._bowser.getEngineName()}))}init(e){let n,i;if(this._bowser=sv.getParser(navigator.userAgent),typeof e=="undefined"){const s=HR(this._bowser);n=s.name,i=s.version}else e.name in ol?(n=ol[e.name],i=e.version):(n=Zp,i=void 0);this._name=n,this._version=i}getName(){return this._name}isChrome(){return this._name===hc}isOpera(){return this._name===qy}isFirefox(){return this._name===Gy}isIExplorer(){return this._name===$y}isSafari(){return this._name===Jy}isNWJS(){return this._name===Ky}isElectron(){return this._name===zy}isReactNative(){return this._name===Yy||navigator.isReactNative===!0}getVersion(){return this._version}isMobile(){return this._bowser.getPlatformType()==="mobile"}_checkCondition(e){if(this._version)return this._bowser.satisfies(e)}isVersionGreaterThan(e){return this._checkCondition({[this._name]:`>${e}`})}isVersionLessThan(e){return this._checkCondition({[this._name]:`<${e}`})}isVersionEqualTo(e){return this._checkCondition({[this._name]:`~${e}`})}}class GR extends qR{doesVideoMuteByStreamRemove(){return this.isChromiumBased()||this.isWebKitBased()}supportsP2P(){return!this.usesUnifiedPlan()}isChromiumBased(){return this.isChrome()||this.isElectron()||this.isNWJS()||this.isOpera()}isWebKitBased(){return this._bowser.isEngine("webkit")&&typeof navigator.mediaDevices!="undefined"&&typeof navigator.mediaDevices.getUserMedia!="undefined"&&typeof window.RTCRtpTransceiver!="undefined"&&Object.keys(RTCRtpTransceiver.prototype).indexOf("currentDirection")>-1}isSupported(){return typeof RTCPeerConnection!="undefined"}isUserInteractionRequiredForUnmute(){return this.isFirefox()&&this.isVersionLessThan("68")}supportsVideoMuteOnConnInterrupted(){return this.isChromiumBased()||this.isReactNative()||this.isWebKitBased()}supportsBandwidthStatistics(){return!this.isFirefox()&&!this.isWebKitBased()}supportsCodecPreferences(){return this.usesUnifiedPlan()&&typeof window.RTCRtpTransceiver!="undefined"&&Object.keys(window.RTCRtpTransceiver.prototype).indexOf("setCodecPreferences")>-1&&Object.keys(RTCRtpSender.prototype).indexOf("getCapabilities")>-1&&!this.isWebKitBased()}supportsDeviceChangeEvent(){return navigator.mediaDevices&&typeof navigator.mediaDevices.ondevicechange!="undefined"&&typeof navigator.mediaDevices.addEventListener!="undefined"}supportsLocalCandidateRttStatistics(){return this.isChromiumBased()||this.isReactNative()||this.isWebKitBased()}supportsPerformanceObserver(){return typeof window.PerformanceObserver!="undefined"&&PerformanceObserver.supportedEntryTypes.indexOf("longtask")>-1}supportsReceiverStats(){return typeof window.RTCRtpReceiver!="undefined"&&Object.keys(RTCRtpReceiver.prototype).indexOf("getSynchronizationSources")>-1}supportsRTTStatistics(){return!this.isFirefox()}usesPlanB(){return!this.usesUnifiedPlan()}usesSdpMungingForSimulcast(){return this.isChromiumBased()||this.isReactNative()||this.isWebKitBased()}usesUnifiedPlan(){return!!(this.isFirefox()||this.isWebKitBased())}usesNewGumFlow(){return!!(this.isChromiumBased()||this.isFirefox()||this.isWebKitBased())}usesAdapter(){return this.usesNewGumFlow()}usesRidsForSimulcast(){return!1}supportsGetDisplayMedia(){return typeof navigator.getDisplayMedia!="undefined"||typeof navigator.mediaDevices!="undefined"&&typeof navigator.mediaDevices.getDisplayMedia!="undefined"}supportsInsertableStreams(){if(!(typeof window.RTCRtpSender!="undefined"&&(window.RTCRtpSender.prototype.createEncodedStreams||window.RTCRtpSender.prototype.createEncodedVideoStreams)))return!1;const e=new ReadableStream;try{return window.postMessage(e,"*",[e]),!0}catch(n){return!1}}supportsAudioRed(){return Boolean(window.RTCRtpSender&&window.RTCRtpSender.getCapabilities&&window.RTCRtpSender.getCapabilities("audio").codecs.some(e=>e.mimeType==="audio/red")&&window.RTCRtpReceiver&&window.RTCRtpReceiver.getCapabilities&&window.RTCRtpReceiver.getCapabilities("audio").codecs.some(e=>e.mimeType==="audio/red"))}supportsSdpSemantics(){return this.isChromiumBased()}_getChromiumBasedVersion(){if(this.isChromiumBased()){if(this.isNWJS())return Number.parseInt(dr.versions.chromium,10);const e=navigator.userAgent;if(e.match(/Chrome/))return Number.parseInt(e.match(/Chrome\/([\d.]+)/)[1],10)}return-1}isIOSMobile(){return this.isMobile&&this._bowser.getOSName()==="iOS"}}const Be=new GR,$R={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},La={baseURL:"http://localhost:5000",createdAt:"2021-08-05T10:49:56.602Z",description:"Develop plugins locally",id:"09259e3b-7be8-46f6-9801-106bf1866e1c",name:"Localhost Dev",organizationId:"4ad15a19-80e2-4105-bf43-48039fd2963e",picture:"https://dyte-uploads.s3.ap-south-1.amazonaws.com/dyte.png",private:!1,published:!0,staggered:!1,tags:["#localhost","#dev"],type:"self_hosted",updatedAt:"2021-08-05T10:50:07.681Z"},JR={pip:!0,poll:!0,chat:!0,stage:!0,theme:!0,plugin:!0,tracing:!0,internals:!0,recording:!0,livestream:!0,participant:!0,devTools:{logs:!1}};function cl(t,e){const n=t.getValue("overrides");return n&&n[e]?n[e]:!1}function KR({baseURI:t}){return t!=null&&t.includes("preprod.dyte")?Go.PREPROD:t!=null&&t.includes("devel.dyte")?Go.DEVEL:Go.PROD}function fa({servicePrefix:t,baseURI:e}){return`${t}.${e}`}function Qy(t){const e=t.getValue("baseURI");return{location:fa({servicePrefix:"location",baseURI:e}),locationLegacy:fa({servicePrefix:"location-legacy",baseURI:e}),daCollector:fa({servicePrefix:"da-collector",baseURI:e})}}const zR='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="m16.242 2.932 4.826 4.826a2.75 2.75 0 0 1-.715 4.404l-4.87 2.435a.75.75 0 0 0-.374.426l-1.44 4.166a1.25 1.25 0 0 1-2.065.476L8.5 16.561 4.06 21H3v-1.06l4.44-4.44-3.105-3.104a1.25 1.25 0 0 1 .476-2.066l4.166-1.44a.75.75 0 0 0 .426-.373l2.435-4.87a2.75 2.75 0 0 1 4.405-.715Zm3.766 5.886-4.826-4.826a1.25 1.25 0 0 0-2.002.325l-2.435 4.871a2.25 2.25 0 0 1-1.278 1.12l-3.789 1.31 6.705 6.704 1.308-3.789a2.25 2.25 0 0 1 1.12-1.277l4.872-2.436a1.25 1.25 0 0 0 .325-2.002Z" fill="currentColor"/></svg>',YR='<svg viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M4 12.02c0 1.06.2 2.1.6 3.08l.6 1.42c.22.55.64 1.01 1.17 1.29.27.14.56.21.86.21h2.55c.77 0 1.49-.41 1.87-1.08.5-.87 1.02-1.7 1.72-2.43l1.32-1.39c.44-.46.97-.84 1.49-1.23l.59-.45a.6.6 0 0 0 .23-.47c0-.75-.54-1.57-1.22-1.79a3.34 3.34 0 0 0-2.78.29V4.5a1.5 1.5 0 0 0-2.05-1.4 1.5 1.5 0 0 0-2.9 0A1.5 1.5 0 0 0 6 4.5v.09A1.5 1.5 0 0 0 4 6v6.02ZM8 4.5v4a.5.5 0 0 0 1 0v-5a.5.5 0 0 1 1 0v5a.5.5 0 0 0 1 0v-4a.5.5 0 0 1 1 0v6a.5.5 0 0 0 .85.37h.01c.22-.22.44-.44.72-.58.7-.35 2.22-.57 2.4.5l-.53.4c-.52.4-1.04.78-1.48 1.24l-1.33 1.38c-.75.79-1.31 1.7-1.85 2.63-.21.36-.6.58-1.01.58H7.23a.87.87 0 0 1-.4-.1 1.55 1.55 0 0 1-.71-.78l-.59-1.42a7.09 7.09 0 0 1-.53-2.7V6a.5.5 0 0 1 1 0v3.5a.5.5 0 0 0 1 0v-5a.5.5 0 0 1 1 0Z" fill="currentColor"></path></svg>',Nc=t=>{if(!t)return;if(!t.startsWith("<svg"))return new Promise(s=>{s(t)});const e=new Blob([t],{type:"image/svg+xml"}),n=new Image,i=window.URL.createObjectURL(e);return new Promise((s,r)=>{n.onload=()=>{s(n),window.URL.revokeObjectURL(i)},n.onerror=()=>{r(),window.URL.revokeObjectURL(i)},n.src=i})};function QR(t){const e=H({},t),n=new Map,i=(a,c)=>(n.has(a)||n.set(a,new Set),n.get(a).add(c),()=>{var d;return(d=n.get(a))==null?void 0:d.delete(c)}),s=(a,c)=>{var d;(d=n.get(a))==null||d.delete(c)},r=a=>{var c;(c=n.get(a))==null||c.forEach(d=>{try{d(e[a])}catch(h){m.error(`Error in notifying for "${a.toString()}"`,h)}})};return{subscribe:i,unsubscribe:s,notify:r,setValue:(a,c,d=!0)=>{e[a]=c,d&&r(a)},getValue:a=>e[a],getAllValues:()=>e}}class XR{constructor(){y(this,"contexts",new Map),y(this,"mostRecentPeerId",null)}createContext(e,n){return this.contexts.has(e)?this.contexts.get(e):(this.contexts.set(e,QR(n)),this.mostRecentPeerId=e,this.contexts.get(e))}remapContext(e,n){const i=n.getValue("peerId");i!==e&&(n.setValue("peerId",e),this.mostRecentPeerId=e,this.contexts.set(e,n),this.contexts.delete(i))}getContext(e){return this.contexts.get(e)}getMostRecentPeerId(){return this.mostRecentPeerId}}const pr=new XR,ve=class{static get logsEndpoint(){const t=pr.getContext(ve.meetingMetadata.peerId);return`https://${fa({servicePrefix:"api-silos",baseURI:t.getValue("baseURI")})}/otel/logs`}static resetPeerId(t){ve.meetingMetadata.peerId=t}static init(t,e){const n=t.getValue("peerId");ve.tracingEnabled=e,ve.meetingMetadata.peerId=n,ve.meetingMetadata.sdkVersion=t.getValue("sdkVersion"),ve.meetingMetadata.deviceInfo=Be.getDeviceInfo(),ve.meetingMetadata.visitedUrl=!navigator.isReactNative&&typeof window!="undefined"&&window.location.href,navigator.isReactNative||document.addEventListener("visibilitychange",ve.processCachedLogs),ve.logsProcessorTimer=setInterval(ve.processCachedLogs,ve.logsProcessingInterval),e&&(ve.initialized=!0)}static trace(t,e=void 0){return(n,i,s)=>{const r=s.value;return s.value=function(...a){if(!ve.initialized||navigator.isReactNative||!ve.tracingEnabled||re.hasFeature(ue.SKIP_OTEL_TRACES))return r.apply(this,a);ve.addLogInCurrentSpan("info",t,e);const c=performance.now(),d=r.apply(this,a);return Promise.resolve(d).then(()=>{const h=performance.now();h-c>10&&ve.addLogInCurrentSpan("info",`${t}_timing`,{execTime:h-c,country:ve.location.country})}).catch(()=>{const h=performance.now();ve.addLogInCurrentSpan("info",`${t}_timing`,{execTime:h-c})}),d},s}}static injectContext(t){var e;const n=Ia().replace(/-/g,"").substring(0,16),i=(e=ve.meetingMetadata.peerId)==null?void 0:e.replace(/-/g,"");t.TRACEPARENT=`00-${i}-${n}-01`}static addLogInCurrentSpan(t,e,n={},i=!1){n!=null&&n.error&&Object.assign(n,{error:pd(n.error)});const s=pr.getContext(ve.meetingMetadata.peerId);if(Wy(s)&&(LR(n)?console[t]("DyteInternalLogs:: ",t,e):console[t]("DyteInternalLogs:: ",t,e,n)),!!UR(t))try{const r=Hf(s,e,n,"metadata"),a=new Date,c=ee(H({message:e,level:t},r),{loggedAt:a.toISOString(),loggedAtTzOffset:a.getTimezoneOffset()});i?ve.sendOtelLogsToNewRelic([c]):ve.logsCache.push(c)}catch(r){ve.addLogInCurrentSpan("error","opentelemetry::addLogInCurrentSpan_failed",{error:pd(r)})}}static sendOtelLogsToNewRelic(t){const e=pr.getContext(ve.meetingMetadata.peerId);fetch(ve.logsEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({meetingMetadata:Hf(e,"sendOtelLogsToNewRelic",ve.meetingMetadata,"meetingMetadata"),serviceName:e.getValue("sdkName"),logs:t})}).catch(n=>{ve.addLogInCurrentSpan("error","opentelemetry::sendOtelLogToNewRelic_failed",{error:pd(n)}),ve.logsCache.push(...t)})}static processCachedLogs(){const t=ve.logsCache.splice(0,25);t!=null&&t.length&&ve.sendOtelLogsToNewRelic(t)}static destruct(){clearInterval(ve.logsProcessorTimer),ve.processCachedLogs(),navigator.isReactNative||document.removeEventListener("visibilitychange",ve.processCachedLogs)}};let k=ve;y(k,"logsCache",[]),y(k,"logsProcessorTimer"),y(k,"location",{country:void 0}),y(k,"tracingEnabled",!0),y(k,"initialized",!1),y(k,"logsProcessingInterval",7e3),y(k,"logExclusionList",["message","websocket/message","roomMessage","websocket/room-message","websocket/room-legacy-mode","chatMessage","websocket/new-chat-message","websocket/no-active-speaker","websocket/selected-peers","websocket/active-speaker","ping","websocket/new-consumer","websocket/producer-score","websocket/consumer-score","websocket/plugin-event","websocket/plugin-data","websocket/plugin-internal-data"]),y(k,"meetingMetadata",{});class m{static info(e,n,i){k.addLogInCurrentSpan("info",e,n,i)}static error(e,n,i){k.addLogInCurrentSpan("error",e,n,i)}static debug(e,n,i){k.addLogInCurrentSpan("debug",e,n,i)}static log(e,n,i){k.addLogInCurrentSpan("log",e,n,i)}static warn(e,n,i){k.addLogInCurrentSpan("warn",e,n,i)}}const ZR=()=>{!navigator.isReactNative&&typeof window!="undefined"&&(window.addEventListener("error",t=>{var e;!((e=t.filename)!=null&&e.includes("localhost"))&&t.lineno!==0&&m.error("window::error",{error:t.error},!0)}),window.addEventListener("unhandledrejection",t=>{var e,n,i,s,r,a,c,d;m.error("window::unhandledrejection",{error:t==null?void 0:t.reason,networkCall:{url:(n=(e=t==null?void 0:t.reason)==null?void 0:e.config)==null?void 0:n.url,baseURL:(s=(i=t==null?void 0:t.reason)==null?void 0:i.config)==null?void 0:s.baseURL,method:(a=(r=t==null?void 0:t.reason)==null?void 0:r.config)==null?void 0:a.method,status:(c=t==null?void 0:t.reason)==null?void 0:c.status,statusText:(d=t==null?void 0:t.reason)==null?void 0:d.statusText}},!0)}),window.addEventListener("offline",()=>{m.info("window::offline")}),window.addEventListener("online",()=>{m.info("window::online")}))},eP={"00":"DyteClient","01":"Controller","02":"RoomNodeClient","03":"HiveNodeClient","04":"SocketService","05":"Chat","06":"Plugin","07":"Polls","08":"Meta","09":"Preset",10:"Recording",11:"Self",12:"Participant",13:"Spotlight",14:"Remote Request",15:"Webinar",16:"LocalMediaHandler",17:"End-End Encryption",18:"AI",19:"Livestream",20:"Stage"},md={"0000":"Internal exception.","0001":"Failed to initialize.","0002":"Failed to join room.","0003":"Failed to leave room.","0004":"Invalid auth token","0010":"Browser not supported","0011":"HTTP Network Error","0012":"Websocket Network Error","0013":"Rate Limited","0100":"Internal exception","0101":"Permission denied","0102":"Prerequisite module missing","0200":"Internal exception.","0300":"Internal exception","0400":"Internal exception","0404":"Missing prerequisites to establish a websocket connection","0500":"Internal exception","0501":"Permission denied.","0502":"Invalid message body.","0503":"Text Message is too large","0504":"Message not found by the given id","0505":"Action not permitted without joining room","0506":"Message search is disabled","0510":"Invalid channel name.","0600":"Internal exception","0601":"Permission denied.","0602":"Auth token not set for plugin","0603":"Iframe was not provided","0700":"Internal exception","0705":"Action not permitted without joining room","0800":"Internal exception","0801":"Permission denied","0900":"Internal exception","0904":"Could not load preset",1e3:"Internal exception",1001:"Permission denied",1004:"Could not find specified recording",1005:"Action not permitted in given recording state",1100:"Internal exception",1101:"Permission denied",1102:"Unsupported",1103:"Name cannot be empty",1104:"No device selected while calling meeting.self.setDevice",1105:"Action not permitted without joining room",1106:"Can't set currently used device",1200:"Internal exception",1201:"Permission denied",1202:"Invalid page number was requested",1203:"Invalid participant count per page was requested",1204:"No participants exists with the given UserIds",1205:"Action not permitted without joining room",1206:"Manual Subscription Mode was not ACTIVATED",1207:"Invalid view mode",1208:"Manual Subscription not enabled for organization",1209:"Broadcast message type must be a non-empty string",1300:"Internal exception",1400:"Internal exception",1402:"No existing remote requests",1403:"No peer exists with given id",1500:"Internal exception",1600:"Internal exception",1601:"Failed to get audio track",1602:"Failed to get video track",1603:"Incorrect device",1604:"Failed to change device",1605:"Failed to get audio & video track",1606:"No audio input devices are available",1607:"No video input devices are available",1608:"No audio output devices (speakers) are available",1609:"Failed to fetch list of media devices",1610:"No media track exists",1611:"Failed to unmute track",1612:"Failed to get screenshare tracks",1701:"Crypto error",1800:"Internal exception",1801:"Can't fetch transcript file",1900:"Internal exception",1901:"Permission denied.",1902:"Livestream that has not yet started, can't be stopped",2e3:"Internal exception",2001:"Permission denied",2002:"Unsupported",2003:"Stage is disabled",2004:"Method not implemented",2005:"Action not permitted without joining room",2006:"Action not permitted in current stage status",9900:"Internal exception"};Object.keys(md).forEach(t=>{md[t]=`{${eP[t.slice(0,2)]}} ${md[t]}`});class O extends Error{constructor(e,n,i=!1){super(e),y(this,"code"),this.code=n,this.name="DyteError",this.message=`[ERR${this.code}]: ${md[this.code]}
20
+ ${this.message}`;try{let s=i;n&&n.endsWith("00")&&(s=!0),s&&m.error("DyteError",{error:{message:this.message,name:this.name,code:n}});const r=pr.getContext(pr.getMostRecentPeerId());if(r){const a=r.getValue("onError");try{a(this)}catch(c){}}typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("dyteError",{detail:this}))}catch(s){}}}function Lc(t,e,n,i){if(i instanceof O)throw i;if(i instanceof e){const s=new O(i.message,n);throw s.stack=i.stack,s}else throw i}function qf(t,e,n){if(!t.value){const s=t.get,r=t.set;return s&&(t.get=function(){try{return s.apply(this)}catch(a){Lc(this,e,n,a)}}),r&&(t.set=function(a){try{return r.apply(this,[a])}catch(c){Lc(this,e,n,c)}}),t}const i=t.value;return t.value=function(...s){try{const r=i.apply(this,s);return r&&r instanceof Promise?r.catch(a=>{Lc(this,e,n,a)}):r}catch(r){Lc(this,e,n,r)}},t}function tP(t,e){return(n,i,s)=>{if(s)return qf(s,t,e);for(const r of Reflect.ownKeys(n.prototype).filter(a=>a!=="constructor")){const a=Object.getOwnPropertyDescriptor(n.prototype,r);(a.value instanceof Function||a.get instanceof Function||a.set instanceof Function)&&Object.defineProperty(n.prototype,r,qf(a,t,e))}}}const Lt=t=>tP(Error,t);function nP(t){let e=0,n,i;if(!t)return e;for(n=0;n<t.length;n+=1)i=t.charCodeAt(n),e=(e<<5)-e+i,e|=0;return Math.abs(e)%100+1}var Xi,Zi;const Xy=class extends Nt.EventEmitter{constructor(){super(),S(this,Xi,void 0),S(this,Zi,void 0),y(this,"asyncPromiseTimeout"),T(this,Xi,new Map),T(this,Zi,new Map),this.asyncPromiseTimeout=8e3}emitAsync(t,...e){return p(this,null,function*(){o(this,Xi).set(t,[]);const n=o(this,Zi).get(t).map(()=>new Promise(i=>{o(this,Xi).get(t).push(i)}));DS(Xy.prototype,this,"emit").call(this,t,...e),yield Promise.race([Promise.all(n),new Promise((i,s)=>setTimeout(()=>s(new Error(`emitAsync failed to resolve for event ${t}.`)),this.asyncPromiseTimeout))]),o(this,Xi).delete(t)})}onAsync(t,e){const n=o(this,Xi),i=(...s)=>p(this,null,function*(){var r;try{yield e(...s)}catch(c){m.error("[onAsync]",{error:c})}const a=(r=n.get(t))==null?void 0:r.shift();a==null||a()});return o(this,Zi).get(t)||o(this,Zi).set(t,[]),o(this,Zi).get(t).push(i),super.on(t,i)}reset(){T(this,Xi,new Map),T(this,Zi,new Map),super.removeAllListeners()}};let iP=Xy;Xi=new WeakMap,Zi=new WeakMap;const L=new iP;function sP(){Be.isElectron()&&window.dyteElectronGetDisplayMediaSource&&(navigator.mediaDevices.getDisplayMedia=()=>p(this,null,function*(){const t=yield window.dyteElectronGetDisplayMediaSource({types:["window","screen"]});let e=[];if(t&&(Array.isArray(t)?e=t:e=[t]),!(e!=null&&e.length))throw new Error("Couldn't find any media source for screen share.");let n=e.find(s=>{var r;return(r=s.id)==null?void 0:r.includes("screen")});n=n!=null?n:e[0];const i={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:n.id}}};return yield navigator.mediaDevices.getUserMedia(i)}))}var x=(t=>(t.NEW_PRODUCER="NEW_PRODUCER",t.PRODUCER_TRACK_ENDED="PRODUCER_TRACK_ENDED",t.ROOM_NODE_CONNECTION_ERROR="ROOM_NODE_CONNECTION_ERROR",t.SOCKET_SERVICE_ROOM_JOINED="SOCKET_SERVICE_ROOM_JOINED",t.SOCKET_SERVICE_RECONNECTED="SOCKET_SERVICE_RECONNECTED",t.SOCKET_SERVICE_DISCONNECTED="SOCKET_SERVICE_DISCONNECTED",t.SOCKET_SERVICE_FAILED="SOCKET_SERVICE_FAILED",t.SOCKET_STATE_UPDATE="SOCKET_STATE_UPDATE",t.ROOM_NODE_RECONNECTED="ROOM_NODE_RECONNECTED",t.ROOM_NODE_DISCONNECTED="ROOM_NODE_DISCONNECTED",t.ROOM_NODE_FAILED="ROOM_NODE_FAILED",t.TRANSPORT_STATE_UPDATE="TRANSPORT_STATE_UPDATE",t.PRODUCER_SCORE_UPDATE="PRODUCER_SCORE_UPDATE",t.CONSUMER_SCORE_UPDATE="CONSUMER_SCORE_UPDATE",t.PRODUCER_STATUS_UPDATE="PRODUCER_STATUS_UPDATE",t.CONSUMER_STATUS_UPDATE="CONSUMER_STATUS_UPDATE",t.LOW_PRODUCER_SCORE="LOW_PRODUCER_SCORE",t.LOW_CONSUMER_SCORE="LOW_CONSUMER_SCORE",t.MEDIA_PERMISSION_ERROR="MEDIA_PERMISSION_ERROR",t.MEDIA_PERMISSION_UPDATE="MEDIA_PERMISSION_UPDATE",t.WAITLISTED="WAIT_LISTED",t.MESSAGE="websocket/message",t.ROOM_MESSAGE="websocket/room-message",t.PEER_JOINED_INTERNAL="peer/joined-internal",t.PEER_CLOSED="websocket/peer-closed",t.CONSUMER_CLOSED="websocket/consumer-closed",t.CONSUMER_PAUSED="websocket/consumer-paused",t.CONSUMER_RESUMED="websocket/consumer-resumed",t.PRODUCER_CLOSED="websocket/producer-closed",t.NEW_CONSUMER="websocket/new-consumer",t.PRODUCER_SCORE="websocket/producer-score",t.CONSUMER_SCORE="websocket/consumer-score",t.PRODUCER_TOGGLE="hive/producer-toggle",t.CONSUMER_TOGGLE="hive/consumer-toggle",t.SELECTED_PEERS_DIFF="hive/selected-peers-diff",t.UPDATE_ACTIVE="media/update-active",t.RESET_PRODUCER_STATE="hive/reset-producer-state",t.CF_TRANSPORT_STATE_CHANGED="cf/transport-state-changed",t.CF_ROOM_REJOINING="cf/room-rejoining",t.CF_ROOM_REJOIN_FAILED="cf/room-rejoining-failed",t.CF_ROOM_REJOINED="cf/room-rejoined",t.CF_TRANPSORT_RECONNECTING="cf/transport-reconnecting",t.ROOM_STATE="sockethub/room-state",t.PEER_DISPLAY_NAME_CHANGED="hive/display-name-changed",t.GET_STAGE_REQUESTS="GET_STAGE_REQUESTS",t.UPDATE_STAGE_REQUESTS="UPDATE_STAGE_REQUESTS",t.KICK_PEER="KICK_PEER",t.UPDATE_PEER_STAGE_STATUS="UPDATE_PEER_STAGE_STATUS",t.JOIN_MEDIA_ROOM="JOIN_MEDIA_ROOM",t.LEAVE_MEDIA_ROOM="LEAVE_MEDIA_ROOM",t.PIP_HANGUP="PIP_HANGUP",t.E2EE_ACTIVE_PRODUCER="E2EE_ACTIVE_PRODUCER",t.E2EE_INACTIVE_PRODUCER="E2EE_INACTIVE_PRODUCER",t.E2EE_ACTIVE_CONSUMER="E2EE_ACTIVE_CONSUMER",t.E2EE_INACTIVE_CONSUMER="E2EE_INACTIVE_CONSUMER",t.SOCKET_PEERS="SOCKET_PEERS",t.UPDATE_PERMISSIONS="UPDATE_PERMISSIONS",t.MAX_SPATIAL_LAYER_CHANGE="MAX_SPATIAL_LAYER_CHANGE",t.MUTE_SELF="MUTE_SELF",t.MUTE_SELF_VIDEO="MUTE_SELF_VIDEO",t))(x||{});class Ca extends Nt.EventEmitter{constructor(){super(),super.setMaxListeners(25)}emit(e,...n){return super.emit("*",e,...n),super.emit(e,...n)}on(e,n){try{const i=this.listenerCount(e);i>25&&i%25===0&&m.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch(i){}return super.on(e,n)}addListener(e,n){try{const i=this.listenerCount(e);i>25&&i%25===0&&m.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch(i){}return super.addListener(e,n)}off(e,n){return super.off(e,n)}once(e,n){return super.once(e,n)}prependListener(e,n){return super.prependListener(e,n)}prependOnceListener(e,n){return super.prependOnceListener(e,n)}removeListener(e,n){return super.removeListener(e,n)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}class fn extends Nt.EventEmitter{constructor(){super(),super.setMaxListeners(25)}emit(e,...n){return super.emit("*",e,...n),super.emit(e,...n)}on(e,n){try{const i=this.listenerCount(e);i>25&&i%25===0&&m.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch(i){}return super.on(e,n)}addListener(e,n){try{const i=this.listenerCount(e);i>25&&i%25===0&&m.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch(i){}return super.addListener(e,n)}off(e,n){return super.off(e,n)}once(e,n){return super.once(e,n)}prependListener(e,n){return super.prependListener(e,n)}prependOnceListener(e,n){return super.prependOnceListener(e,n)}removeListener(e,n){return super.removeListener(e,n)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}function rP(t,e=2){return t.replace(/[^\u00BF-\u1FFF\u2C00-\uD7FF\w\s]/g,"").trim().split(/\s+/).slice(0,e).map(n=>n.charAt(0)).join("").toUpperCase()}const Gf=1080,$f=1920,aP=(t,e,n,i,s,r)=>{let a=.5,c=.5;const d=s,h=r,u=Math.min(n/d,i/h);let g=d*u,E=h*u,b,w,M,D,F=1;return g<n&&(F=n/g),Math.abs(F-1)<1e-14&&E<i&&(F=i/E),g*=F,E*=F,M=d/(g/n),D=h/(E/i),b=(d-M)*a,w=(h-D)*c,b<0&&(b=0),w<0&&(w=0),M>d&&(M=d),D>h&&(D=h),[b,w,M,D,t,e,n,i]};var Ln,ho,jt,xn,nt,Zn,es,en,dt,po,mo,ts,fo;const Zy=class extends fn{constructor(t,e,n,i){super(),S(this,Ln,void 0),S(this,ho,void 0),S(this,jt,void 0),S(this,xn,void 0),S(this,nt,{height:Gf,width:$f}),S(this,Zn,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"}),S(this,es,void 0),S(this,en,{}),S(this,dt,void 0),S(this,po,void 0),S(this,mo,void 0),S(this,ts,void 0),S(this,fo,!1),y(this,"cleanupEventListeners",()=>{o(this,ho).unsubscribe("stageStatus",this.handlePipMediaControls),o(this,dt).removeListener("videoUpdate",this.onSelfVideoUpdateListener),o(this,dt).removeListener("audioUpdate",this.onSelfAudioUpdateListener),o(this,dt).removeListener("roomLeft",()=>this.disable())}),y(this,"enablePipMediaControls",()=>{this.mountAudioEvents(),this.mountVideoEvents()}),y(this,"onSelfVideoUpdateListener",({videoEnabled:s})=>{this.updateMediaSession("CAMERA",s)}),y(this,"onSelfAudioUpdateListener",({audioEnabled:s})=>{this.updateMediaSession("MIC",s)}),y(this,"handlePipMediaControls",s=>{s==="ON_STAGE"?this.enablePipMediaControls():this.unmountEvents()}),y(this,"eventCallback",s=>{s==="CAMERA"&&(o(this,dt).videoEnabled?o(this,dt).disableVideo():o(this,dt).enableVideo(),this.emit("cameraToggled")),s==="MIC"&&(o(this,dt).audioEnabled?o(this,dt).disableAudio():o(this,dt).enableAudio(),this.emit("micToggled")),s==="END"&&(L.emit(x.PIP_HANGUP),this.cleanupEventListeners(),this.emit("hangup"),this.cleanup())}),y(this,"unmountEvents",()=>{navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("togglemicrophone",void 0),navigator.mediaSession.setActionHandler("togglecamera",void 0))}),y(this,"animate",()=>{if(!this.isActive&&o(this,ts)==="active"){this.disable(!0);return}o(this,en)!==void 0&&this.paintCanvas(),o(this,es)!==void 0&&T(this,es,requestAnimationFrame(()=>this.animate()))}),y(this,"disable",(s=!1)=>{T(this,ts,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(o(this,es)),s!==!0&&document.body.removeChild(o(this,jt)),T(this,es,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()}),T(this,ho,t),T(this,ts,"idle"),T(this,dt,e),T(this,Zn,{brand:e.config.designTokens.colors.brand[500],background:e.config.designTokens.colors.background[1e3],text:e.config.designTokens.colors.text,videoBackground:e.config.designTokens.colors.videoBg,textOnBrand:e.config.designTokens.colors.textOnBrand}),n&&this.setupIcon("pin",n),i&&this.setupIcon("handRaise",i)}static _init(t,e){return p(this,null,function*(){let n,i;try{n=yield Nc(zR),i=yield Nc(YR)}catch(s){}return new Zy(t,e,n,i)})}setupIcon(t,e){return p(this,null,function*(){switch(t){case"handRaise":T(this,mo,e);break;case"pin":T(this,po,e);break}})}overrideIcon(t,e){return p(this,null,function*(){switch(t){case"handRaise":T(this,mo,yield Nc(e));break;case"pin":T(this,po,yield Nc(e));break}})}constructImage(t){const e=new Image,n=new Blob([t],{type:"image/svg+xml"}),i=window.URL.createObjectURL(n);return new Promise(s=>{e.onload=()=>{s(e),window.URL.revokeObjectURL(i)},e.src=i})}createVideoContainer(){T(this,jt,document.createElement("div")),o(this,jt).style.width="0.1px",o(this,jt).style.height="0.1px",o(this,jt).style.overflow="hidden",o(this,jt).style.position="absolute",o(this,jt).style.bottom="0",o(this,jt).style.right="0",o(this,jt).style.opacity="0",o(this,jt).appendChild(o(this,xn))}setupEventListeners(){o(this,ho).subscribe("stageStatus",this.handlePipMediaControls),o(this,dt).addListener("videoUpdate",this.onSelfVideoUpdateListener),o(this,dt).addListener("audioUpdate",this.onSelfAudioUpdateListener),o(this,dt).addListener("roomLeft",()=>this.disable())}createCanvas(){const t=document.createElement("canvas");t.height=o(this,nt).height,t.width=o(this,nt).width,T(this,Ln,t)}setupMediaSessionEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("hangup",()=>{this.eventCallback("END")}),this.mountAudioEvents(),this.mountVideoEvents())}mountAudioEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setMicrophoneActive===void 0||o(this,dt).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||o(this,dt).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const t=Object.values(o(this,en)).reduce((e,n)=>(e[n.pinned?"pinned":"regular"].push(n),e),{pinned:[],regular:[]});return[...t.pinned,...t.regular]}drawEmptyTile(t,e,n,i){if(o(this,Ln)===void 0)return;const s=o(this,Ln).getContext("2d"),r=o(this,Ln).width,a=0,c=0,d=e-a*2,h=n-a*2,u=Math.floor(r/d),g=Math.floor(t/u),E=t%u*(d+a)+a,b=g*(h+a)+a,{displayText:w,image:M}=i!=null?i:{};s.fillStyle=w||M?o(this,Zn).videoBackground:o(this,Zn).background,s.strokeStyle=o(this,Zn).brand,s.beginPath(),s.moveTo(E+c,b),s.arcTo(E+d,b,E+d,b+c,c),s.arcTo(E+d,b+h,E+d-c,b+h,c),s.arcTo(E,b+h,E,b+h-c,c),s.arcTo(E,b,E+c,b,c),s.closePath(),s.fill(),s.stroke();const D=d/6,F=d/2+E,Y=h/2+b;s.save(),(w||M)&&(s.beginPath(),s.arc(F,Y,D,0,Math.PI*2),s.fillStyle=o(this,Zn).brand,s.fill(),M?(s.clip(),s.drawImage(M,F-D,Y-D,D*2,D*2),s.restore()):w&&(s.fillStyle=o(this,Zn).textOnBrand,s.font=`${D/2}px sans-serif`,s.textAlign="center",s.textBaseline="middle",s.fillText(w,F,Y)),this.drawIcons(i,E,b,Math.max(d,h)))}drawIcons(t,e,n,i){const s=Math.min(Math.max(i*.15,100),200),r=s*.2,a=s*.2;let c=e+r;const d=n+r,h=u=>{const g=o(this,Ln).getContext("2d");g.save(),g.fillStyle=o(this,Zn).background,g.beginPath(),g.moveTo(c+a,d),g.arcTo(c+s,d,c+s,d+a,a),g.arcTo(c+s,d+s,c+s-a,d+s,a),g.arcTo(c,d+s,c,d+s-a,a),g.arcTo(c,d,c+a,d,a),g.closePath(),g.fill(),typeof u=="string"?(g.font=`${s/1.5}px sans-serif`,g.fillStyle=o(this,Zn).text,g.textAlign="center",g.textBaseline="top",g.fillText(u,s/2+c,d+r)):g.drawImage(u,c+r,d+r,s-r*2,s-r*2),c+=s+r,g.restore()};t.pinned&&h(o(this,po)),t.handRaised&&h(o(this,mo))}drawTile(t,e,n){var i,s;if(o(this,Ln)===void 0)return;const r=o(this,Ln).getContext("2d"),a=this.getSources();let c=0,d=0;for(;c<o(this,nt).height-5;){let h=0;for(;h<o(this,nt).width-5&&d<n;){if((i=a[d])!=null&&i.enabled){const u=a[d].element,[g,E,b,w,M,D,F,Y]=aP(h,c,t,e,u.videoWidth,u.videoHeight);(s=u==null?void 0:u.classList)!=null&&s.contains("mirror")?(r.save(),r.scale(-1,1),r.drawImage(u,g,E,b,w,-1*M,D,-1*F,Y),r.restore()):r.drawImage(u,g,E,b,w,M,D,F,Y),this.drawIcons(a[d],M,D,Math.max(F,Y))}else this.drawEmptyTile(d,t,e,a[d]);d+=1,h+=t}c+=e}}calcGridElemSize(t){switch(t){case 0:case 1:return[o(this,nt).width,o(this,nt).height];case 2:return[Math.floor(o(this,nt).width/2),o(this,nt).height];case 3:case 4:return[Math.floor(o(this,nt).width/2),Math.floor(o(this,nt).height/2)];case 5:case 6:return[Math.floor(o(this,nt).width/3),Math.floor(o(this,nt).height/2)];case 7:case 8:case 9:return[Math.floor(o(this,nt).width/3),Math.floor(o(this,nt).height/3)];default:return[Math.floor(o(this,nt).width/3),Math.floor(o(this,nt).height/2)]}}paintCanvas(){let t=this.getSources().length;t!==1&&(t=t%2>0?t+1:t);const[e,n]=this.calcGridElemSize(t);this.drawTile(e,n,t)}isSupported(){var t;return!!window.chrome&&document.pictureInPictureEnabled&&((t=o(this,dt).config)==null?void 0:t.viewType)!=="LIVESTREAM"}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(T(this,fo,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),o(this,jt))try{document.body.removeChild(o(this,jt))}catch(t){}this.removeAllSources(),T(this,Ln,void 0),T(this,xn,void 0),T(this,es,void 0)}init({height:t,width:e}={}){if(!this.isSupported())throw m.error("DytePip.unsupported"),new Error("Picture-in-picture is not available in this environment");if(o(this,fo))return;T(this,fo,!0),this.createCanvas(),this.setupMediaSessionEvents();const n=document.createElement("video");T(this,nt,{height:t!=null?t:Gf,width:e!=null?e:$f}),n.height=o(this,nt).height,n.width=o(this,nt).width,n.autoplay=!0,n.muted=!0,n.srcObject=o(this,Ln).captureStream(24),T(this,xn,n),o(this,xn).onloadedmetadata=()=>{try{this.emit("pipStarted"),o(this,xn).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch(i){this.emit("pipEnded")}},this.createVideoContainer(),this.paintCanvas()}updateMediaSession(t,e){navigator.mediaSession!==void 0&&(t==="CAMERA"&&navigator.mediaSession.setCameraActive!==void 0&&navigator.mediaSession.setCameraActive(e),t==="MIC"&&navigator.mediaSession.setMicrophoneActive!==void 0&&navigator.mediaSession.setMicrophoneActive(e))}enableSource(t){o(this,en)[t]!==void 0&&(o(this,en)[t].enabled=!0)}disableSource(t){o(this,en)[t]!==void 0&&(o(this,en)[t].enabled=!1)}generateAvatar(t,e){return p(this,null,function*(){if(!e)return;const n=new Image;try{const i=yield(yield fetch(e)).blob(),s=window.URL.createObjectURL(i);n.onload=()=>{this.updateSource(t,{image:n}),window.URL.revokeObjectURL(s)},n.src=s}catch(i){m.error("DytePip::GenerateAvatar",{error:i})}})}addSource(t,e,n,i=!1,s=void 0,r=void 0,a=!1){m.debug("DytePIP::AddSource",{pip:{id:t,handRaised:a}}),o(this,en)[t]={id:t,element:e,enabled:n,pinned:i,displayText:s?rP(s):void 0,imageUrl:r,handRaised:a},r&&this.generateAvatar(t,r)}updateSource(t,e){m.info("DytePIP::UpdateSource",{pip:{id:t,handRaised:e.handRaised}});const n=o(this,en)[t];n&&(o(this,en)[t]=H(H({},n),e))}removeSource(t){delete o(this,en)[t]}removePinnedSource(){Object.values(o(this,en)).forEach(t=>{t.pinned&&this.removeSource(t.id)})}removeAllSources(){T(this,en,{})}enable(){T(this,ts,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",o(this,dt).videoEnabled),this.updateMediaSession("MIC",o(this,dt).audioEnabled),document.body.appendChild(o(this,jt)),T(this,es,requestAnimationFrame(()=>this.animate())),o(this,xn).onloadedmetadata=()=>{o(this,xn).requestPictureInPicture().then(()=>{T(this,ts,"active")})},o(this,xn).readyState===4&&o(this,xn).requestPictureInPicture().then(()=>{T(this,ts,"active")})}};let oP=Zy;Ln=new WeakMap,ho=new WeakMap,jt=new WeakMap,xn=new WeakMap,nt=new WeakMap,Zn=new WeakMap,es=new WeakMap,en=new WeakMap,dt=new WeakMap,po=new WeakMap,mo=new WeakMap,ts=new WeakMap,fo=new WeakMap;var Pi;(function(t){t[t.PUBLISHER=0]="PUBLISHER",t[t.SUBSCRIBER=1]="SUBSCRIBER"})(Pi||(Pi={}));var ci;(function(t){t[t.AUDIO=0]="AUDIO",t[t.VIDEO=1]="VIDEO"})(ci||(ci={}));class cP extends _{constructor(){super("media.Codec",[{no:1,name:"channels",kind:"scalar",opt:!0,T:5},{no:2,name:"clock_rate",kind:"scalar",T:5},{no:3,name:"mime_type",kind:"scalar",T:9},{no:4,name:"sdp_fmtp_line",kind:"scalar",opt:!0,T:9},{no:5,name:"payload_type",kind:"scalar",opt:!0,T:13}])}}const e0=new cP;class dP extends _{constructor(){super("media.HeaderExtension",[{no:1,name:"direction",kind:"scalar",opt:!0,T:9},{no:2,name:"uri",kind:"scalar",T:9}])}}const lP=new dP;class uP extends _{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new uP;class hP extends _{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",Pi]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const Jn=new hP;class pP extends _{constructor(){super("media.ProducerPayload",[{no:1,name:"kind",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8},{no:4,name:"msid",kind:"scalar",T:9},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"mime_type",kind:"scalar",opt:!0,T:9}])}}const mP=new pP;class fP extends _{constructor(){super("media.CreateTransportRequest",[{no:1,name:"consuming",kind:"scalar",T:8},{no:2,name:"force_tcp",kind:"scalar",opt:!0,T:8},{no:3,name:"description",kind:"message",T:()=>Jn},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8},{no:5,name:"producers",kind:"message",repeat:1,T:()=>mP}])}}const gP=new fP;class vP extends _{constructor(){super("media.AudioActivityRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"energy",kind:"scalar",T:5},{no:3,name:"silent",kind:"scalar",T:8}])}}const yP=new vP;class EP extends _{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Jn},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:4,name:"producer_ids",kind:"scalar",repeat:2,T:9}])}}const t0=new EP;class SP extends _{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Jn}])}}const TP=new SP;class bP extends _{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Jn}])}}new bP;class kP extends _{constructor(){super("media.NestedScore",[{no:1,name:"encoding_idx",kind:"scalar",T:5},{no:2,name:"rid",kind:"scalar",T:9},{no:3,name:"score",kind:"scalar",T:5},{no:4,name:"ssrc",kind:"scalar",T:3,L:0}])}}const wP=new kP;class _P extends _{constructor(){super("media.ProducerTrack",[{no:1,name:"track_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9},{no:3,name:"stream_id",kind:"scalar",T:9}])}}const IP=new _P;class CP extends _{constructor(){super("media.ProducerEntry",[{no:1,name:"producing_transport_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9}])}}new CP;class RP extends _{constructor(){super("media.ConsumerEntry",[{no:1,name:"consuming_transport_id",kind:"scalar",T:9},{no:2,name:"consumer_id",kind:"scalar",T:9}])}}new RP;class PP extends _{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",ci]},{no:3,name:"pause",kind:"scalar",T:8},{no:4,name:"screen_share",kind:"scalar",T:8},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9},{no:8,name:"codec",kind:"message",T:()=>e0}])}}const Sc=new PP;class AP extends _{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Sc},{no:3,name:"producer_track",kind:"message",T:()=>IP},{no:4,name:"error_code",kind:"scalar",opt:!0,T:9}])}}const MP=new AP;class OP extends _{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>MP}}])}}const n0=new OP;class DP extends _{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>Kf},{no:2,name:"receiver",kind:"message",T:()=>Kf}])}}const i0=new DP;class NP extends _{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>e0},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>lP}])}}const Jf=new NP;class LP extends _{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>Jf},{no:2,name:"video",kind:"message",T:()=>Jf}])}}const Kf=new LP;class xP extends _{constructor(){super("media.PreferredCodec",[{no:1,name:"audio",kind:"scalar",opt:!0,T:9},{no:2,name:"video",kind:"scalar",opt:!0,T:9}])}}const VP=new xP;class UP extends _{constructor(){super("media.edge.GeoLocation",[{no:1,name:"latitude",kind:"scalar",T:2},{no:2,name:"longitude",kind:"scalar",T:2},{no:3,name:"region",kind:"scalar",opt:!0,T:9}])}}const BP=new UP;class FP extends _{constructor(){super("media.edge.PeerJoinRequest",[{no:1,name:"display_name",kind:"scalar",opt:!0,T:9},{no:2,name:"prejoined",kind:"scalar",T:8},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:5,name:"preset",kind:"scalar",opt:!0,T:12},{no:6,name:"user_id",kind:"scalar",opt:!0,T:9},{no:7,name:"organization_id",kind:"scalar",opt:!0,T:9},{no:8,name:"location",kind:"message",T:()=>BP},{no:9,name:"capabilities",kind:"message",T:()=>i0}])}}const jP=new FP;class WP extends _{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const HP=new WP;class qP extends _{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const GP=new qP;class $P extends _{constructor(){super("media.edge.ConsumeMultipleProducerRequest",[{no:1,name:"producer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8}])}}new $P;class JP extends _{constructor(){super("media.edge.ConsumePeerRequest",[{no:1,name:"producing_peer_id",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8},{no:3,name:"producer_id",kind:"scalar",opt:!0,T:9},{no:4,name:"preferred_codec",kind:"message",T:()=>VP},{no:5,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const KP=new JP;class zP extends _{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>KP},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const YP=new zP;class QP extends _{constructor(){super("media.edge.ProducerCreateRequest",[{no:1,name:"kind",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8},{no:4,name:"description",kind:"message",T:()=>Jn},{no:5,name:"msid",kind:"scalar",T:9},{no:6,name:"app_data",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9},{no:8,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const XP=new QP;class ZP extends _{constructor(){super("media.edge.SelectedPeersRequest",[])}}new ZP;class e1 extends _{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const t1=new e1;class n1 extends _{constructor(){super("media.edge.ProducerToggleRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const xc=new n1;class i1 extends _{constructor(){super("media.edge.ConsumerToggleRequest",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}new i1;class s1 extends _{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Jn},{no:3,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const r1=new s1;class a1 extends _{constructor(){super("media.edge.ConsumerCloseRequest",[{no:1,name:"consumer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"description",kind:"message",T:()=>Jn},{no:3,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const o1=new a1;class c1 extends _{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new c1;class d1 extends _{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const s0=new d1;class l1 extends _{constructor(){super("media.edge.PeerDisplayNameEditRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}const u1=new l1;class h1 extends _{constructor(){super("media.edge.HostMediaControlForPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"audio",kind:"scalar",T:8},{no:3,name:"video",kind:"scalar",T:8},{no:4,name:"scree_share",kind:"scalar",T:8}])}}const p1=new h1;class m1 extends _{constructor(){super("media.edge.HostMediaControlForAllPeerRequest",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8}])}}const f1=new m1;class g1 extends _{constructor(){super("media.edge.GetRoomStateResponse",[{no:1,name:"display_title",kind:"scalar",T:9},{no:2,name:"locked_mode",kind:"scalar",T:8},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"room_name",kind:"scalar",T:9},{no:5,name:"current_peer_id",kind:"scalar",T:9},{no:6,name:"is_recording",kind:"scalar",opt:!0,T:8},{no:7,name:"recorder_participant_id",kind:"scalar",opt:!0,T:9},{no:8,name:"pinned_peer_ids",kind:"scalar",repeat:2,T:9}])}}const v1=new g1;class y1 extends _{constructor(){super("media.edge.ErrorResponse",[{no:1,name:"error_message",kind:"scalar",T:9},{no:2,name:"event_id",kind:"scalar",T:5}])}}const E1=new y1;class S1 extends _{constructor(){super("media.edge.EmptyResponse",[])}}new S1;class T1 extends _{constructor(){super("media.edge.RoomParticipants",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"producer_states",kind:"message",repeat:1,T:()=>Sc},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"user_id",kind:"scalar",opt:!0,T:9},{no:5,name:"capabilities",kind:"message",T:()=>i0}])}}const r0=new T1;class b1 extends _{constructor(){super("media.edge.SelectedPeersResponse",[{no:1,name:"audio_peers",kind:"scalar",repeat:2,T:9},{no:2,name:"compulsory_peers",kind:"scalar",repeat:2,T:9}])}}const bh=new b1;class k1 extends _{constructor(){super("media.edge.SelectedPeersDiffEntry",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"priority",kind:"scalar",T:5}])}}const w1=new k1;class _1 extends _{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>w1}])}}const zf=new _1;class I1 extends _{constructor(){super("media.edge.PeerJoinResponse",[])}}new I1;class C1 extends _{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>v1},{no:2,name:"participants",kind:"message",repeat:1,T:()=>r0},{no:3,name:"selected_peers",kind:"message",T:()=>bh},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const kh=new C1;class R1 extends _{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const P1=new R1;class A1 extends _{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>n0}])}}new A1;class M1 extends _{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>n0},{no:3,name:"description",kind:"message",T:()=>Jn}])}}const O1=new M1;class D1 extends _{constructor(){super("media.edge.ProducerCreateResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"producer_id",kind:"scalar",T:9},{no:4,name:"description",kind:"message",T:()=>Jn}])}}const N1=new D1;class L1 extends _{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>wP}])}}new L1;class x1 extends _{constructor(){super("media.edge.ActiveSpeakerResponse",[{no:1,name:"responsepeer_id",kind:"scalar",T:9},{no:2,name:"volume",kind:"scalar",T:5}])}}new x1;class V1 extends _{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new V1;class U1 extends _{constructor(){super("media.edge.ProducerToggleResponse",[])}}new U1;class B1 extends _{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new B1;class F1 extends _{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>Jn}])}}const j1=new F1;class W1 extends _{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>Jn}])}}const H1=new W1;class q1 extends _{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new q1;class G1 extends _{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new G1;class $1 extends _{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new $1;class J1 extends _{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const K1=new J1;class z1 extends _{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Y1=new z1;class Q1 extends _{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const X1=new Q1;class Z1 extends _{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>r0}])}}const Yf=new Z1;class eA extends _{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const Qf=new eA;class tA extends _{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>Qf},{no:3,name:"screenshare",kind:"message",T:()=>Qf}])}}const nA=new tA;class iA extends _{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>t0},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>nA}])}}new iA;class sA extends _{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Sc}])}}const rA=new sA;class aA extends _{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Sc},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const Xf=new aA;class oA extends _{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Sc}])}}const cA=new oA;class dA extends _{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const wh=new dA;class lA extends _{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Zf=new lA;class uA extends _{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new uA;class hA extends _{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new hA;class pA extends _{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new pA;class mA extends _{constructor(){super("media.edge.PeerDisplayNameEditBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}new mA;class fA extends _{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new fA;class gA extends _{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new gA;class vA extends _{constructor(){super("socket.ai.MeetingTranscript",[{no:1,name:"meeting_id",kind:"scalar",T:9},{no:2,name:"transcript",kind:"scalar",T:9},{no:3,name:"is_partial",kind:"scalar",T:8}])}}const wu=new vA;class yA extends _{constructor(){super("socket.api.BaseSocketHubMessage",[{no:1,name:"event",kind:"scalar",T:5},{no:2,name:"id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9},{no:4,name:"room_id",kind:"scalar",T:9},{no:5,name:"user_id",kind:"scalar",T:9},{no:6,name:"payload",kind:"scalar",T:12},{no:7,name:"error",kind:"scalar",opt:!0,T:8},{no:8,name:"sid",kind:"scalar",opt:!0,T:9}])}}new yA;class EA extends _{constructor(){super("socket.api.ErrorMessage",[{no:1,name:"code",kind:"scalar",opt:!0,T:5},{no:2,name:"message",kind:"scalar",T:9}])}}const SA=new EA;var mr;(function(t){t[t.BROWSER=0]="BROWSER",t[t.TRACK=1]="TRACK",t[t.COMPOSITE=2]="COMPOSITE"})(mr||(mr={}));var ki;(function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.ON_STAGE=1]="ON_STAGE",t[t.APPROVED_STAGE=2]="APPROVED_STAGE",t[t.REQUESTED_STAGE=3]="REQUESTED_STAGE",t[t.OFF_STAGE=4]="OFF_STAGE"})(ki||(ki={}));var _h;(function(t){t[t.NONE=0]="NONE",t[t.RECORDER=1]="RECORDER",t[t.LIVESTREAMER=2]="LIVESTREAMER"})(_h||(_h={}));var Ih;(function(t){t[t.PEERS=0]="PEERS",t[t.ROOMS=1]="ROOMS"})(Ih||(Ih={}));var dl;(function(t){t[t.HIVE=0]="HIVE",t[t.CHAT=1]="CHAT",t[t.PING=2]="PING"})(dl||(dl={}));class TA extends _{constructor(){super("socket.room.PeerFlags",[{no:1,name:"preset_name",kind:"scalar",T:9},{no:2,name:"recorder_type",kind:"scalar",T:9},{no:3,name:"hidden_participant",kind:"scalar",T:8}])}}const bA=new TA;class kA extends _{constructor(){super("socket.room.Peer",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"stage_type",kind:"enum",opt:!0,T:()=>["socket.room.StageType",ki,"STAGE_TYPE_"]},{no:5,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:6,name:"preset_id",kind:"scalar",opt:!0,T:9},{no:7,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:8,name:"waitlisted",kind:"scalar",T:8},{no:9,name:"flags",kind:"message",T:()=>bA}])}}const ql=new kA;class wA extends _{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>ql}])}}const qr=new wA;class _A extends _{constructor(){super("socket.room.PeerStatusUpdate",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"stage_type",kind:"enum",opt:!0,T:()=>["socket.room.StageType",ki,"STAGE_TYPE_"]}])}}const eg=new _A;class IA extends _{constructor(){super("socket.room.RoomPeersInfoRequest",[{no:1,name:"seach_query",kind:"scalar",T:9},{no:2,name:"limit",kind:"scalar",T:5},{no:3,name:"offset",kind:"scalar",T:5}])}}const CA=new IA;class RA extends _{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>ql}])}}const _u=new RA;class PA extends _{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const tg=new PA;class AA extends _{constructor(){super("socket.room.Room",[{no:1,name:"room_id",kind:"scalar",T:9},{no:2,name:"title",kind:"scalar",T:9},{no:4,name:"created_at",kind:"scalar",T:4,L:2},{no:5,name:"active_recordings",kind:"message",repeat:1,T:()=>OA},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const a0=new AA;class MA extends _{constructor(){super("socket.room.ActiveRecording",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",mr]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const OA=new MA;class DA extends _{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>a0}])}}const ng=new DA;class NA extends _{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const o0=new NA;class LA extends _{constructor(){super("socket.room.UpdatePeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9}])}}new LA;class xA extends _{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>ql},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"organization_id",kind:"scalar",opt:!0,T:9},{no:5,name:"use_hive",kind:"scalar",opt:!0,T:8},{no:6,name:"preset",kind:"scalar",opt:!0,T:12},{no:7,name:"capabilities",kind:"enum",repeat:1,T:()=>["socket.room.Capabilities",dl,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const VA=new xA;class UA extends _{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>ql},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const BA=new UA;class FA extends _{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>a0}])}}new FA;class jA extends _{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new jA;class WA extends _{constructor(){super("socket.room.ServiceError",[{no:1,name:"message",kind:"scalar",opt:!0,T:9},{no:2,name:"code",kind:"scalar",opt:!0,T:9}])}}const em=new WA;class HA extends _{constructor(){super("socket.room.ConnectedMeetingPeer",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9},{no:3,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:4,name:"preset_id",kind:"scalar",opt:!0,T:9},{no:5,name:"display_picture_url",kind:"scalar",opt:!0,T:9}])}}const qA=new HA;class GA extends _{constructor(){super("socket.room.ConnectedMeetingDump",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9},{no:3,name:"participants",kind:"message",repeat:1,T:()=>qA}])}}const ig=new GA;class $A extends _{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>ig},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>ig}])}}const JA=new $A;class KA extends _{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const zA=new KA;class YA extends _{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>zA}])}}const QA=new YA;class XA extends _{constructor(){super("socket.room.CreateRoomResponsePayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9},{no:3,name:"error",kind:"message",T:()=>em}])}}const ZA=new XA;class eM extends _{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>ZA}])}}const sg=new eM;class tM extends _{constructor(){super("socket.room.UpdateRoomRequestPayload",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9}])}}const nM=new tM;class iM extends _{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>nM}])}}new iM;class sM extends _{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const rM=new sM;class aM extends _{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>rM}])}}const oM=new aM;class cM extends _{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>uM}])}}const dM=new cM;class lM extends _{constructor(){super("socket.room.DisableConnectedRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"status",kind:"scalar",opt:!0,T:9},{no:3,name:"title",kind:"scalar",opt:!0,T:9},{no:4,name:"error",kind:"message",T:()=>em}])}}const uM=new lM;class hM extends _{constructor(){super("socket.room.MovePeerPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"preset_id",kind:"scalar",opt:!0,T:9}])}}const pM=new hM;class mM extends _{constructor(){super("socket.room.MovePeersBetweenRoomsRequest",[{no:1,name:"source_meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"destination_meeting_id",kind:"scalar",opt:!0,T:9},{no:3,name:"participants",kind:"message",repeat:1,T:()=>pM}])}}const fM=new mM;class gM extends _{constructor(){super("socket.room.MovedPeer",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:3,name:"error",kind:"message",T:()=>em}])}}const c0=new gM;class vM extends _{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>c0}])}}new vM;class yM extends _{constructor(){super("socket.room.TransferPeer",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"auth_token",kind:"scalar",opt:!0,T:9}])}}const EM=new yM;class SM extends _{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>kM}])}}const TM=new SM;class bM extends _{constructor(){super("socket.room.AddedParticipant",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",opt:!0,T:9},{no:3,name:"picture",kind:"scalar",opt:!0,T:9},{no:4,name:"custom_participant_id",kind:"scalar",T:9}])}}const kM=new bM;class wM extends _{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const d0=new wM;class _M extends _{constructor(){super("socket.room.BroadcastMessage",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"timestamp",kind:"scalar",T:4,L:2},{no:4,name:"ids",kind:"scalar",repeat:2,T:9},{no:5,name:"broadcast_type",kind:"enum",opt:!0,T:()=>["socket.room.BroadcastType",Ih,"BROADCAST_TYPE_"]}])}}const xa=new _M;class IM extends _{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const CM=new IM;class RM extends _{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const PM=new RM;class AM extends _{constructor(){super("socket.room.WaitingRoomRequest",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"picture",kind:"scalar",opt:!0,T:9},{no:5,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:6,name:"preset_name",kind:"scalar",opt:!0,T:9}])}}const MM=new AM;class OM extends _{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>MM}])}}const rg=new OM;class DM extends _{constructor(){super("socket.room.GetRoomStageStateResponse",[{no:1,name:"on_stage_peers",kind:"scalar",repeat:2,T:9},{no:2,name:"approved_stage_peers",kind:"scalar",repeat:2,T:9},{no:3,name:"requested_stage_peers",kind:"scalar",repeat:2,T:9}])}}const ag=new DM;var Ch;(function(t){t[t.NONE=0]="NONE",t[t.SKIP=1]="SKIP",t[t.ON_PRIVILEGED_USER_ENTRY=2]="ON_PRIVILEGED_USER_ENTRY",t[t.SKIP_ON_ACCEPT=3]="SKIP_ON_ACCEPT"})(Ch||(Ch={}));var vs;(function(t){t[t.NONE=0]="NONE",t[t.ALLOWED=1]="ALLOWED",t[t.NOT_ALLOWED=2]="NOT_ALLOWED",t[t.CAN_REQUEST=3]="CAN_REQUEST"})(vs||(vs={}));class NM extends _{constructor(){super("socket.preset.PollsPermissionUpdate",[{no:1,name:"can_create",kind:"scalar",opt:!0,T:8},{no:2,name:"can_vote",kind:"scalar",opt:!0,T:8},{no:3,name:"can_view",kind:"scalar",opt:!0,T:8}])}}const LM=new NM;class xM extends _{constructor(){super("socket.preset.PluginsPermissionsUpdate",[{no:1,name:"can_close",kind:"scalar",opt:!0,T:8},{no:2,name:"can_start",kind:"scalar",opt:!0,T:8}])}}const VM=new xM;class UM extends _{constructor(){super("socket.preset.PublicChatPermission",[{no:1,name:"can_send",kind:"scalar",opt:!0,T:8},{no:2,name:"text",kind:"scalar",opt:!0,T:8},{no:3,name:"files",kind:"scalar",opt:!0,T:8}])}}const BM=new UM;class FM extends _{constructor(){super("socket.preset.PrivateChatPermission",[{no:1,name:"can_send",kind:"scalar",opt:!0,T:8},{no:2,name:"can_receive",kind:"scalar",opt:!0,T:8},{no:3,name:"text",kind:"scalar",opt:!0,T:8},{no:4,name:"files",kind:"scalar",opt:!0,T:8}])}}const jM=new FM;class WM extends _{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>BM},{no:2,name:"private",kind:"message",T:()=>jM}])}}const HM=new WM;class qM extends _{constructor(){super("socket.preset.ConnectedMeetingPermissionUpdate",[{no:1,name:"can_alter_connected_meetings",kind:"scalar",opt:!0,T:8},{no:2,name:"can_switch_to_parent_meeting",kind:"scalar",opt:!0,T:8},{no:3,name:"can_switch_connected_meetings",kind:"scalar",opt:!0,T:8}])}}const GM=new qM;class $M extends _{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",vs,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",vs,"STREAM_PERMISSION_TYPE_"]}])}}const Iu=new $M;class JM extends _{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>Iu},{no:2,name:"audio",kind:"message",T:()=>Iu},{no:3,name:"screenshare",kind:"message",T:()=>Iu}])}}const KM=new JM;class zM extends _{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>LM},{no:2,name:"plugins",kind:"message",T:()=>VM},{no:3,name:"chat",kind:"message",T:()=>HM},{no:4,name:"accept_waiting_requests",kind:"scalar",opt:!0,T:8},{no:5,name:"can_accept_production_requests",kind:"scalar",opt:!0,T:8},{no:6,name:"can_edit_display_name",kind:"scalar",opt:!0,T:8},{no:7,name:"can_record",kind:"scalar",opt:!0,T:8},{no:8,name:"can_livestream",kind:"scalar",opt:!0,T:8},{no:9,name:"can_spotlight",kind:"scalar",opt:!0,T:8},{no:10,name:"disable_participant_audio",kind:"scalar",opt:!0,T:8},{no:11,name:"disable_participant_screensharing",kind:"scalar",opt:!0,T:8},{no:12,name:"disable_participant_video",kind:"scalar",opt:!0,T:8},{no:13,name:"kick_participant",kind:"scalar",opt:!0,T:8},{no:14,name:"pin_participant",kind:"scalar",opt:!0,T:8},{no:15,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:16,name:"waiting_room_type",kind:"enum",opt:!0,T:()=>["socket.preset.WaitingRoomType",Ch,"WAITING_ROOM_TYPE_"]},{no:17,name:"is_recorder",kind:"scalar",opt:!0,T:8},{no:18,name:"recorder_type",kind:"enum",opt:!0,T:()=>["socket.room.RecorderType",_h,"RECORDER_TYPE_"]},{no:19,name:"hidden_participant",kind:"scalar",opt:!0,T:8},{no:20,name:"show_participant_list",kind:"scalar",opt:!0,T:8},{no:21,name:"can_change_participant_permissions",kind:"scalar",opt:!0,T:8},{no:22,name:"connected_meetings",kind:"message",T:()=>GM},{no:23,name:"media",kind:"message",T:()=>KM}])}}const tm=new zM;class YM extends _{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const QM=new YM;class XM extends _{constructor(){super("socket.preset.PeerPreset",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"preset",kind:"scalar",T:12}])}}const ZM=new XM;class eO extends _{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>ZM}])}}const tO=new eO;class nO extends _{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>tm}])}}const l0=new nO;class iO extends _{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>l0}])}}const sO=new iO;class rO extends _{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>l0}])}}const og=new rO;class aO extends _{constructor(){super("socket.preset.PeerUserIDMap",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9}])}}const oO=new aO;class cO extends _{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>oO},{no:2,name:"patch",kind:"message",T:()=>tm}])}}new cO;class dO extends _{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>tm}])}}new dO;class lO extends _{constructor(){super("socket.chat.ChatMessage",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"user_id",kind:"scalar",T:9},{no:4,name:"display_name",kind:"scalar",T:9},{no:5,name:"pinned",kind:"scalar",T:8},{no:6,name:"is_edited",kind:"scalar",T:8},{no:7,name:"payload_type",kind:"scalar",T:5},{no:8,name:"payload",kind:"scalar",T:9},{no:10,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:11,name:"created_at",kind:"scalar",T:4,L:2},{no:12,name:"created_at_ms",kind:"scalar",opt:!0,T:4,L:2},{no:13,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:14,name:"channel_index",kind:"scalar",opt:!0,T:9}])}}const Ir=new lO;class uO extends _{constructor(){super("socket.chat.GetPaginatedChatMessageRoomRequest",[{no:1,name:"time_stamp",kind:"scalar",T:4,L:2},{no:2,name:"size",kind:"scalar",T:5},{no:3,name:"from",kind:"scalar",T:5},{no:4,name:"reversed",kind:"scalar",T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const hO=new uO;class pO extends _{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Ir},{no:2,name:"next",kind:"scalar",T:8}])}}const mO=new pO;class fO extends _{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Ir}])}}const u0=new fO;class gO extends _{constructor(){super("socket.chat.SendChatMessageToRoomRequest",[{no:1,name:"payload_type",kind:"scalar",T:5},{no:2,name:"payload",kind:"scalar",T:9}])}}const vO=new gO;class yO extends _{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>Ir}])}}const Cu=new yO;class EO extends _{constructor(){super("socket.chat.SendChatMessageToPeersRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"payload_type",kind:"scalar",T:5},{no:3,name:"payload",kind:"scalar",T:9}])}}const SO=new EO;class TO extends _{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>Ir}])}}const Ru=new TO;class bO extends _{constructor(){super("socket.chat.SendChatMessageToChannelRequest",[{no:1,name:"channel_id",kind:"scalar",T:9},{no:2,name:"payload_type",kind:"scalar",T:5},{no:3,name:"payload",kind:"scalar",T:9}])}}const kO=new bO;class wO extends _{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>Ir}])}}new wO;class _O extends _{constructor(){super("socket.chat.EditChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"payload_type",kind:"scalar",opt:!0,T:5},{no:3,name:"payload",kind:"scalar",opt:!0,T:9},{no:4,name:"pinned",kind:"scalar",opt:!0,T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const IO=new _O;class CO extends _{constructor(){super("socket.chat.PinChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"pinned",kind:"scalar",T:8},{no:3,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const RO=new CO;class PO extends _{constructor(){super("socket.chat.PinChatMessageResponse",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"pinned",kind:"scalar",T:8},{no:3,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const Vc=new PO;class AO extends _{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>Ir}])}}const Uc=new AO;class MO extends _{constructor(){super("socket.chat.DeleteChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const OO=new MO;class DO extends _{constructor(){super("socket.chat.DeleteChatMessageResponse",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const Bc=new DO;class NO extends _{constructor(){super("socket.chat.SearchChatMessagesRequest",[{no:1,name:"time_stamp",kind:"scalar",T:4,L:2},{no:2,name:"size",kind:"scalar",T:5},{no:3,name:"from",kind:"scalar",T:5},{no:4,name:"reversed",kind:"scalar",T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:6,name:"search_term",kind:"scalar",T:9}])}}const LO=new NO;class xO extends _{constructor(){super("socket.chat.MarkChannelIndexAsReadRequest",[{no:1,name:"channel_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"channel_index",kind:"scalar",T:9}])}}const VO=new xO;class UO extends _{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}const BO=new UO;class FO extends _{constructor(){super("socket.chat.CreateChatChannelRequest",[{no:1,name:"display_name",kind:"scalar",T:9},{no:2,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:3,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:4,name:"visibility",kind:"scalar",T:9},{no:5,name:"is_direct_message",kind:"scalar",T:8}])}}const jO=new FO;class WO extends _{constructor(){super("socket.chat.UpdateChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9},{no:3,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:4,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:5,name:"visibility",kind:"scalar",opt:!0,T:9},{no:6,name:"is_direct_message",kind:"scalar",opt:!0,T:8}])}}const HO=new WO;class qO extends _{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new qO;class GO extends _{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}const $O=new GO;class JO extends _{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>Ir},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const KO=new JO;class zO extends _{constructor(){super("socket.chat.ChatChannel",[{no:1,name:"chat_channel_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9},{no:3,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:4,name:"visibility",kind:"scalar",T:9},{no:5,name:"is_direct_message",kind:"scalar",T:8},{no:6,name:"latest_message_and_unread_count",kind:"message",T:()=>KO},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const YO=new zO;class QO extends _{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>YO}])}}const mi=new QO;class XO extends _{constructor(){super("socket.chat.ChannelMember",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",opt:!0,T:9},{no:3,name:"picture",kind:"scalar",opt:!0,T:9},{no:4,name:"custom_participant_id",kind:"scalar",T:9}])}}const ZO=new XO;class eD extends _{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>ZO}])}}const tD=new eD;class nD extends _{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const iD=new nD;class sD extends _{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const rD=new sD;class aD extends _{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const oD=new aD;class cD extends _{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const dD=new cD;class lD extends _{constructor(){super("socket.plugin.EnablePluginForPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const uD=new lD;class hD extends _{constructor(){super("socket.plugin.DisablePluginForPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const pD=new hD;class mD extends _{constructor(){super("socket.plugin.PluginEventToRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const fD=new mD;class gD extends _{constructor(){super("socket.plugin.PluginEventToPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9},{no:3,name:"plugin_data",kind:"scalar",T:12}])}}const vD=new gD;class yD extends _{constructor(){super("socket.plugin.StoreKeys",[{no:1,name:"store_key",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",opt:!0,T:12}])}}const nm=new yD;class ED extends _{constructor(){super("socket.plugin.PluginStoreInsertKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"insert_keys",kind:"message",repeat:1,T:()=>nm}])}}const cg=new ED;class SD extends _{constructor(){super("socket.plugin.PluginStoreGetKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"get_keys",kind:"message",repeat:1,T:()=>nm}])}}const TD=new SD;class bD extends _{constructor(){super("socket.plugin.PluginStoreDeleteKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"delete_keys",kind:"message",repeat:1,T:()=>nm}])}}const kD=new bD;class wD extends _{constructor(){super("socket.plugin.PluginStoreDeleteRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9}])}}const _D=new wD;class ID extends _{constructor(){super("socket.plugin.EnablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"enabled_by",kind:"scalar",T:9}])}}const Rh=new ID;class CD extends _{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>Rh}])}}const RD=new CD;class PD extends _{constructor(){super("socket.plugin.DisablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"disabled_by",kind:"scalar",T:9}])}}const dg=new PD;class AD extends _{constructor(){super("socket.plugin.PluginStoreItem",[{no:1,name:"timestamp",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"store_key",kind:"scalar",T:9},{no:4,name:"payload",kind:"scalar",T:12}])}}const MD=new AD;class OD extends _{constructor(){super("socket.plugin.PluginStoreResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"store_items",kind:"message",repeat:1,T:()=>MD}])}}const lg=new OD;class DD extends _{constructor(){super("socket.plugin.PluginEventResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const ug=new DD;class ND extends _{constructor(){super("socket.livestreaming.LiveStreamingEvent",[{no:1,name:"livestream_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"meeting_id",kind:"scalar",T:9},{no:5,name:"playback_url",kind:"scalar",T:9},{no:6,name:"org_id",kind:"scalar",T:9},{no:7,name:"room_name",kind:"scalar",T:9},{no:8,name:"room_uuid",kind:"scalar",T:9},{no:9,name:"status",kind:"scalar",T:9},{no:10,name:"manual_ingest",kind:"scalar",opt:!0,T:8}])}}const hg=new ND;class LD extends _{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const pg=new LD;class xD extends _{constructor(){super("socket.livestreaming.StageRequest",[{no:1,name:"display_name",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9}])}}const VD=new xD;class UD extends _{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>VD}])}}const Pu=new UD;class BD extends _{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const FD=new BD;class jD extends _{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const WD=new jD;class HD extends _{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const mg=new HD;class qD extends _{constructor(){super("socket.polls.Poll",[{no:1,name:"poll_id",kind:"scalar",T:9},{no:2,name:"created_by",kind:"scalar",T:9},{no:3,name:"created_by_user_id",kind:"scalar",T:9},{no:4,name:"question",kind:"scalar",T:9},{no:5,name:"options",kind:"message",repeat:1,T:()=>$D},{no:6,name:"hide_votes",kind:"scalar",T:8},{no:7,name:"anonymous",kind:"scalar",T:8},{no:8,name:"votes",kind:"scalar",repeat:2,T:9}])}}const h0=new qD;class GD extends _{constructor(){super("socket.polls.PollOption",[{no:1,name:"text",kind:"scalar",T:9},{no:2,name:"count",kind:"scalar",opt:!0,T:4,L:2},{no:3,name:"votes",kind:"message",repeat:1,T:()=>KD}])}}const $D=new GD;class JD extends _{constructor(){super("socket.polls.PollVote",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])}}const KD=new JD;class zD extends _{constructor(){super("socket.polls.NewPollRequest",[{no:1,name:"question",kind:"scalar",T:9},{no:2,name:"options",kind:"scalar",repeat:2,T:9},{no:3,name:"anonymous",kind:"scalar",T:8},{no:4,name:"hide_votes",kind:"scalar",T:8},{no:5,name:"created_by",kind:"scalar",opt:!0,T:9},{no:6,name:"created_by_user_id",kind:"scalar",opt:!0,T:9}])}}const YD=new zD;class QD extends _{constructor(){super("socket.polls.VotePollRequest",[{no:1,name:"poll_id",kind:"scalar",T:9},{no:2,name:"index",kind:"scalar",T:4,L:2}])}}const XD=new QD;class ZD extends _{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>h0}])}}const Au=new ZD;class eN extends _{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>h0}])}}const tN=new eN;class nN extends _{constructor(){super("socket.recording.RecordingEvent",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",mr]}])}}const fg=new nN;class iN extends _{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:0},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const e=this.create(),n=Date.now();return e.seconds=xe.from(Math.floor(n/1e3)).toBigInt(),e.nanos=n%1e3*1e6,e}toDate(e){return new Date(xe.from(e.seconds).toNumber()*1e3+Math.ceil(e.nanos/1e6))}fromDate(e){const n=this.create(),i=e.getTime();return n.seconds=xe.from(Math.floor(i/1e3)).toBigInt(),n.nanos=i%1e3*1e6,n}internalJsonWrite(e,n){let i=xe.from(e.seconds).toNumber()*1e3;if(i<Date.parse("0001-01-01T00:00:00Z")||i>Date.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(e.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let s="Z";if(e.nanos>0){let r=(e.nanos+1e9).toString().substring(1);r.substring(3)==="000000"?s="."+r.substring(0,3)+"Z":r.substring(6)==="000"?s="."+r.substring(0,6)+"Z":s="."+r+"Z"}return new Date(i).toISOString().replace(".000Z",s)}internalJsonRead(e,n,i){if(typeof e!="string")throw new Error("Unable to parse Timestamp from JSON "+Ap(e)+".");let s=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!s)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let r=Date.parse(s[1]+"-"+s[2]+"-"+s[3]+"T"+s[4]+":"+s[5]+":"+s[6]+(s[8]?s[8]:"Z"));if(Number.isNaN(r))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return i||(i=this.create()),i.seconds=xe.from(r/1e3).toBigInt(),i.nanos=0,s[7]&&(i.nanos=parseInt("1"+s[7]+"0".repeat(9-s[7].length))-1e9),i}}new iN;class sN extends _{constructor(){super("common.BaseHubMessage",[{no:1,name:"event",kind:"scalar",T:5},{no:2,name:"id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9},{no:4,name:"room_id",kind:"scalar",T:9},{no:5,name:"user_id",kind:"scalar",T:9},{no:6,name:"payload",kind:"scalar",T:12},{no:7,name:"error",kind:"scalar",opt:!0,T:8},{no:8,name:"sid",kind:"scalar",opt:!0,T:9},{no:9,name:"room_object_id",kind:"scalar",opt:!0,T:9},{no:10,name:"preset",kind:"scalar",opt:!0,T:9}])}}const Ph=new sN;class rN extends _{constructor(){super("common.BulkedHubMessage",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Ph}])}}new rN;class aN extends _{constructor(){super("common.CFWorkersResponse",[{no:1,name:"responses",kind:"message",repeat:1,T:()=>Ph},{no:2,name:"broadcast_responses",kind:"message",repeat:1,T:()=>Ph}])}}new aN;const oN=0,cN=1,dN=2,lN=3,uN=4,hN=5,pN={getPeerInfo:0,updatePeerInfo:1,getRoomPeersInfo:2,joinRoom:3,leaveRoom:4,getRoomInfo:5,updateRoomInfo:6,closeRoom:7,startedLivestream:8,stoppedLivestream:9,erroredLivestream:10,getStagePeers:11,getStageRequests:12,requestStageAccess:13,cancelStageRequest:14,grantStageAccess:15,denyStageAccess:16,roomPeerCount:17,joinStage:18,leaveStage:19,getConnectedRoomsDump:20,createConnectedRooms:21,deleteConnectedRooms:22,movePeers:23,transferPeer:24,movedPeer:25,connectedRoomsUpdated:26,connectedRoomsDeleted:27,getAllAddedParticipants:28,broadcastMessage:29,kick:30,kickAll:31,transcript:32,getWaitingRoomRequests:33,acceptWaitingRoomRequests:34,waitingRoomRequestAccepted:35,denyWaitingRoomRequests:36,waitingRoomRequestDenied:37,peerStageStatusUpdate:38,broadcastToEntity:39,recordingStarted:40,recordingStopped:41,recordingPaused:42,getRoomStageState:43,livestreamingInvoked:44},mN={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,sendMessageToChannel:6,searchChannelMessages:7,getAllChatChannels:8,markChannelIndexAsRead:9,pinMessage:10},fN={getPlugins:0,addPlugin:1,enablePluginForRoom:2,disablePluginForPeers:3,enablePluginForPeers:4,disablePluginForRoom:5,removePlugin:6,customPluginEventToRoom:7,customPluginEventToPeers:8,storeInsertKeys:9,storeGetKeys:10,storeDeleteKeys:11,storeDelete:12},gN={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},p0={unknown:0,createWebRTCTransport:1,produce:2,consume:3,toggleProducer:4,toggleConsumer:5,closeProducer:6,closeConsumer:7,joinRoom:16,leaveRoom:17,selectedPeer:18,globalPinPeer:19,selfJoinComplete:20,peerJoinedBroadcast:25,peerLeaveBroadcast:26,peerProducerCreateBroadcast:27,peerProducerToggleBroadcast:28,peerProducerCloseBroadcast:29,globalPeerPinBroadcast:30,recordingStartedBroadcast:31,recordingStoppedBroadcast:32,peerDisplayNameEditBroadcast:33,mediaRoomTerminationBroadcastResponse:36,selectedPeerDiff:40,renegotiateSessionDescription:50,errorResponse:60,kickPeer:90,kickAll:91,changeDisplayName:92,hostControlPeer:93,hostControlAllPeers:94,audioActivity:100},vN={createChatChannel:0,getChatChannel:1,deprecatedGetAllChatChannels:2,getChannelMembers:3,updateChatChannel:4},yN={getUserPresets:0,updateUserPreset:1};function Ra(t,e){return Object.keys(e).reduce((n,i)=>(n[i]=(t<<16)+e[i],n),{})}function m0(t,e){return Object.keys(t).reduce((n,i)=>(n[i]=e|t[i],n),{})}const z=Ra(oN,pN),Ge=Ra(cN,mN),ie=Ra(dN,fN),Ei=Ra(lN,gN),sr=Ra(uN,vN),_n=m0(p0,16777216),Wn=m0(p0,50331648),fd=Ra(hN,yN);var EN=Object.defineProperty,SN=Object.getOwnPropertyDescriptor,im=(t,e,n,i)=>{for(var s=i>1?void 0:i?SN(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&EN(e,n,s),s},Ds,gg;const Ah=(gg=class{constructor(t){S(this,Ds,void 0),T(this,Ds,t)}createChannel(t,e,n,i="public",s=!1){return p(this,null,function*(){const r={displayName:t,targetUserIds:e,displayPictureUrl:n,visibility:i,isDirectMessage:s};s&&(r.visibility="private");const a=yield o(this,Ds).sendMessagePromise(sr.createChatChannel,jO.toBinary(r)),c=mi.fromBinary(a.payload).chatChannels;return Ah.formatChannel(c[0])})}updateChannel(t,e){return p(this,null,function*(){const n=yield o(this,Ds).sendMessagePromise(sr.updateChatChannel,HO.toBinary({chatChannelId:t,targetUserIds:e.memberIds,displayName:e.displayName,displayPictureUrl:e.displayPictureUrl,visibility:e.visibility})),i=mi.fromBinary(n.payload).chatChannels;return Ah.formatChannel(i[0])})}static formatChannel(t){var e;const{latestMessageAndUnreadCount:n}=t,i=ee(H({},t),{id:t.chatChannelId,memberIds:t.targetUserIds,unreadCount:(e=n==null?void 0:n.unreadCount)!=null?e:0});return n!=null&&n.message&&(i.latestMessage=Ii.formatSocketServiceMessage(n.message)),delete i.chatChannelId,delete i.targetUserIds,delete i.latestMessageAndUnreadCount,i}getChannelMembers(t){return p(this,null,function*(){try{const e=yield o(this,Ds).sendMessagePromise(sr.getChannelMembers,$O.toBinary({chatChannelId:t}));return tD.fromBinary(e.payload).channelMembers.map(n=>{var i=n,{id:s}=i,r=Pl(i,["id"]);return ee(H({},r),{userId:s})})}catch(e){return[]}})}on(t,e){let n,i;switch(t){case sr.createChatChannel:{n=mi.fromBinary.bind(mi),i=mi.create();break}case sr.updateChatChannel:{n=mi.fromBinary.bind(mi),i=mi.create();break}}if(!n){m.warn(`ChatChannelSocketHandler::Event ${t} is not recognized`);return}o(this,Ds).on(t,({payload:s})=>{let r=i;try{r=n(s)}catch(a){m.error("ChatChannelSocketHandler::on::binary_decode_error",{error:a})}return e(r)})}},Ds=new WeakMap,gg);let yr=Ah;im([k.trace("ChatChannelHandler.createChannel")],yr.prototype,"createChannel",1);im([k.trace("ChatChannelHandler.updateChannel")],yr.prototype,"updateChannel",1);im([k.trace("ChatChannelHandler.getChannelMembers")],yr.prototype,"getChannelMembers",1);var TN=Object.defineProperty,bN=Object.getOwnPropertyDescriptor,Kn=(t,e,n,i)=>{for(var s=i>1?void 0:i?bN(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&TN(e,n,s),s},$t=(t=>(t[t.TEXT=0]="TEXT",t[t.IMAGE=1]="IMAGE",t[t.FILE=2]="FILE",t[t.CUSTOM=3]="CUSTOM",t))($t||{}),Wt;class In{constructor(e){S(this,Wt,void 0),T(this,Wt,e)}getChatMessages(){return o(this,Wt).sendMessagePromise(Ge.getMessages)}getChatMessagesPaginated(e,n,i,s=0,r=""){return p(this,null,function*(){const a={timeStamp:e,size:n,from:s,reversed:i,channelId:r},c=yield o(this,Wt).sendMessagePromise(Ge.getPaginatedMessages,hO.toBinary(a));return c.payload?mO.fromBinary(c.payload):{messages:[],next:!1}})}sendMessageToRoom(e,n){const i={payloadType:n,payload:e};o(this,Wt).sendMessage(Ge.sendMessageToRoom,vO.toBinary(i))}sendMessageToPeers(e,n,i){const s={payloadType:n,peerIds:i,payload:e};o(this,Wt).sendMessage(Ge.sendMessageToPeers,SO.toBinary(s))}sendMessageToChannel(e,n,i){const s={payloadType:n,channelId:i,payload:e};o(this,Wt).sendMessage(Ge.sendMessageToChannel,kO.toBinary(s))}sendMessage(e,n,i,s){if(s&&this.sendMessageToChannel(e,n,s),i&&i.length>0){this.sendMessageToPeers(e,n,i);return}this.sendMessageToRoom(e,n)}editMessage(e,n,i,s,r){return p(this,null,function*(){const a={chatId:e,payloadType:i,payload:n};s&&(a.channelId=s),r!==void 0&&(a.pinned=r);const c=yield o(this,Wt).sendMessagePromise(Ge.editMessage,IO.toBinary(a));return Uc.fromBinary(c.payload).message})}deleteMessage(e,n){return p(this,null,function*(){const i={chatId:e};n&&(i.channelId=n);const s=yield o(this,Wt).sendMessagePromise(Ge.deleteMessage,OO.toBinary(i)),r=Bc.fromBinary(s.payload);return H({id:r.chatId},r.channelId?{channelId:r.channelId}:{})})}searchMessages(e,n){return p(this,null,function*(){var i,s,r;const a={searchTerm:e,timeStamp:(i=n.timestamp)!=null?i:Date.now(),size:(s=n.size)!=null?s:75,from:0,reversed:(r=n.reversed)!=null?r:!0};n.channelId&&(a.channelId=n.channelId);try{const c=yield o(this,Wt).sendMessagePromise(Ge.searchChannelMessages,LO.toBinary(a));return u0.fromBinary(c.payload).messages}catch(c){return[]}})}getAllChannels(){return p(this,null,function*(){try{const e=yield o(this,Wt).sendMessagePromise(Ge.getAllChatChannels);return mi.fromBinary(e.payload).chatChannels.map(yr.formatChannel)}catch(e){return[]}})}markLastReadMessage(e,n){return p(this,null,function*(){const i=yield o(this,Wt).sendMessagePromise(Ge.markChannelIndexAsRead,VO.toBinary({channelId:e,userId:n.userId,channelIndex:n.channelIndex}));return BO.fromBinary(i.payload).channelIndex})}setPinState(e,n){return p(this,null,function*(){const i={chatId:e.id,pinned:n,channelId:e.channelId},s=yield o(this,Wt).sendMessagePromise(Ge.pinMessage,RO.toBinary(i));return Vc.fromBinary(s.payload)})}on(e,n){let i,s;switch(e){case Ge.sendMessageToRoom:{i=Cu.fromBinary.bind(Cu),s=Cu.create();break}case Ge.sendMessageToPeers:{i=Ru.fromBinary.bind(Ru),s=Ru.create();break}case Ge.editMessage:{i=Uc.fromBinary.bind(Uc),s=Uc.create();break}case Ge.pinMessage:{i=Vc.fromBinary.bind(Vc),s=Vc.create();break}case Ge.deleteMessage:{i=Bc.fromBinary.bind(Bc),s=Bc.create();break}}if(!i){m.warn(`ChatSocketHandler::Event ${e} is not recognized`);return}o(this,Wt).on(e,({payload:r})=>{let a=s;try{a=i(r)}catch(c){m.error("chatSocketHandler::on::binary_decode_error",{error:c})}return n(a)})}}Wt=new WeakMap;Kn([k.trace("SocketService.getChatMessages")],In.prototype,"getChatMessages",1);Kn([k.trace("SocketService.getChatMessagesPaginated")],In.prototype,"getChatMessagesPaginated",1);Kn([k.trace("SocketService.sendMessageToRoom")],In.prototype,"sendMessageToRoom",1);Kn([k.trace("SocketService.sendMessageToPeers")],In.prototype,"sendMessageToPeers",1);Kn([k.trace("SocketService.sendMessageToChannel")],In.prototype,"sendMessageToChannel",1);Kn([k.trace("SocketService.sendMessage")],In.prototype,"sendMessage",1);Kn([k.trace("SocketService.editMessage")],In.prototype,"editMessage",1);Kn([k.trace("SocketService.deleteMessage")],In.prototype,"deleteMessage",1);Kn([k.trace("SocketService.searchMessages")],In.prototype,"searchMessages",1);Kn([k.trace("SocketService.getAllChannels")],In.prototype,"getAllChannels",1);Kn([k.trace("SocketService.markLastReadMessage")],In.prototype,"markLastReadMessage",1);function kN(t){return t.replace(/([-_]\w)/g,e=>e[1].toUpperCase())}function qn(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(n=>qn(n));const e={};return Object.keys(t).forEach(n=>{const i=Pp(n)?n:kN(n);e[i]=qn(t[n])}),e}function wN(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function f0(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(n=>f0(n));const e={};return Object.keys(t).forEach(n=>{const i=Pp(n)?n:wN(n);e[i]=t[n]}),e}function ll(t,e={}){return t==null?{}:(Object.getOwnPropertyNames(t).forEach(n=>{if(typeof t[n]!="function"){if(typeof t[n]=="object"){ll(t[n],e[n]={});return}e[n]=t[n]}}),e)}class vg{constructor(e){y(this,"defaults"),this.defaults={baseURL:e.baseURL,headers:{common:{}},timeout:e.timeout,retry:e.retry,retryDelay:e.retryDelay}}buildURL(e,n){const{baseURL:i}=this.defaults,s=e.startsWith("http")?e:`${i}${e.startsWith("/")?e:`/${e}`}`;if(n){const r=new URLSearchParams;return Object.entries(n).forEach(([a,c])=>{r.append(a,c)}),`${s}${s.includes("?")?"&":"?"}${r.toString()}`}return s}request(e){return p(this,null,function*(){var n;const i=((n=e.method)==null?void 0:n.toUpperCase())||"GET",s=this.buildURL(e.url||"",e.params),r=H(H({},this.defaults.headers.common),e.headers);i!=="GET"&&i!=="HEAD"&&e.data&&!r["Content-Type"]&&(r["Content-Type"]="application/json");const a=r["Content-Type"]==="application/json"?JSON.stringify(e.data):e.data,c={method:i,headers:r,body:i!=="GET"&&i!=="HEAD"&&e.data?a:void 0},d=e.timeout||this.defaults.timeout,h=e.retry!==void 0?e.retry:this.defaults.retry,u=e.retryDelay||this.defaults.retryDelay;try{const g=new AbortController,E=setTimeout(()=>g.abort(),d);c.signal=g.signal;const b=yield fetch(s,c);clearTimeout(E);let w=null;const M=b.headers.get("content-type");M&&M.includes("application/json")?w=yield b.json():w=yield b.text();const D={};b.headers.forEach((Y,X)=>{D[X]=Y});const F={data:w,status:b.status,statusText:b.statusText,headers:D,config:e};if(!b.ok)throw F;return F}catch(g){if(g instanceof Error&&h>0)return yield new Promise(E=>setTimeout(E,u)),this.defaults.baseURL==="https://api.dyte.io"?this.defaults.baseURL="https://api.cluster.dyte.in":this.defaults.baseURL==="https://api.cluster.dyte.in"&&(this.defaults.baseURL="https://api.dyte.io"),this.request(ee(H({},e),{retry:h-1}));throw g}})}get(e){return p(this,arguments,function*(n,i={}){return this.request(ee(H({},i),{method:"GET",url:n}))})}post(e,n){return p(this,arguments,function*(i,s,r={}){return this.request(ee(H({},r),{method:"POST",url:i,data:s}))})}put(e,n){return p(this,arguments,function*(i,s,r={}){return this.request(ee(H({},r),{method:"PUT",url:i,data:s}))})}}const _N=3,IN=30,CN=8e3;class RN{constructor(e,n){y(this,"ipInfo"),y(this,"fetchClient"),y(this,"requests"),y(this,"roomName"),y(this,"roomUUID"),y(this,"authToken"),y(this,"organizationId"),y(this,"iceServers"),y(this,"pluginInformation"),y(this,"userDetails"),y(this,"roomDetails"),y(this,"context"),this.context=e;const{timeout:i=CN,retry:s=_N,retryDelay:r=IN,baseURL:a="https://api.dyte.io",authToken:c,cachedUserDetails:d}=n||{};this.iceServers=d==null?void 0:d.iceServers,this.pluginInformation=d==null?void 0:d.pluginInformation,this.userDetails=d==null?void 0:d.userDetails,this.roomDetails=d==null?void 0:d.roomDetails,this.requests=new vg({baseURL:a,timeout:i,retry:s,retryDelay:r,responseType:"json"}),this.fetchClient=new vg({baseURL:"",timeout:i,retry:s,retryDelay:r,responseType:"json"}),this.setAuthToken(c,{bearer:!0});const h=this.requests.request.bind(this.requests);this.requests.request=u=>p(this,null,function*(){var g,E,b,w,M;try{k.injectContext(this.requests.defaults.headers.common);const D=yield h(u);return u.url!==k.logsEndpoint&&m.debug("xhr::fetch",{networkCall:{status:D.status,statusText:D.statusText,baseURL:u.baseURL||this.requests.defaults.baseURL,url:u.url,method:u.method}}),D}catch(D){throw D?(((g=D.config)==null?void 0:g.url)!==k.logsEndpoint&&m.error("xhr::fetch",{error:D,networkCall:{status:D.status,statusText:D.statusText,baseURL:((E=D.config)==null?void 0:E.baseURL)||this.requests.defaults.baseURL,url:(b=D.config)==null?void 0:b.url,retries:(w=D.config)==null?void 0:w.retry,method:(M=D.config)==null?void 0:M.method,isOnline:navigator.onLine?"online":"offline"}}),new O(D.message||"Network request failed","0011")):new O("Unknown network error occurred","0011")}})}get peerId(){return this.context.getValue("peerId")}setAuthToken(e,n){const{bearer:i}=n||{};this.authToken=e,this.requests.defaults.headers.common.Authorization=i?`Bearer ${e}`:e}setHeader(e,n){this.requests.defaults.headers.common[e]=n}setRoomName(e){this.roomName=e}setRoomUUID(e){this.roomUUID=e}setOrganizationId(e){this.organizationId=e}}var PN=Object.defineProperty,AN=Object.getOwnPropertyDescriptor,Cn=(t,e,n,i)=>{for(var s=i>1?void 0:i?AN(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&PN(e,n,s),s};class gn extends RN{constructor(e,n){super(e,n),this.setHeader("x-dyte-web-core-version",e.getValue("sdkVersion"))}getIPDetails(){return p(this,null,function*(){var e;const{peerId:n}=this;try{const i=yield Lp.getIPDetails({peerId:n,apiHostnames:Qy(this.context),logger:m});if(m.log("ipInfo",{ipInfo:i}),((e=i==null?void 0:i.loc)==null?void 0:e.length)>5)return i;throw Error("Insufficient data")}catch(i){m.warn("ApiClient.getRoomNodeLinkAndTitleV1 Failed to get ip details",{error:{name:i.name,message:i.message}});return}})}getICEServers(){return p(this,null,function*(){if(this.iceServers)return this.iceServers;const{success:e,iceServers:n}=(yield this.requests.get("/iceservers")).data;if(e)return(n==null?void 0:n.length)>0&&(this.iceServers=n),n})}getPlugins(){return p(this,null,function*(){var e,n,i,s,r,a,c;if(this.pluginInformation)return this.pluginInformation;const{plugins:d}=(yield this.requests.get("/v2/plugins/user")).data.data,h=((n=(e=re.getValue(ue.V1_PLUGINS))==null?void 0:e.toString())==null?void 0:n.split(","))||[],u=d.reduce((g,E)=>(g[h.includes(E.id)?"v1":"v2"].push(ee(H({},E),{name:E.name.replace("v2","")})),g),{v1:[],v2:[]});return(r=(s=(i=this.context.getValue("modules"))==null?void 0:i.devTools)==null?void 0:s.plugins)!=null&&r.length&&((c=(a=this.context.getValue("modules"))==null?void 0:a.devTools)==null||c.plugins.forEach(g=>{var E,b,w;const M=ee(H({},La),{tags:[...La.tags],baseUrl:`http://localhost:${g.port}`,name:g.name,picture:(E=g.picture)!=null?E:La.picture,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),id:g.id,organizationId:this.organizationId,description:(b=g.description)!=null?b:La.description,staggered:(w=g.staggered)!=null?w:La.staggered});u.v2.push(M)})),u.v2})}getPluginDetails(e){return p(this,null,function*(){const{plugin:n}=(yield this.requests.get(`/v2/plugins/view/${e}`)).data.data;return n})}getPluginConfig(e){return p(this,null,function*(){return(yield this.fetchClient.get(`${e}/dyte-config.json`)).data})}authorizePlugin(e){return p(this,null,function*(){const n={peerId:this.peerId},{token:i}=(yield this.requests.post(`/v2/plugins/authorize/${e}`,n)).data.data;return i})}getPresignedUrls(e,n){return p(this,null,function*(){const i=cl(this.context,"chat_upload_expiry"),s={roomUUID:this.roomUUID,filename:e,expiry:typeof i=="number"?i:void 0};re.hasFeature(ue.FEAT_CHAT_SDK)&&(s.viewType=n);const{getLocation:r,putLocation:a}=(yield this.requests.post("/v1/meetings/genPreSignedUploadUrl",s)).data.data;return{getLocation:r,putLocation:a}})}uploadFile(e,n){return p(this,null,function*(){if(navigator.isReactNative&&"uri"in e)try{yield fetch(n,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:{uri:e.uri,name:e.name}})}catch(i){m.error(`sendFileMessage::${i}`)}else yield this.fetchClient.put(n,e,{headers:{"Content-Type":e.type}})})}startLivestreaming(e){return p(this,arguments,function*({manualIngestion:n}){const i=qn(yield this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/livestreams`,{manual_ingest:!!n})).data.data;return{playbackUrl:i.playbackUrl,status:i.status,manualIngest:i.manualIngest,ingestionCredentials:i.streamKey?{ingestionServer:i.ingestServer,streamKey:i.streamKey}:null}})}stopLivestreaming(){return p(this,null,function*(){return this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream/stop`)})}getActiveLivestream(){return p(this,null,function*(){const e=qn((yield this.requests.get(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream`)).data.data);return{playbackUrl:e.playbackUrl,status:e.status,manualIngest:e.manualIngest,ingestionCredentials:e.streamKey?{ingestionServer:e.ingestServer,streamKey:e.streamKey}:null}})}getUserDetails(){return p(this,null,function*(){if(this.userDetails)return this.userDetails;const e=(yield this.requests.get("v2/internals/participant-details")).data.data;return qn(e)})}startRecording(e,n){return p(this,null,function*(){return(yield this.requests.post("/v2/recordings",ee(H({},f0(e)),{meeting_id:this.context.getValue("meetingId"),allow_multiple_recordings:!!n}))).data.data.id})}updateRecording(e,n){return p(this,null,function*(){return this.requests.put(`v2/recordings/${e}`,{action:n})})}getActiveRecording(){return p(this,null,function*(){const{status:e,id:n}=(yield this.requests.get(`v2/recordings/active-recording/${this.context.getValue("meetingId")}`)).data.data;return{status:e,id:n}})}getActiveTranscript(){return p(this,null,function*(){const{transcript_download_url:e}=(yield this.requests.get(`v2/meetings/${this.context.getValue("meetingId")}/active-transcript`)).data.data;try{return{transcript:(yield this.fetchClient.get(e)).data}}catch(n){throw new O("Cant fetch transcript s3 url","1801")}})}getRoomNodeData(){return p(this,null,function*(){const e=yield this.getIPDetails();if(this.ipInfo=e,this.roomDetails)return this.roomDetails;const{roomNodeLink:n,title:i,useHiveMedia:s,sfu:r}=qn((yield this.requests.post("v2/internals/rooms",{ip_information:e})).data.data);return{roomNodeUrl:n,meetingTitle:i,useHiveMedia:s!=null?s:!1,sfu:r}})}}Cn([k.trace("APIClient.getIPDetails")],gn.prototype,"getIPDetails",1);Cn([k.trace("APIClient.getICEServers")],gn.prototype,"getICEServers",1);Cn([k.trace("APIClient.getPlugins")],gn.prototype,"getPlugins",1);Cn([k.trace("APIClient.startLivestreaming")],gn.prototype,"startLivestreaming",1);Cn([k.trace("APIClient.stopLivestreaming")],gn.prototype,"stopLivestreaming",1);Cn([k.trace("APIClient.getActiveLivestream")],gn.prototype,"getActiveLivestream",1);Cn([k.trace("APIClient.getUserDetails")],gn.prototype,"getUserDetails",1);Cn([k.trace("APIClient.startRecording")],gn.prototype,"startRecording",1);Cn([k.trace("APIClient.stopRecording")],gn.prototype,"updateRecording",1);Cn([k.trace("APIClient.getActiveRecording")],gn.prototype,"getActiveRecording",1);Cn([k.trace("APIClient.getActiveTranscript")],gn.prototype,"getActiveTranscript",1);Cn([k.trace("APIClient.getRoomNodeData")],gn.prototype,"getRoomNodeData",1);let Mh;function MN(t,e){return Mh=new gn(t,e),Mh}function Pt(){return Mh}function ON(t,e){return`<blockquote>${e.replace(/<blockquote>[.\s\S]*<\/blockquote>\n\n/m,"")}</blockquote>
21
+ ${t}`}const Pa={maxInvocations:5,period:1};function an(t,e){return function(n,i,s){const r=s.value;let a=0,c=Date.now();return s.value=function(...d){const h=Date.now(),u=e?this[e]:t;if(h-c>u.period*1e3&&(c=h,a=0),a>=u.maxInvocations)throw new O(`Method rate limit ${u.maxInvocations} invocations/${u.period}sec exceeded`,"0013");return a+=1,r.apply(this,d)},s}}var DN=Object.defineProperty,NN=Object.getOwnPropertyDescriptor,xt=(t,e,n,i)=>{for(var s=i>1?void 0:i?NN(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&DN(e,n,s),s};const LN=["text","image","file","custom","poll"],gd={maxInvocations:180,period:60};var he,Mr,pt,Or,Fc,Mu,yg,jc,Ou,Eg;let kt=(Eg=class extends fn{constructor(t,e,n,i,s){super(),S(this,Mu),S(this,jc),y(this,"messages"),y(this,"channels",[]),S(this,he,void 0),S(this,Mr,void 0),S(this,pt,void 0),S(this,Or,void 0),S(this,Fc,void 0),y(this,"maxTextLimit",2e3),T(this,Fc,t),T(this,pt,e),T(this,Or,n),T(this,he,i),T(this,Mr,s),this.messages=[]}setMaxTextLimit(t){this.maxTextLimit=t}sendMessageInternal(t,e,n){return p(this,arguments,function*(i,s,r,a={}){switch(i.type){case"text":{const c=a.replyTo&&a.replyTo.type==="text"?ON(i.message,a.replyTo.message):i.message;yield this.sendTextMessageInternal(c,s,r);break}case"image":yield this.sendImageMessageInternal(i.image,s,r);break;case"file":yield this.sendFileMessageInternal(i.file,s,r);break;default:m.error("sendMessage::message_type_not_supported",{dyteChat:{messageType:i.type}});break}})}sendTextMessageInternal(t,e,n){return p(this,null,function*(){var i,s,r,a,c,d;if(t.length>this.maxTextLimit)throw new O("Max character limit breached","0503");if(e&&e.length>0){if(!((i=o(this,he).permissions)!=null&&i.chatPrivate.canSend)||!((s=o(this,he).permissions)!=null&&s.chatPrivate.text))throw m.error("sendTextMessage::private_chat_permission_denied"),new O("Could not send message to private chat.","0501")}else if(!((a=(r=o(this,he).permissions)==null?void 0:r.chatPublic)!=null&&a.canSend)||!((d=(c=o(this,he).permissions)==null?void 0:c.chatPublic)!=null&&d.text))throw m.error("sendTextMessage::public_chat_permission_denied"),new O("Could not send message to public chat.","0501");if(!t)throw m.error("sendTextMessage::message_can_not_be_empty"),new O("Message can not be empty.","0502");if(n){o(this,pt).sendMessageToChannel(t,$t.TEXT,n);return}let h=[];e&&e.length>0&&(e.push(o(this,he).id),h=o(this,Mr).joined.toArray().filter(u=>e.includes(u.id)).map(u=>u.userId),h.push(o(this,he).userId)),o(this,pt).sendMessage(t,$t.TEXT,e)})}sendImageMessageInternal(t,e,n){return p(this,null,function*(){var i,s,r,a,c,d;if(e&&e.length>0){if(!((i=o(this,he).permissions)!=null&&i.chatPrivate.canSend)||!((s=o(this,he).permissions)!=null&&s.chatPrivate.files)){m.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((a=(r=o(this,he).permissions)==null?void 0:r.chatPublic)!=null&&a.canSend)||!((d=(c=o(this,he).permissions)==null?void 0:c.chatPublic)!=null&&d.files)){m.error("sendImageMessage::permission_denied");return}if(!t){m.error("sendImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(t.type)){m.error("sendImageMessage::image_type_not_supported",{dyteChat:{imageType:t.type}});return}try{const h=Pt(),{getLocation:u,putLocation:g}=yield h.getPresignedUrls(t.name,o(this,he).config.viewType);if(yield h.uploadFile(t,g),n){o(this,pt).sendMessageToChannel(u,$t.IMAGE,n);return}let E=[];e&&e.length>0&&(e.push(o(this,he).id),E=o(this,Mr).joined.toArray().filter(b=>e.includes(b.id)).map(b=>b.userId),E.push(o(this,he).userId)),o(this,pt).sendMessage(u,$t.IMAGE,e)}catch(h){throw new O("Error sending image message.","0500")}})}sendFileMessageInternal(t,e,n){return p(this,null,function*(){var i,s,r,a,c,d;if(e&&e.length>0){if(!((i=o(this,he).permissions)!=null&&i.chatPrivate.canSend)||!((s=o(this,he).permissions)!=null&&s.chatPrivate.files)){m.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((a=(r=o(this,he).permissions)==null?void 0:r.chatPublic)!=null&&a.canSend)||!((d=(c=o(this,he).permissions)==null?void 0:c.chatPublic)!=null&&d.files)){m.error("sendFileMessage::permission_denied");return}if(!t){m.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const h=Pt(),{getLocation:u,putLocation:g}=yield h.getPresignedUrls(t.name,o(this,he).config.viewType);if(yield h.uploadFile(t,g),n){o(this,pt).sendMessageToChannel(JSON.stringify({link:u,name:t.name,size:"size"in t?t.size:0}),$t.FILE,n);return}let E=[];e&&e.length>0&&(e.push(o(this,he).id),E=o(this,Mr).joined.toArray().filter(w=>e.includes(w.id)).map(w=>w.userId),E.push(o(this,he).userId));const b=JSON.stringify({link:u,name:t.name,size:"size"in t?t.size:0});o(this,pt).sendMessage(b,$t.FILE,e)}catch(h){throw new O("Error sending file message.","0500")}})}get rateLimits(){return gd}updateRateLimits(t,e){gd.maxInvocations=t,gd.period=e}sendTextMessage(t,e){return p(this,null,function*(){return this.sendTextMessageInternal(t,e)})}sendCustomMessage(t,e){return p(this,null,function*(){var n,i,s,r,a,c,d,h,u,g,E,b,w,M,D;if(e&&e.length>0){if(!((n=o(this,he).permissions)!=null&&n.chatPrivate.canSend)||!((i=o(this,he).permissions)!=null&&i.chatPrivate.files)||!((s=o(this,he).permissions)!=null&&s.chatPrivate.text)){m.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((a=(r=o(this,he).permissions)==null?void 0:r.chatPublic)!=null&&a.canSend)||!((d=(c=o(this,he).permissions)==null?void 0:c.chatPublic)!=null&&d.files)||!((u=(h=o(this,he).permissions)==null?void 0:h.chatPublic)!=null&&u.text)){m.error("sendCustomMessage::permission_denied");return}const F=X=>p(this,null,function*(){try{if(typeof X=="string")return{link:X};const A=Pt(),{getLocation:$,putLocation:me}=yield A.getPresignedUrls(X.name,o(this,he).config.viewType);return yield A.uploadFile(X,me),{link:$,type:X.type,name:X.name,size:X.size}}catch(A){throw new O("Error sending image message.","0500")}}),Y=ee(H({},t),{files:yield Promise.all((E=(g=t.files)!=null?g:[])==null?void 0:E.map(X=>p(this,null,function*(){return F(X)}))),images:yield Promise.all((w=(b=t.images)!=null?b:[])==null?void 0:w.map(X=>p(this,null,function*(){return F(X)}))),videos:yield Promise.all((D=(M=t.videos)!=null?M:[])==null?void 0:D.map(X=>p(this,null,function*(){return F(X)})))});o(this,pt).sendMessage(JSON.stringify(Y),$t.CUSTOM,e)})}sendImageMessage(t,e){return p(this,null,function*(){return this.sendImageMessageInternal(t,e)})}sendFileMessage(t,e){return p(this,null,function*(){return this.sendFileMessageInternal(t,e)})}sendMessage(t,e){return p(this,null,function*(){return this.sendMessageInternal(t,e)})}editTextMessage(t,e,n){return p(this,null,function*(){var i,s,r,a,c,d;if(((s=(i=o(this,he).permissions)==null?void 0:i.chatMessage)==null?void 0:s.canEdit)==="NONE")throw new O("Not permitted to edit messages","0501");if(!((a=(r=o(this,he).permissions)==null?void 0:r.chatPublic)!=null&&a.canSend)||!((d=(c=o(this,he).permissions)==null?void 0:c.chatPublic)!=null&&d.text)){m.error("editTextMessage::permission_denied");return}if(!e){m.error("editTextMessage::message_can_not_be_empty");return}o(this,pt).editMessage(t,e,$t.TEXT,n)})}editImageMessage(t,e,n){return p(this,null,function*(){var i,s,r,a;if(!((s=(i=o(this,he).permissions)==null?void 0:i.chatPublic)!=null&&s.canSend)||!((a=(r=o(this,he).permissions)==null?void 0:r.chatPublic)!=null&&a.files)){m.error("editImageMessage::permission_denied");return}if(!e){m.error("editImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(e.type)){m.error("sendImageMessage::image_type_not_supported",{dyteChat:{imageType:e.type}});return}try{const c=Pt(),{getLocation:d,putLocation:h}=yield c.getPresignedUrls(e.name,o(this,he).config.viewType);yield c.uploadFile(e,h),o(this,pt).editMessage(t,d,$t.IMAGE,n)}catch(c){throw new O("Error editing image message.","0500")}})}editFileMessage(t,e,n){return p(this,null,function*(){var i,s,r,a;if(!((s=(i=o(this,he).permissions)==null?void 0:i.chatPublic)!=null&&s.canSend)||!((a=(r=o(this,he).permissions)==null?void 0:r.chatPublic)!=null&&a.files)){m.error("sendFileMessage::permission_denied");return}if(!e){m.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const c=Pt(),{getLocation:d,putLocation:h}=yield c.getPresignedUrls(e.name,o(this,he).config.viewType);yield c.uploadFile(e,h),o(this,pt).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),$t.FILE,n)}catch(c){throw new O("Error editing file message.","0500")}})}editMessage(t,e,n){return p(this,null,function*(){switch(e.type){case"text":{this.editTextMessage(t,e.message,n);break}case"image":{this.editImageMessage(t,e.image,n);break}case"file":{this.editFileMessage(t,e.file,n);break}default:{m.error("editMessage::message_type_not_supported",{dyteChat:{messageType:e.type}});break}}})}deleteMessage(t,e){return p(this,null,function*(){var n,i;if(((i=(n=o(this,he).permissions)==null?void 0:n.chatMessage)==null?void 0:i.canDelete)==="NONE")throw new O("Not permitted to delete messages","0501");o(this,pt).deleteMessage(t,e)})}getMessagesByUser(t){return this.messages.filter(e=>e.userId===t)}getMessagesByType(t){return this.messages.filter(e=>e.type===t)}pin(t){return p(this,null,function*(){if(!o(this,jc,Ou))throw new O("Can`t pin message without joining room","0505");if(!o(this,he).permissions.pinParticipant)throw new O("You do not have permission to pin messages.","0501");const e=this.messages.find(n=>n.id===t);if(e){o(this,pt).setPinState(e,!0);return}throw new O(`No message found with id: ${t}`,"0504")})}unpin(t){return p(this,null,function*(){if(!o(this,jc,Ou))throw new O("Can`t unpin message without joining room","0505");if(!o(this,he).permissions.pinParticipant)throw new O("You do not have permission to unpin messages.","0501");const e=this.messages.find(n=>n.id===t);if(e){o(this,pt).setPinState(e,!1);return}throw new O(`No message found with id: ${t}`,"0504")})}getMessages(t,e,n,i=0,s=void 0){return p(this,null,function*(){const r=yield o(this,pt).getChatMessagesPaginated(t,e,n,i,s);return{messages:r.messages.map(a=>Ii.formatSocketServiceMessage(a)),next:r.next}})}createChannel(t,e){return p(this,arguments,function*(n,i,s={}){var r;const a=(r=o(this,he).permissions)==null?void 0:r.chatChannel;if(a){if(a.canCreate==="NONE")throw new O("Not permitted to create channels","0501");if(s.visibility==="public"&&!(a.canCreate==="PUBLIC"||a.canCreate==="ALL"))throw new O("Not permitted to create public channels","0501");if(s.visibility==="private"&&!(a.canCreate==="PRIVATE"||a.canCreate==="ALL"))throw new O("Not permitted to create private channels","0501")}if(!n||n.trim().length===0)throw new O("channel name cannot be empty.","0510");const c=[...new Set([...i,o(this,he).userId])];return yield o(this,Or).createChannel(n.trim(),c,s.displayPictureUrl,s.visibility,s.isDirectMessage)})}updateChannel(t,e){var n,i,s,r,a;const c=this.channels.find(u=>u.id===t),d=(n=o(this,he).permissions)==null?void 0:n.chatChannel;if(d){if(d.canUpdate==="NONE")throw new O("Not permitted to update channels","0501");if(c.visibility==="public"&&!(d.canUpdate==="PUBLIC"||d.canUpdate==="ALL"))throw new O("Not permitted to update public channels","0501");if(c.visibility==="private"&&!(d.canUpdate==="PRIVATE"||d.canUpdate==="ALL"))throw new O("Not permitted to update private channels","0501")}const h={memberIds:(i=e.memberIds)!=null?i:c.memberIds,displayName:(s=e.displayName)!=null?s:c.displayName,displayPictureUrl:(r=e.displayPictureUrl)!=null?r:c.displayPictureUrl,visibility:(a=e.visibility)!=null?a:c.visibility};return o(this,Or).updateChannel(t,h)}sendMessageToChannel(t,e){return p(this,arguments,function*(n,i,s={}){return this.sendMessageInternal(n,null,i,s)})}getChannelMembers(t){return p(this,null,function*(){return o(this,Or).getChannelMembers(t)})}searchMessages(t){return p(this,arguments,function*(e,n={}){if(!re.hasFeature(ue.FEAT_CHAT_SDK_SEARCH))throw new O("searchMessages is temporarily disabled!","0506");return(yield o(this,pt).searchMessages(e,n)).map(Ii.formatSocketServiceMessage)})}markLastReadMessage(t,e){return p(this,null,function*(){yield o(this,pt).markLastReadMessage(t,e);const n=this.channels.find(i=>i.id===t);if(n){const i=ee(H({},n),{unreadCount:0});this.channels=this.channels.map(s=>s.id===t?i:s),this.emit("channelMessageUpdate",i)}})}get pinned(){return this.messages.filter(t=>t.pinned)}},he=new WeakMap,Mr=new WeakMap,pt=new WeakMap,Or=new WeakMap,Fc=new WeakMap,Mu=new WeakSet,yg=function(){return o(this,Fc).getValue("connectionHandler")},jc=new WeakSet,Ou=function(){return o(this,Mu,yg).socketJoined===!0},Eg);xt([k.trace("DyteChat.sendTextMessage"),an(gd)],kt.prototype,"sendTextMessage",1);xt([k.trace("DyteChat.sendImageMessage"),an({maxInvocations:20,period:60})],kt.prototype,"sendImageMessage",1);xt([k.trace("DyteChat.sendFileMessage"),an({maxInvocations:20,period:60})],kt.prototype,"sendFileMessage",1);xt([k.trace("DyteChat.sendMessage"),an({maxInvocations:180,period:60})],kt.prototype,"sendMessage",1);xt([k.trace("DyteChat.editTextMessage")],kt.prototype,"editTextMessage",1);xt([k.trace("DyteChat.editImageMessage")],kt.prototype,"editImageMessage",1);xt([k.trace("DyteChat.editFileMessage")],kt.prototype,"editFileMessage",1);xt([k.trace("DyteChat.editMessage")],kt.prototype,"editMessage",1);xt([k.trace("DyteChat.deleteMessage")],kt.prototype,"deleteMessage",1);xt([k.trace("DyteChat.createChannel")],kt.prototype,"createChannel",1);xt([k.trace("DyteChat.updateChannel")],kt.prototype,"updateChannel",1);xt([k.trace("DyteChat.sendMessageToChannel")],kt.prototype,"sendMessageToChannel",1);xt([k.trace("DyteChat.getChannelMembers")],kt.prototype,"getChannelMembers",1);xt([k.trace("DyteChat.searchMessages")],kt.prototype,"searchMessages",1);xt([k.trace("DyteChat.markLastReadMessage")],kt.prototype,"markLastReadMessage",1);kt=xt([Lt("0500")],kt);var xN=Object.defineProperty,VN=Object.getOwnPropertyDescriptor,UN=(t,e,n,i)=>{for(var s=i>1?void 0:i?VN(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&xN(e,n,s),s},Du,Sg;const js=(Sg=class{constructor(t,e,n,i,s){y(this,"chat"),y(this,"chatSocketHandler"),y(this,"chatChannelSocketHandler"),y(this,"self"),S(this,Du,void 0),T(this,Du,t),this.chatSocketHandler=e,this.chatChannelSocketHandler=n,this.chat=new kt(t,e,n,i,s),this.self=i,this.setupEvents()}static init(t,e,n,i,s){return p(this,null,function*(){return new js(t,e,n,i,s)})}static formatMessage(t){return ee(H({},t),{time:new Date(t.time),type:LN[t.type]})}static formatSocketServiceMessage(t){const e=t.createdAt*1e3,n={displayName:t.displayName,id:t.chatId,time:e,timeMs:t.createdAtMs,type:t.payloadType,isEdited:t.isEdited,userId:t.userId,targetUserIds:t.targetUserIds,channelId:t.channelId,channelIndex:t.channelIndex,message:"",link:"",name:"",html:"",images:[],videos:[],files:[],size:0,pinned:t.pinned};switch(n.type){case $t.TEXT:{n.message=t.payload;break}case $t.IMAGE:{n.link=t.payload;break}case $t.FILE:{const{link:i,name:s,size:r}=JSON.parse(t.payload);n.link=i,n.name=s,n.size=r;break}case $t.CUSTOM:{const{html:i,images:s,message:r,videos:a,files:c}=JSON.parse(t.payload);n.message=r,n.html=i,n.images=s,n.videos=a,n.files=c;break}}return js.formatMessage(n)}getChatMessages(){return p(this,null,function*(){if(this.self.config.viewType==="LIVESTREAM"||this.self.config.viewType==="CHAT"||re.hasFeature(ue.FEAT_PAGINATED_CHAT))return;const t=yield this.chatSocketHandler.getChatMessages();if(!(t!=null&&t.payload))return;const e=u0.fromBinary(t.payload).messages;this.chat.messages=e.map(n=>js.formatSocketServiceMessage(n))})}setupEvents(){L.on(x.SOCKET_SERVICE_ROOM_JOINED,()=>p(this,null,function*(){this.getChatMessages()})),this.chatSocketHandler.on(Ge.sendMessageToRoom,t=>{const e=js.formatSocketServiceMessage(t.message);if(!e.channelId)this.chat.messages=[...this.chat.messages,e];else{const n=this.chat.channels.find(i=>i.id===e.channelId);n&&(n.latestMessage=e,n.unreadCount+=1,this.chat.emit("channelMessageUpdate",n))}this.chat.emit("chatUpdate",{action:"add",message:e,messages:this.chat.messages})}),this.chatSocketHandler.on(Ge.sendMessageToPeers,t=>{const e=js.formatSocketServiceMessage(t.message);this.chat.messages=[...this.chat.messages,e],this.chat.emit("chatUpdate",{action:"add",message:e,messages:this.chat.messages})}),this.chatSocketHandler.on(Ge.editMessage,t=>{const e=js.formatSocketServiceMessage(t.message);if(e.channelId){this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages});return}const n=this.chat.messages.findIndex(i=>i.id===e.id);n!==-1&&(this.chat.messages[n]=e,this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages}))}),this.chatSocketHandler.on(Ge.deleteMessage,t=>{if(t.channelId){this.chat.emit("chatUpdate",{action:"delete",message:{id:t.chatId,channelId:t.channelId},messages:this.chat.messages});return}const e=this.chat.messages.findIndex(i=>i.id===t.chatId);if(e===-1)return;const[n]=this.chat.messages.splice(e,1);this.chat.emit("chatUpdate",{action:"delete",message:n,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(sr.createChatChannel,t=>{const[e]=t.chatChannels,n=yr.formatChannel(e);this.chat.channels.push(n),this.chat.emit("channelCreate",n)}),this.chatSocketHandler.on(Ge.pinMessage,t=>{const e=this.chat.messages.findIndex(i=>i.id===t.chatId);if(e===-1)return;const n=this.chat.messages[e];n.pinned=t.pinned,this.chat.messages[e]=n,this.chat.emit("chatUpdate",{action:"edit",message:n,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(sr.updateChatChannel,t=>{const[e]=t.chatChannels,n=yr.formatChannel(e);this.chat.channels=this.chat.channels.map(i=>i.id===n.id?n:i),this.chat.emit("channelUpdate",n)})}},Du=new WeakMap,Sg);let Ii=js;UN([k.trace("ChatController.setupEvents")],Ii.prototype,"setupEvents",1);var BN=Object.defineProperty,FN=Object.getOwnPropertyDescriptor,jN=(t,e,n,i)=>{for(var s=i>1?void 0:i?FN(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&BN(e,n,s),s},Nu,Tg,Lu,bg,Va,Ua,Wc,kg;let Oh=(kg=class extends fn{constructor(t,e,n){super(),S(this,Nu),S(this,Lu),y(this,"items"),S(this,Va,void 0),S(this,Ua,void 0),S(this,Wc,void 0),T(this,Wc,t),T(this,Va,e),T(this,Ua,n),this.items=[]}create(t,e,n=!1,i=!1){return p(this,null,function*(){if(!o(this,Lu,bg))throw new O("Can't create polls without joining room","0705");if(!o(this,Va).permissions.polls.canCreate){m.error("DytePolls::create::permission_denied");return}if(!t||!e){m.error("DytePolls::question_and_options_can_not_be_empty",{dytePolls:{hasQuestion:!!t,optionsLength:e==null?void 0:e.length}});return}if(e.length<2){m.error("DytePolls::there_must_be_at_least_two_options",{dytePolls:{hasQuestion:!!t,optionsLength:e.length}});return}yield o(this,Ua).createPoll(t,e,n,i)})}vote(t,e){return p(this,null,function*(){if(!o(this,Va).permissions.polls.canVote){m.error("DytePolls::vote::permission_denied");return}yield o(this,Ua).votePoll(t,e)})}},Nu=new WeakSet,Tg=function(){return o(this,Wc).getValue("connectionHandler")},Lu=new WeakSet,bg=function(){var t;return((t=o(this,Nu,Tg))==null?void 0:t.socketJoined)===!0},Va=new WeakMap,Ua=new WeakMap,Wc=new WeakMap,kg);Oh=jN([Lt("0700")],Oh);var WN=Object.defineProperty,HN=Object.getOwnPropertyDescriptor,qN=(t,e,n,i)=>{for(var s=i>1?void 0:i?HN(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&WN(e,n,s),s},Ba,Dr,wg;const Gr=(wg=class{constructor(t,e,n){y(this,"polls"),S(this,Ba,void 0),S(this,Dr,void 0),this.polls=new Oh(t,e,n),T(this,Ba,e),T(this,Dr,n),this.setupEvents()}static init(t,e,n){return p(this,null,function*(){return new Gr(t,e,n)})}canViewPolls(){return o(this,Ba).permissions.polls.canView}setupEvents(){const t={[Ei.createPoll]:i=>{i.poll&&this.updatePoll(Gr.formatSocketServicePoll(i.poll))},[Ei.updatePoll]:i=>{i.poll&&this.updatePoll(Gr.formatSocketServicePoll(i.poll))},[Ei.votePoll]:i=>{i.poll&&this.updatePoll(Gr.formatSocketServicePoll(i.poll))}},e=()=>{L.on(x.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(t).map(Number).forEach(i=>{o(this,Dr).on(i,t[i])})},n=()=>{L.on(x.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(t).map(Number).forEach(i=>{o(this,Dr).removeListeners(i)})};o(this,Ba).permissions.on("permissionsUpdate",i=>p(this,null,function*(){var s;(s=i==null?void 0:i.polls)!=null&&s.canView?(yield this.getPolls(),e()):(this.polls.items=[],n())})),this.canViewPolls()&&e()}updatePoll(t){if(!this.canViewPolls())return;const e=this.polls.items.findIndex(n=>n.id===t.id);if(e>-1){const n=JSON.stringify(this.polls.items[e]);this.polls.items[e]=t,n!==JSON.stringify(t)&&this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!1});return}this.polls.items=[...this.polls.items,t],this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!0})}getPolls(){return p(this,null,function*(){const t=yield o(this,Dr).getPolls();if(!(t!=null&&t.payload))return;const{polls:e}=tN.fromBinary(t.payload);this.polls.items=e.map(n=>Gr.formatSocketServicePoll(n))})}static formatSocketServicePoll(t){const e=t.options.map(n=>({count:n.count,text:n.text,votes:n.votes.map(i=>({id:i.userId,name:i.name}))}));return{anonymous:t.anonymous,createdBy:t.createdBy,createdByUserId:t.createdByUserId,hideVotes:t.hideVotes,id:t.pollId,options:e,question:t.question,voted:t.votes}}},Ba=new WeakMap,Dr=new WeakMap,wg);let g0=Gr;qN([k.trace("PollController.setupEvents")],g0.prototype,"setupEvents",1);var GN=Object.defineProperty,$N=Object.getOwnPropertyDescriptor,JN=(t,e,n,i)=>{for(var s=i>1?void 0:i?$N(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&GN(e,n,s),s},v0=(t=>(t[t.User=0]="User",t[t.Meeting=1]="Meeting",t))(v0||{}),Fa,Hc,xu,Nr,qc,_g;let Dh=(_g=class extends fn{constructor(t,e,n,i,s){super(),S(this,Hc),y(this,"selfActiveTab"),y(this,"broadcastTabChanges"),S(this,Fa,void 0),S(this,Nr,void 0),S(this,qc,void 0),y(this,"viewType"),y(this,"meetingStartedTimestamp"),y(this,"meetingTitle"),y(this,"sessionId"),T(this,Fa,t),T(this,Nr,e),this.viewType=n,T(this,qc,i),this.meetingTitle=s,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return o(this,Hc,xu).socketState}get mediaState(){return o(this,Hc,xu).mediaState}get meetingId(){return o(this,Fa).getValue("meetingId")}setBroadcastTabChanges(t){if(!o(this,Nr).permissions.canSpotlight)throw m.error("DyteSpotlight::setSpotlighted::permission_denied"),new O("User does not have permission to toggle spotlight","0801");this.broadcastTabChanges=t,this.emit("broadcastTabChangesUpdate",this.broadcastTabChanges),this.broadcastTabChanges&&this.assertActiveTabToRoom()}setSelfActiveTab(t,e){var n;m.info("DyteSpotlight::setActiveTab",{spotlight:{currentTab:{id:t.id,type:t.type}}}),this.selfActiveTab=t,e===0&&this.emit("selfTabUpdate",t),(n=o(this,Nr).permissions)!=null&&n.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){o(this,qc).broadcastMessage("spotlight",{userId:o(this,Nr).userId,currentTab:this.selfActiveTab})}},Fa=new WeakMap,Hc=new WeakSet,xu=function(){return o(this,Fa).getValue("connectionHandler")},Nr=new WeakMap,qc=new WeakMap,_g);Dh=JN([Lt("0800")],Dh);function KN(t){let e="",n=[""];const i=[n];let s=0,r=0,a=!0,c;for(c of t)c==='"'?(a&&c===e&&(n[s]+=c),a=!a):c===","&&a?c=n[++s]="":c===`
22
+ `&&a?(e==="\r"&&(n[s]=n[s].slice(0,-1)),n=i[++r]=[c=""],s=0):n[s]+=c,e=c;return i}var zN=Object.defineProperty,YN=Object.getOwnPropertyDescriptor,y0=(t,e,n,i)=>{for(var s=i>1?void 0:i?YN(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&zN(e,n,s),s};let Ss=class extends fn{constructor(){super(),y(this,"transcripts"),this.transcripts=[]}static init(t){return p(this,null,function*(){const e=new Ss;try{t&&e.getActiveTranscript()}catch(n){m.error("Error fetching active transcriptions ",n)}return e})}static parseTranscript(t,e=!1){try{if(!t)return;const[[n,i,s,r,a,c]]=KN(t);return{id:Ia(),name:a,peerId:i,userId:s,customParticipantId:r,transcript:c,isPartialTranscript:e,date:new Date(parseInt(n,10)*1e3)}}catch(n){m.error(`Failed to parse transcript: ${t}`,n);return}}static parseTranscripts(t){return t?t.split(`
23
+ `).map(e=>Ss.parseTranscript(e,!1)).filter(Boolean):[]}getActiveTranscript(){return p(this,null,function*(){try{const t=Pt(),{transcript:e}=yield t.getActiveTranscript();this.transcripts=Ss.parseTranscripts(e)}catch(t){}})}onTranscript(t){return p(this,null,function*(){var e;const n=this.transcripts.filter(({peerId:i})=>i===t.peerId);if((e=n==null?void 0:n.at(-1))!=null&&e.isPartialTranscript){const i=n.at(-1);i.transcript=t.transcript,i.isPartialTranscript=t.isPartialTranscript,this.emit("transcript",i);return}this.transcripts=[...this.transcripts,t],this.emit("transcript",t)})}};y0([k.trace("DyteAi.getActiveTranscript")],Ss.prototype,"getActiveTranscript",1);Ss=y0([Lt("0000")],Ss);var QN=Object.defineProperty,XN=Object.getOwnPropertyDescriptor,ZN=(t,e,n,i)=>{for(var s=i>1?void 0:i?XN(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&QN(e,n,s),s},Ns,ja,Vu,Ig;const E0=(Ig=class{constructor(t,e,n,i,s,r){y(this,"meta"),y(this,"ai"),S(this,Ns,void 0),S(this,ja,void 0),y(this,"aiSocketHandler"),S(this,Vu,void 0),T(this,Vu,t),this.meta=new Dh(t,e,e.config.viewType,n,r),this.ai=i,T(this,Ns,e),T(this,ja,n),this.aiSocketHandler=s,e.config.viewType!==zt.Chat&&this.setupEvents()}static init(t,e,n,i,s){return p(this,null,function*(){const r=yield Ss.init(e.permissions.transcriptionEnabled);return new E0(t,e,n,r,i,s)})}conditionallySetActiveTab(t){var e;t!=null&&t.currentTab&&((e=this.meta.selfActiveTab)==null?void 0:e.id)!==t.currentTab.id&&(this.meta.setSelfActiveTab(t.currentTab,v0.Meeting),this.meta.emit("activeTabUpdate",t.currentTab))}setupEvents(){L.on(x.TRANSPORT_STATE_UPDATE,t=>{this.meta.emit("mediaConnectionUpdate",t)}),L.on(x.SOCKET_STATE_UPDATE,t=>{this.meta.emit("socketConnectionUpdate",t)}),L.on(x.ROOM_STATE,({createdAt:t,roomUuid:e})=>{const n=this.meta.meetingStartedTimestamp;if(e&&(this.meta.sessionId=e),t&&!n){const i=new Date(t*1e3);this.meta.meetingStartedTimestamp=i,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),L.on(x.PRODUCER_SCORE_UPDATE,({score:t})=>{t<5&&this.meta.emit("poorConnection",{score:t})}),o(this,Ns).permissions.canSpotlight&&(m.info("DyteMetaController::Asserting Spotlight"),this.meta.selfActiveTab&&o(this,ja).broadcastMessage("spotlight",{userId:o(this,Ns).userId,currentTab:this.meta.selfActiveTab})),L.on(x.PEER_JOINED_INTERNAL,t=>p(this,null,function*(){o(this,Ns).permissions.canSpotlight&&this.meta.selfActiveTab&&o(this,ja).broadcastToPeers("spotlight",[t.id],{userId:o(this,Ns).userId,currentTab:this.meta.selfActiveTab})})),L.on(x.ROOM_MESSAGE,t=>{var e,n;let i;if("type"in t){if(t.type!=="spotlight")return;i=H(H({},t),t.payload)}else if("roomMessageType"in t){if(t.roomMessageType!=="spotlight")return;i=t}else return;m.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:i.userId},currentTab:{id:(e=i.currentTab)==null?void 0:e.id,type:(n=i.currentTab)==null?void 0:n.type}}}),this.conditionallySetActiveTab(i)}),L.on(x.MESSAGE,t=>{var e,n;let i;if("type"in t){if(t.type!=="spotlight")return;i=H(H({},t),t.payload)}else if("roomMessageType"in t){if(t.roomMessageType!=="spotlight")return;i=t}else return;m.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:i.userId},currentTab:{id:(e=i.currentTab)==null?void 0:e.id,type:(n=i.currentTab)==null?void 0:n.type}}}),this.conditionallySetActiveTab(i)}),this.aiSocketHandler.on(z.transcript,t=>{const{meetingId:e,transcript:n,isPartial:i}=t,s=Ss.parseTranscript(n,i);if(!s){m.warn("Received empty transcript data");return}this.ai.onTranscript(s),this.meta.emit("transcript",s);const{peerId:r,name:a,transcript:c}=s;m.debug(`${e} Received transcript for peer ${r} - ${a}: ${c}`)})}},Ns=new WeakMap,ja=new WeakMap,Vu=new WeakMap,Ig);let S0=E0;ZN([k.trace("MetaController.setupEvents")],S0.prototype,"setupEvents",1);var eL=Object.defineProperty,tL=Object.getOwnPropertyDescriptor,Cr=(t,e,n,i)=>{for(var s=i>1?void 0:i?tL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&eL(e,n,s),s},Vn,go,be,vd,fi,si,yd,Nh,vo,Ed;class Is extends fn{constructor(e,n,i,s,r){super(),S(this,yd),S(this,vo),S(this,Vn,void 0),S(this,go,void 0),S(this,be,void 0),S(this,vd,void 0),S(this,fi,void 0),S(this,si,void 0),T(this,si,e),T(this,Vn,s),T(this,go,r),T(this,be,n),T(this,vd,i),T(this,fi,[]),this.setupEvents()}get status(){return o(this,si).getValue("stageStatus")}setupEvents(){const e={[x.GET_STAGE_REQUESTS]:s=>p(this,null,function*(){T(this,fi,s)}),[x.UPDATE_STAGE_REQUESTS]:s=>p(this,[s],function*({add:r}){const a=o(this,fi).length,{stageRequests:c}=this.getAccessRequests();(r||c.length>a)&&this.emit("newStageRequest",{count:c.length}),this.emit("stageAccessRequestUpdate",c)})},n=()=>{Object.entries(e).forEach(([s,r])=>{L.onAsync(s,r)})},i=()=>{Object.entries(e).forEach(([s,r])=>{L.removeListener(s,r)})};o(this,be).permissions.on("permissionsUpdate",s=>{const{canAcceptProductionRequests:r}=s;r!==void 0&&(o(this,be).permissions.acceptStageRequests?(n(),o(this,Vn).getStageRequests()):(i(),T(this,fi,[]),this.emit("stageAccessRequestUpdate",o(this,fi))))}),o(this,be).permissions.acceptStageRequests&&n()}getAccessRequests(){if(!o(this,be).permissions.stageEnabled)throw m.error("DyteStage::stage_disabled"),new O("Stage is disabled","2003");if(!o(this,be).permissions.acceptStageRequests)throw m.error("DyteStage::get_access_request::permission_denied"),new O("You do not have permission to perform this action","2001");const e=o(this,vd).joined.toArray().filter(n=>n.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(n=>({displayName:n.name,userId:n.userId,peerId:n.id}));return T(this,fi,e),{stageRequests:o(this,fi)}}requestAccess(){return p(this,null,function*(){if(!o(this,be).permissions.stageEnabled)throw m.error("DyteStage::stage_disabled"),new O("Stage is disabled","2003");if(this.status!=="OFF_STAGE")throw new O(`Unable to request access you are currently ${this.status}`,"2006");if(o(this,be).permissions.stageAccess===se.Allowed){Q(this,vo,Ed).call(this,"ACCEPTED_TO_JOIN_STAGE");return}o(this,Vn).requestAccess(),Q(this,vo,Ed).call(this,"REQUESTED_TO_JOIN_STAGE")})}cancelRequestAccess(){return p(this,null,function*(){if(!o(this,be).permissions.stageEnabled)throw m.error("DyteStage::stage_disabled"),new O("Stage is disabled","2003");o(this,Vn).cancelRequestAccess(),Q(this,vo,Ed).call(this,"OFF_STAGE")})}grantAccess(e){if(!o(this,be).roomJoined)throw new O("Can`t grant for participant without joining room");if(!o(this,be).permissions.stageEnabled)throw m.error("DyteStage::stage_disabled"),new O("Stage is disabled","2003");if(!o(this,be).permissions.acceptStageRequests)throw m.error("DyteStage::grant_access::permission_denied"),new O("You do not have permission to perform this action","2001");return o(this,Vn).grantAccess(e)}denyAccess(e){if(!o(this,be).roomJoined)throw new O("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!o(this,be).permissions.stageEnabled)throw m.error("DyteStage::stage_disabled"),new O("Stage is disabled","2003");if(!o(this,be).permissions.acceptStageRequests)throw m.error("DyteStage::deny_access::permission_denied"),new O("You do not have permission to perform this action","2001");return o(this,Vn).denyAccess(e)}join(){return p(this,null,function*(){const e=o(this,si).getValue("viewType");if(this.status==="ON_STAGE")throw new O("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||o(this,be).permissions.stageAccess===se.NotAllowed)throw new O(`Unable to join stage you are currently ${this.status}`,"2006");if(yield o(this,Vn).joinStage(),e===zt.Livestream){yield o(this,go).joinRoom(o(this,be));const{peers:n}=yield o(this,go).getStagePeers();L.emit(x.SOCKET_PEERS,n)}o(this,si).setValue("stageStatus","ON_STAGE"),o(this,be).audioEnabled&&o(this,yd,Nh).shareMic(o(this,be).audioTrack),o(this,be).videoEnabled&&o(this,yd,Nh).shareWebcam(o(this,be).videoTrack)})}leave(){return p(this,null,function*(){if(!o(this,be).permissions.stageEnabled)throw m.error("DyteStage::stage_disabled"),new O("Stage is disabled","2003");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new O(`Unable to leave stage you are currently ${this.status}`,"2006");o(this,be).setIsPinned(!1),yield o(this,Vn).leaveStage(o(this,be).userId),o(this,si).setValue("stageStatus","OFF_STAGE",!1),yield L.emitAsync(x.LEAVE_MEDIA_ROOM,"stageLeft"),o(this,si).notify("stageStatus")})}kick(e){return p(this,null,function*(){if(!o(this,be).roomJoined)throw new O("Can`t kick participant without joining room","2005");if(!o(this,be).permissions.stageEnabled)throw m.error("DyteStage::stage_disabled"),new O("Stage is disabled","2003");if(!o(this,be).permissions.acceptStageRequests)throw m.error("DyteStage::kick::permission_denied"),new O("You do not have permissions for kick","2001");return o(this,Vn).kick(e)})}}Vn=new WeakMap,go=new WeakMap,be=new WeakMap,vd=new WeakMap,fi=new WeakMap,si=new WeakMap,yd=new WeakSet,Nh=function(){return o(this,si).getValue("roomNodeClient")},vo=new WeakSet,Ed=function(t){return p(this,null,function*(){this.status!==t&&o(this,si).setValue("stageStatus",t)})};Cr([k.trace("DyteStage.getStageRequests")],Is.prototype,"getAccessRequests",1);Cr([k.trace("DyteStage.requestAccess")],Is.prototype,"requestAccess",1);Cr([k.trace("DyteStage.cancelRequestAccess")],Is.prototype,"cancelRequestAccess",1);Cr([k.trace("DyteStage.grantAccess")],Is.prototype,"grantAccess",1);Cr([k.trace("DyteStage.denyAccess")],Is.prototype,"denyAccess",1);Cr([k.trace("DyteStage.joinStage")],Is.prototype,"join",1);Cr([k.trace("DyteStage.leaveStage")],Is.prototype,"leave",1);function nL(t){return!(t.viewType==="LIVESTREAM"||t.viewType==="CHAT")}function sm(t){switch(t){case ki.UNSPECIFIED:return"OFF_STAGE";case ki.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case ki.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case ki.OFF_STAGE:return"OFF_STAGE";case ki.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var iL=Object.defineProperty,sL=Object.getOwnPropertyDescriptor,rL=(t,e,n,i)=>{for(var s=i>1?void 0:i?sL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&iL(e,n,s),s},Ws,$r,Hs,Sd,ns;class T0{constructor(e,n,i,s,r){y(this,"stage"),S(this,Ws,void 0),S(this,$r,void 0),S(this,Hs,void 0),S(this,Sd,0),S(this,ns,void 0),T(this,ns,e),this.stage=new Is(e,s,r,n,i),T(this,Hs,n),T(this,Ws,s),T(this,$r,r),this.setupEvents()}setupEvents(){o(this,ns).subscribe("stageStatus",e=>{this.stage.emit("stageStatusUpdate",e)}),o(this,Hs).on(z.grantStageAccess,()=>{o(this,Ws).permissions.stageAccess!==se.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),o(this,Hs).on(z.peerStageStatusUpdate,e=>{e!==void 0&&(e.peerId===o(this,Ws).id?this.selfStageStatusHandler(e):this.peerStageStatusHandler(e))}),o(this,Hs).on(z.denyStageAccess,()=>{o(this,Ws).permissions.stageAccess!==se.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),o(this,Hs).on(z.getStageRequests,e=>p(this,null,function*(){var n;if(o(this,Ws).permissions.stageAccess!==se.Allowed)return;const i=(n=e==null?void 0:e.stageRequests)!=null?n:[];yield L.emitAsync(x.GET_STAGE_REQUESTS,i),o(this,Sd)<i.length&&i.length>0&&this.stage.emit("newStageRequest",{count:i.length}),T(this,Sd,i.length),this.stage.emit("stageAccessRequestUpdate",i)}))}getCurrentStageRequests(){return o(this,$r).joined.toArray().filter(e=>e.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(e=>({displayName:e.name,userId:e.userId,peerId:e.id}))}setStageStatus(e){return p(this,null,function*(){this.stage.status!==e&&o(this,ns).setValue("stageStatus",e)})}selfStageStatusHandler(e){const n=sm(e.stageType),i=o(this,ns).getValue("stageStatus");if(i!==n)switch(e.stageType){case 1:o(this,ns).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(i);break;case 0:case 4:default:o(this,ns).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}peerStageStatusHandler(e){return p(this,null,function*(){const n=o(this,$r).joined.get(e.peerId),i=o(this,$r).viewMode==="ACTIVE_GRID";if(!n){m.warn("err::peerStageStatusUpdate: participant not found");return}switch(e.stageType){case 1:n.setStageStatus("ON_STAGE"),i&&L.emit(x.UPDATE_ACTIVE);break;case 2:n.setStageStatus("ACCEPTED_TO_JOIN_STAGE");break;case 3:n.setStageStatus("REQUESTED_TO_JOIN_STAGE");break;case 0:case 4:default:n.setStageStatus("OFF_STAGE"),i&&L.emit(x.UPDATE_ACTIVE);break}L.emit(x.UPDATE_PEER_STAGE_STATUS,{id:n.id,status:n.stageStatus})})}}Ws=new WeakMap,$r=new WeakMap,Hs=new WeakMap,Sd=new WeakMap,ns=new WeakMap;rL([k.trace("DyteStage.setupEvents")],T0.prototype,"setupEvents",1);var aL=Object.defineProperty,oL=Object.getOwnPropertyDescriptor,Gl=(t,e,n,i)=>{for(var s=i>1?void 0:i?oL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&aL(e,n,s),s};const Ye={getPeer:14,getPeers:15,chatMessage:16,getRoomName:17,getDisplayTitle:18,getPluginInitiator:19,customPluginEventToParent:20,peerJoined:22,peerLeft:23,sendData:24,stageStatusUpdate:25,peerStageStatusUpdate:26};var Ut,Sn,Wa,Ha,Hi,qa,Lr,Ga,Cg;let _a=(Cg=class extends Ca{constructor(t,{baseURL:e,createdAt:n,description:i,id:s,name:r,organizationId:a,picture:c,private:d,published:h,staggered:u,tags:g,type:E,updatedAt:b},w,M,D,F,Y){super(),S(this,Ut,void 0),y(this,"baseURL"),y(this,"createdAt"),y(this,"description"),y(this,"id"),y(this,"name"),S(this,Sn,void 0),S(this,Wa,void 0),S(this,Ha,void 0),y(this,"organizationId"),y(this,"picture"),y(this,"private"),y(this,"published"),y(this,"staggered"),y(this,"tags"),y(this,"type"),y(this,"updatedAt"),S(this,Hi,void 0),y(this,"config"),S(this,qa,void 0),y(this,"active"),y(this,"iframes"),y(this,"enabledBy"),S(this,Lr,void 0),S(this,Ga,void 0),T(this,Lr,t),this.baseURL=e,this.createdAt=new Date(n),this.description=i,this.id=s,this.name=r,T(this,Sn,M),this.organizationId=a,this.picture=c,this.private=d,this.published=h,this.staggered=u,this.tags=g,this.type=E,this.updatedAt=new Date(b),this.active=!1,this.iframes=new Map,T(this,Ut,w),T(this,Wa,D),T(this,Ha,F),this.enabledBy="",T(this,Ga,Y)}sendIframeEvent(t){this.iframes.size&&this.iframes.forEach(e=>{const{iframe:n}=e;n&&(navigator.isReactNative?n.postMessage(JSON.stringify(t)):n.contentWindow.postMessage(t,"*"))})}handleIframeMessage(t){return p(this,null,function*(){var e;if(!this.active)return;const n=t,{payload:i,uuid:s,type:r}=n;switch(r){case ie.customPluginEventToRoom:{o(this,Ut).customPluginEventToRoom(this.id,i,s);break}case ie.customPluginEventToPeers:{o(this,Ut).customPluginEventToPeers(this.id,i.peerIds,i,s);break}case ie.enablePluginForRoom:{o(this,Ut).enablePluginForRoom(this.id,s);break}case ie.enablePluginForPeers:{o(this,Ut).enablePluginForPeers(this.id,i.peerIds,s);break}case ie.disablePluginForRoom:{o(this,Ut).disablePluginForRoom(this.id,s);break}case ie.disablePluginForPeers:{o(this,Ut).disablePluginForPeers(this.id,i.peerIds,s);break}case ie.storeInsertKeys:{o(this,Ut).storeInsertKeys(this.id,i.store,i.insertKeys,s);break}case ie.storeGetKeys:{o(this,Ut).storeGetKeys(this.id,i.store,i.getKeys,s);break}case ie.storeDeleteKeys:{o(this,Ut).storeDeleteKeys(this.id,i.store,i.deleteKeys,s);break}case ie.storeDelete:{o(this,Ut).storeDelete(this.id,i.store,s);break}case Ye.chatMessage:{const{messagePayload:a,peerIds:c}=i;if(!o(this,Ha)){this.sendIframeEvent({type:Ye.chatMessage,uuid:n.uuid,payload:{error:"Chat is disabled for this room."}});return}try{yield o(this,Ha).sendMessage(a,c),this.sendIframeEvent({type:Ye.chatMessage,uuid:n.uuid,payload:{success:!0}})}catch(d){this.sendIframeEvent({type:Ye.chatMessage,uuid:n.uuid,payload:{error:d}})}break}case Ye.getPeer:{let a;const{peerId:c}=i,d=ee(H({},o(this,Sn)),{id:o(this,Sn).id,isRecorder:(e=o(this,Sn).permissions)==null?void 0:e.isRecorder,isHidden:o(this,Sn).permissions.hiddenParticipant,stageStatus:o(this,Sn).stageStatus});c?(a=o(this,Wa).joined.get(i.peerId),o(this,Sn).id===c&&(a=d)):a=d,this.sendIframeEvent({type:Ye.getPeer,payload:{peer:a&&ll(a)},uuid:n.uuid});break}case Ye.getPeers:{const a=o(this,Wa).joined.toArray().map(c=>ll(c));this.sendIframeEvent({type:Ye.getPeers,payload:{peers:a},uuid:n.uuid});break}case Ye.getPluginInitiator:{this.sendIframeEvent({type:Ye.getPluginInitiator,payload:{enabledBy:this.enabledBy},uuid:n.uuid});break}case Ye.getDisplayTitle:{this.sendIframeEvent({type:Ye.getDisplayTitle,payload:{displayTitle:o(this,Ga)},uuid:n.uuid});break}case Ye.getRoomName:{this.sendIframeEvent({type:Ye.getRoomName,payload:{roomName:o(this,Lr).getValue("meetingId")},uuid:n.uuid});break}case Ye.customPluginEventToParent:{this.emit(n.payload.eventName,n.payload.data);break}}})}sendData(t){this.active&&(m.info("DytePlugin::SendData",{plugin:{id:this.id,name:this.name,data:{eventName:t.eventName}}}),this.sendIframeEvent({type:Ye.sendData,uuid:"",payload:t}))}removePluginView(t="default"){var e;const{iframe:n,listener:i}=(e=this.iframes.get(t))!=null?e:{};(n||i)&&(navigator.isReactNative?n.props.onMessage=void 0:window.removeEventListener("message",i),this.iframes.delete(t))}addPluginView(t,e="default"){var n;if(!o(this,qa))throw m.error("DytePlugin::addPluginView::no_auth_token_set_for_plugin"),new O("No auth token set for plugin.","0602");if(!t)throw m.error("DytePlugin::addPluginView::iframe_was_not_provided"),new O("Iframe was not provided.","0603");this.removePluginView(e);const i=t,s=new URL(this.baseURL),r={auth:o(this,qa),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:o(this,Lr).getValue("apiBase"),pluginId:this.id,roomName:(n=o(this,Lr).getValue("meetingId"))!=null?n:"",displayTitle:o(this,Ga)};if(Object.keys(r).forEach(a=>{s.searchParams.set(a,r[a])}),i.src=s.href,i.allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",i.title=e,navigator.isReactNative)i.props.onMessage=a=>{this.handleIframeMessage(JSON.parse(a.nativeEvent.data))},this.iframes.set(e,{iframe:i});else{const a=c=>p(this,null,function*(){c.source===t.contentWindow&&(yield this.handleIframeMessage(c.data))});window.addEventListener("message",a),this.iframes.set(e,{iframe:i,listener:a})}}setActive(t){var e,n;if(this.active=t,t){this.emit("stateUpdate",{active:this.active,pluginId:this.id,bind:this.addPluginView.bind(this),views:(e=this.config)==null?void 0:e.views});return}this.active=!1,this.emit("stateUpdate",{active:this.active,pluginId:this.id,views:(n=this.config)==null?void 0:n.views})}activateForSelf(){return p(this,null,function*(){const t=Pt(),e=yield t.authorizePlugin(this.id);T(this,qa,e),T(this,Hi,new Date);try{const n=yield t.getPluginConfig(this.baseURL);this.config=n}catch(n){m.error("DytePlugin::activateForSelf",{error:n})}this.setActive(!0),this.emit("enabled")})}deactivateForSelf(){Array.from(this.iframes.keys()).forEach(t=>{this.removePluginView(t)}),T(this,Hi,void 0),this.iframes.clear(),this.setActive(!1),this.emit("closed")}enable(){return p(this,null,function*(){return this.activateForSelf()})}disable(){return this.deactivateForSelf()}activate(){return p(this,null,function*(){var t,e;this.active||(e=(t=o(this,Sn).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(o(this,Ut).addPlugin(this.id,this.staggered),T(this,Hi,new Date),m.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}}))})}deactivate(){return p(this,null,function*(){var t,e;this.active&&(!((e=(t=o(this,Sn).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==o(this,Sn).id||(o(this,Ut).removePlugin(this.id),m.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:o(this,Hi)?new Date().getTime()-o(this,Hi).getTime():0}}),T(this,Hi,void 0)))})}},Ut=new WeakMap,Sn=new WeakMap,Wa=new WeakMap,Ha=new WeakMap,Hi=new WeakMap,qa=new WeakMap,Lr=new WeakMap,Ga=new WeakMap,Cg);Gl([an({maxInvocations:5,period:1})],_a.prototype,"sendData",1);Gl([k.trace("DytePlugin.activatePlugin")],_a.prototype,"activate",1);Gl([k.trace("DytePlugin.deactivatePlugin")],_a.prototype,"deactivate",1);_a=Gl([Lt("0600")],_a);var lt,Jr;class b0 extends Map{constructor(e){const{onAddEvent:n,onDeleteEvent:i,onClearEvent:s}=e;super(),S(this,lt,void 0),S(this,Jr,void 0),y(this,"onAddEvent"),y(this,"onDeleteEvent"),y(this,"onClearEvent"),T(this,lt,new Ca),this.onAddEvent=n,this.onDeleteEvent=i,this.onClearEvent=s,T(this,Jr,new Map)}emit(e,...n){return o(this,lt).emit(e,...n)}on(e,n){return o(this,lt).on(e,n)}addListener(e,n){return o(this,lt).addListener(e,n)}off(e,n){return o(this,lt).off(e,n)}once(e,n){return o(this,lt).once(e,n)}prependListener(e,n){return o(this,lt).prependListener(e,n)}prependOnceListener(e,n){return o(this,lt).prependOnceListener(e,n)}removeListener(e,n){return o(this,lt).removeListener(e,n)}removeAllListeners(e){return o(this,lt).removeAllListeners(e)}listeners(e){return o(this,lt).listeners(e)}listenerCount(e){return o(this,lt).listenerCount(e)}getMaxListeners(){return o(this,lt).getMaxListeners()}setMaxListeners(e){return o(this,lt).setMaxListeners(e)}eventNames(){return o(this,lt).eventNames()}add(e,n=!0){return this.set(e.id,e,n)}set(e,n,i=!0){const s=super.set(e,n),r=(a,...c)=>{this.emit(a,n,...c)};return o(this,Jr).set(e,r),n.on("*",r),i&&o(this,lt).emit(this.onAddEvent,n),s}delete(e,n=!0,i=!1){const s=this.get(e);if(!s)return!1;s.removeListener("*",o(this,Jr).get(e));const r=super.delete(e);return i&&s.removeAllListeners(),n&&o(this,lt).emit(this.onDeleteEvent,s),r}clear(e=!0,n=!1){this.forEach(s=>{s.removeListener("*",o(this,Jr).get(s.id)),n&&s.removeAllListeners()});const i=super.clear();return e&&o(this,lt).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}lt=new WeakMap,Jr=new WeakMap;class Rg extends b0{constructor(){super({onAddEvent:"pluginAdded",onDeleteEvent:"pluginDeleted"})}add(e,n=!0){return super.add(e,n)}delete(e,n=!0,i=!1){return super.delete(e,n,i)}}var cL=Object.defineProperty,dL=Object.getOwnPropertyDescriptor,lL=(t,e,n,i)=>{for(var s=i>1?void 0:i?dL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&cL(e,n,s),s};let Lh=class{constructor(){y(this,"all"),y(this,"active"),this.all=new Rg,this.active=new Rg}};Lh=lL([Lt("0600")],Lh);var uL=Object.defineProperty,hL=Object.getOwnPropertyDescriptor,$l=(t,e,n,i)=>{for(var s=i>1?void 0:i?hL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&uL(e,n,s),s},Pn,$a,Gc,Pg;const k0=(Pg=class{constructor(t,e,n,i){y(this,"plugins"),S(this,Pn,void 0),S(this,$a,void 0),S(this,Gc,void 0),T(this,Pn,e),T(this,$a,n),T(this,Gc,t),this.plugins=i,this.setupEvents()}static init(t,e,n,i,s,r,a,c){return p(this,null,function*(){const d=new Lh;return e.forEach(h=>{const u=new _a(t,h,n,r,a,s,c);d.all.add(u)}),new k0(t,n,i,d)})}getRoomPlugins(){return p(this,null,function*(){var t;const{plugins:e}=yield o(this,Pn).getActivePlugins();(t=this.plugins.active)==null||t.toArray().forEach(n=>{this.disablePlugin({id:n.id})}),yield Promise.all(e.map(n=>this.enablePlugin({id:n.pluginId,enabledBy:n.enabledBy})))})}enablePlugin(t){return p(this,arguments,function*({id:e,enabledBy:n}){const i=this.plugins.all.get(e);i&&(yield i.activateForSelf(),i.enabledBy=n)})}disablePlugin(t){return p(this,arguments,function*({id:e}){const n=this.plugins.all.get(e);n&&n.deactivateForSelf()})}sendIframeEvent(t,e,n,i){const s=this.plugins.all.get(e);s&&s.sendIframeEvent({type:t,uuid:n,payload:i})}broadcastIframeEvent(t,e){this.plugins.active.forEach(n=>{this.sendIframeEvent(t,n.id,"",e)})}setupEvents(){this.plugins.all.on("stateUpdate",({active:t,id:e})=>{if(t){this.plugins.active.add(this.plugins.all.get(e));return}this.plugins.active.delete(e)}),L.onAsync(x.SOCKET_SERVICE_ROOM_JOINED,()=>p(this,null,function*(){yield this.getRoomPlugins(),m.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to fetch plugins.")})),o(this,Pn).on(ie.addPlugin,t=>p(this,null,function*(){var e;const n=t.pluginId;(e=this.plugins.all.get(n))!=null&&e.active||(yield this.enablePlugin({id:n,enabledBy:t.enabledBy}))})),o(this,Pn).on(ie.removePlugin,t=>p(this,null,function*(){var e;const n=t.pluginId;(e=this.plugins.all.get(n))!=null&&e.active&&(yield this.disablePlugin({id:n}))})),[ie.enablePluginForPeers,ie.enablePluginForRoom].forEach(t=>{o(this,Pn).on(t,(e,n)=>p(this,null,function*(){this.sendIframeEvent(t,e.pluginId,n,{enabledBy:e.enabledBy})}))}),[ie.disablePluginForPeers,ie.disablePluginForRoom].forEach(t=>{o(this,Pn).on(t,(e,n)=>p(this,null,function*(){this.sendIframeEvent(t,e.pluginId,n,{disabledBy:e.disabledBy})}))}),[ie.customPluginEventToPeers,ie.customPluginEventToRoom].forEach(t=>{o(this,Pn).on(t,(e,n)=>p(this,null,function*(){this.sendIframeEvent(t,e.pluginId,n,{data:JSON.parse(new TextDecoder().decode(e.pluginData))})}))}),[ie.storeInsertKeys,ie.storeGetKeys,ie.storeDeleteKeys].forEach(t=>{o(this,Pn).on(t,(e,n)=>p(this,null,function*(){var i;const s=(i=e.storeItems)==null?void 0:i.map(r=>{var a;return{timestamp:r.timestamp,peerId:r.peerId,payload:JSON.parse((a=r.payload)!=null&&a.length?new TextDecoder().decode(r.payload):"{}"),key:r.storeKey}});this.sendIframeEvent(t,e.pluginId,n,{storeName:e.storeName,storeItems:s})}))}),o(this,Pn).on(ie.storeDelete,(t,e)=>p(this,null,function*(){this.sendIframeEvent(ie.storeDelete,t.pluginId,e,{storeName:t.storeName})})),o(this,$a).on(Ge.sendMessageToPeers,t=>{const e=Ii==null?void 0:Ii.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(Ye.chatMessage,{message:e})}),o(this,$a).on(Ge.sendMessageToRoom,t=>{const e=Ii==null?void 0:Ii.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(Ye.chatMessage,{message:e})}),L.on(x.PEER_JOINED_INTERNAL,t=>{const e=ll(t);this.broadcastIframeEvent(Ye.peerJoined,e)}),L.on(x.PEER_CLOSED,t=>{this.broadcastIframeEvent(Ye.peerLeft,t)}),L.on(x.UPDATE_PEER_STAGE_STATUS,t=>{this.broadcastIframeEvent(Ye.peerStageStatusUpdate,t)}),o(this,Gc).subscribe("stageStatus",t=>{this.broadcastIframeEvent(Ye.stageStatusUpdate,t)})}},Pn=new WeakMap,$a=new WeakMap,Gc=new WeakMap,Pg);let Tc=k0;$l([k.trace("PluginController.getRoomPlugins")],Tc.prototype,"getRoomPlugins",1);$l([k.trace("PluginController.enableForSelf")],Tc.prototype,"enablePlugin",1);$l([k.trace("PluginController.disableForSelf")],Tc.prototype,"disablePlugin",1);$l([k.trace("PluginController.setupEvents")],Tc.prototype,"setupEvents",1);class pL{constructor(){y(this,"mediaJoined"),y(this,"socketJoined"),y(this,"socketJoinAttempted"),y(this,"mediaJoinAttempted"),y(this,"socketState"),y(this,"mediaState"),this.mediaJoined=!1,this.socketJoined=!1,this.socketJoinAttempted=!1,this.mediaJoinAttempted=!1,this.socketState={state:void 0,reconnected:!1,reconnectionAttempt:void 0},this.mediaState={recv:void 0,send:void 0}}get joinAttempted(){return this.mediaJoinAttempted||this.socketJoinAttempted}get roomJoined(){return this.mediaJoined&&this.socketJoined}updateSocketConnectionState(e,n){let i;const{reconnected:s}=this.socketState;switch(e){case"connected":i={state:"connected",reconnected:s,reconnectionAttempt:void 0};break;case"disconnected":i={state:"disconnected",reconnected:!1,reconnectionAttempt:0},this.socketJoined=!1;break;case"reconnected":i={state:"connected",reconnected:!0,reconnectionAttempt:void 0};break;case"reconnecting":i={state:"reconnecting",reconnected:s,reconnectionAttempt:0};break;case"reconnectAttempt":i={state:"reconnecting",reconnected:s,reconnectionAttempt:n};break;case"failed":i={state:"failed",reconnected:s,reconnectionAttempt:void 0},this.socketJoined=!1;break}i&&(L.emit(x.SOCKET_STATE_UPDATE,i),this.socketState=i)}}var mL=Object.defineProperty,fL=Object.getOwnPropertyDescriptor,bc=(t,e,n,i)=>{for(var s=i>1?void 0:i?fL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&mL(e,n,s),s},Ja,$c,Ka,Jc,Ag;let Er=(Ag=class extends fn{constructor(t,e){super(),S(this,Ka),S(this,Ja,void 0),S(this,$c,void 0),y(this,"recordingPeerIds",[]),y(this,"recordings",[]),T(this,$c,t),T(this,Ja,e)}get recordingState(){return this.recordings.some(t=>t.state==="RECORDING")?"RECORDING":this.recordings.some(t=>t.state==="PAUSED")?"PAUSED":this.recordings.some(t=>t.state==="STARTING")?"STARTING":this.recordings.some(t=>t.state==="STOPPING")?"STOPPING":"IDLE"}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}start(t){return p(this,null,function*(){if(!o(this,Ja).permissions.canRecord)throw m.error("DyteRecording::start::permission_denied"),new O("User does not have permission to start recording","1001");if((t==null?void 0:t.allowMultiple)!==!0&&(this.recordingState==="STARTING"||this.recordingState==="RECORDING"||this.recordingState==="STOPPING"))throw m.error("DyteRecording::start::recording_in_progress",{recording:{state:this.recordingState}}),new O(`Cant start recording, recordingState irregular: ${this.recordingState}`,"1005");try{const e=Pt(),{recording:n={}}=o(this,$c).getValue("defaults"),i=yield e.startRecording(n,t==null?void 0:t.allowMultiple);this.updateRecordings([...this.recordings,{id:i,state:"STARTING",type:"BROWSER"}])}catch(e){throw m.error("DyteRecording::stop::recording_failed_to_start",{error:e}),new O("Error while starting recording","1000")}})}stop(t){return p(this,null,function*(){yield Q(this,Ka,Jc).call(this,"stop",["RECORDING","PAUSED"],t)})}pause(t){return p(this,null,function*(){yield Q(this,Ka,Jc).call(this,"pause",["RECORDING"],t)})}resume(t){return p(this,null,function*(){yield Q(this,Ka,Jc).call(this,"resume",["PAUSED"],t)})}},Ja=new WeakMap,$c=new WeakMap,Ka=new WeakSet,Jc=function(t,e,n){return p(this,null,function*(){if(!o(this,Ja).permissions.canRecord)throw m.error("DyteRecording::stop::permission_denied"),new O("User does not have permission to stop recording","1001");let i=[];if(n!==void 0){const s=this.recordings.find(r=>r.id===n);if(s===void 0)throw new O("Could not find the specified recording","1004");if(e.includes(s.state)){m.error("DyteRecording::stop::recording_not_in_expected_state",{recording:{state:s.state}});return}i.push(s)}else i=this.recordings.filter(s=>e.includes(s.state));i.forEach(s=>p(this,null,function*(){const r=s.state;t==="stop"&&(s.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{yield Pt().updateRecording(s.id,t)}catch(a){throw m.error("DyteRecording::stop::recording_failed_to_stop",{error:a}),s.state!==r&&(s.state=r,this.emit("recordingUpdate",r)),new O("Error while stopping recording","1000")}}))})},Ag);bc([k.trace("DyteRecording.start")],Er.prototype,"start",1);bc([k.trace("DyteRecording.stop")],Er.prototype,"stop",1);bc([k.trace("DyteRecording.stop")],Er.prototype,"pause",1);bc([k.trace("DyteRecording.stop")],Er.prototype,"resume",1);Er=bc([Lt("1000")],Er);var gL=Object.defineProperty,vL=Object.getOwnPropertyDescriptor,yL=(t,e,n,i)=>{for(var s=i>1?void 0:i?vL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&gL(e,n,s),s},xh;class w0{constructor(e,n,i){y(this,"recording"),y(this,"room"),S(this,xh,void 0),T(this,xh,e),this.recording=new Er(e,n),this.room=i,this.setupEvents()}getRecordingTypeFromProtoType(e){let n;switch(e){case mr.BROWSER:n="BROWSER";break;case mr.COMPOSITE:n="COMPOSITE";break;case mr.TRACK:n="TRACK";break;default:n="BROWSER"}return n}setupEvents(){L.on(x.ROOM_STATE,e=>{e.activeRecordings.length!==0?this.recording.updateRecordings(e.activeRecordings.map(n=>{const i=this.getRecordingTypeFromProtoType(n.recordingType);return{id:n.recordingId,state:n.recordingStatus,type:i}})):this.recording.recordings.length&&this.recording.updateRecordings([])}),this.room.on(z.recordingStarted,e=>{let n=!1;const i=[...this.recording.recordings];if(i.forEach(s=>{s.id===e.recordingId&&(n=!0,s.state="RECORDING")}),n===!1){const s=this.getRecordingTypeFromProtoType(e.recordingType);i.push({id:e.recordingId,state:"RECORDING",type:s})}this.recording.updateRecordings(i)}),this.room.on(z.recordingPaused,e=>{const n=[...this.recording.recordings];n.forEach(i=>{i.id===e.recordingId&&(i.state="PAUSED")}),this.recording.updateRecordings(n)}),this.room.on(z.recordingStopped,e=>{const n=[...this.recording.recordings.filter(i=>i.id!==e.recordingId)];this.recording.updateRecordings(n)})}}xh=new WeakMap;yL([k.trace("RecordingController.setupEvents")],w0.prototype,"setupEvents",1);class EL{static hasFeature(e){var n;return(n=re.hasFeature(e))!=null?n:!1}static getFeatureValue(e){return re.getValue(e)}static getAllFeatures(){return re.getAllFlags()}}class rm{constructor(e,n,i){y(this,"logger"),y(this,"features"),y(this,"browserSpecs"),y(this,"callStats"),this.logger=e,this.features=n,this.browserSpecs=Be,this.callStats=i}static init(e){return new rm(m,EL,e)}}class am{constructor(e){y(this,"internals"),this.internals=e}static init(){return p(this,null,function*(){const e=rm.init(ne);return new am(e)})}}var SL=Object.defineProperty,TL=Object.getOwnPropertyDescriptor,vn=(t,e,n,i)=>{for(var s=i>1?void 0:i?TL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&SL(e,n,s),s},Et,ut,We,gi,Un,Td,Vh;class on extends Ca{constructor(e,n,i=Uh,s=!0){super(),S(this,Et,void 0),S(this,ut,void 0),S(this,We,void 0),S(this,gi,void 0),S(this,Un,void 0),S(this,Td,void 0),S(this,Vh,void 0),y(this,"audioUpdateInProgress"),y(this,"videoUpdateInProgress"),T(this,Vh,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,T(this,Et,new _0(e,n)),T(this,ut,new HL(o(this,Et),void 0,i)),T(this,We,new YL(o(this,Et),void 0,i)),T(this,Un,new JL(o(this,Et))),T(this,gi,new GL(o(this,Et))),T(this,Td,s),o(this,ut).on("trackMuted",this.onAudioTrackMuted.bind(this)),o(this,ut).on("trackChanged",this.onAudioTrackChanged.bind(this)),o(this,We).on("trackChanged",this.onVideoTrackChanged.bind(this)),o(this,We).on("trackEnded",this.onVideoTrackEnded.bind(this)),o(this,Un).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}onVisibilityChange(){return p(this,null,function*(){ne.tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?ne.browserBackgrounded():(ne.browserForegrounded(),yield this.setupSpeaker())})}repopulateAvailableDevices(){return p(this,null,function*(){return!0})}setupStreams(e){return p(this,arguments,function*({audio:n,video:i}){var s;n?ne.audioOn():ne.audioOff(),i?ne.videoOn():ne.videoOff();let r,a;if(n&&i)try{const c=yield o(this,Et).getAudioAndVideoTrack(o(this,ut).userSelectedDevice,o(this,We).userSelectedDevice);r=c.audioTrack,a=c.videoTrack}catch(c){m.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:c})}if(!r&&n)try{r=yield o(this,Et).getAudioTrack(!1,o(this,ut).userSelectedDevice)}catch(c){m.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!a&&i)try{a=yield o(this,Et).getVideoTrack(o(this,We).userSelectedDevice)}catch(c){m.error("LocalMediaHandler::init::Failed to get video track",{error:c})}n&&!r&&ne.audioOff(),i&&!a&&ne.videoOff(),yield o(this,ut).setMediaTrack(r),yield o(this,We).setMediaTrack(a);try{yield o(this,gi).setupSpeaker()}catch(c){}if(a){const c=yield this.getDeviceById(a.getSettings().deviceId);ne.selectedDevice("VIDEO",c)}if(r){const c=yield this.getDeviceById(r.getSettings().deviceId);ne.selectedDevice("AUDIO",c)}(s=o(this,gi).currentDevice)!=null&&s.deviceId&&ne.selectedDevice("SPEAKER",o(this,gi).currentDevice),o(this,Et).onDeviceChange((c,d,h)=>{this.onDeviceChange(d,h)})})}getCurrentDevices(){return{audio:o(this,ut).currentDevice,video:o(this,We).currentDevice,speaker:o(this,gi).currentDevice}}get permissions(){return o(this,Et).permissions}getAllDevices(){return o(this,Et).getAvailableDevices()}getDeviceById(e,n){return o(this,Et).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return o(this,ut).mediaTrack}get audioTrack(){return o(this,ut).transformedMediaTrack}get audioEnabled(){return o(this,ut).trackEnabled}enableAudio(){return p(this,null,function*(){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{yield o(this,ut).unmuteTrack()}catch(e){}finally{this.audioUpdateInProgress=!1}}})}disableAudio(){o(this,ut).muteTrack()}getAudioDevices(e){return o(this,Et).getAudioInputDevices(e)}setAudioDevice(e){return p(this,null,function*(){yield o(this,ut).setDevice(e),e!=null&&e.deviceId&&ne.selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}setupSpeaker(){return o(this,gi).setupSpeaker()}setSpeakerDevice(e){return p(this,null,function*(){yield o(this,gi).setupSpeaker(e),e!=null&&e.deviceId&&ne.selectedDevice("SPEAKER",e),this.emit("DEVICE_CHANGE",{device:e})})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return o(this,We).mediaTrack}get videoTrack(){return o(this,We).transformedMediaTrack}get videoEnabled(){return o(this,We).trackEnabled}enableVideo(){return p(this,null,function*(){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{yield o(this,We).unmuteTrack()}catch(e){}finally{this.videoUpdateInProgress=!1}}})}disableVideo(){o(this,We).disableTrack()}getVideoDevices(e){return o(this,Et).getVideoInputDevices(e)}setVideoDevice(e){return p(this,null,function*(){yield o(this,We).setDevice(e),e!=null&&e.deviceId&&ne.selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}updateVideoConstraints(e){return p(this,null,function*(){yield o(this,We).updateConstraints(e)})}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:o(this,Un).audioMediaTrack,video:o(this,Un).videoMediaTrack}}get screenShareEnabled(){return o(this,Un).trackEnabled}enableScreenShare(){return p(this,null,function*(){yield o(this,Un).enableScreenShare()})}disableScreenShare(){return p(this,null,function*(){o(this,Un).disableScreenShare()})}updateScreenshareConstraints(e){return p(this,null,function*(){yield o(this,Un).updateConstraints(e)})}getSpeakerDevices(e){return o(this,Et).getAudioOutputDevices(e)}addAudioMiddleware(e){return o(this,ut).addMiddleware(e)}removeAudioMiddleware(e){return o(this,ut).removeMiddleware(e)}removeAllAudioMiddlewares(){return o(this,ut).removeAllMiddlewares()}addVideoMiddleware(e){return o(this,We).addMiddleware(e)}removeVideoMiddleware(e){return o(this,We).removeMiddleware(e)}removeAllVideoMiddlewares(){return o(this,We).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return o(this,We).setVideoMiddlewareGlobalConfig(e)}destruct(){o(this,ut).disableTrack(),o(this,We).disableTrack(),o(this,We).terminateMiddlewareWebWorker(),o(this,Un).disableScreenShare(),o(this,Et).destruct()}onDeviceChange(e,n){return p(this,null,function*(){var i,s;this.emit("DEVICE_LIST_UPDATED",e),!(n||!o(this,Td))&&((i=e==null?void 0:e.added)==null||i.forEach(r=>p(this,null,function*(){var a;r&&!Uh(r)&&(r.kind==="audioinput"&&((a=this.audioTrack)==null?void 0:a.enabled)===!0?yield this.setAudioDevice(r):r.kind==="audiooutput"&&(yield this.setSpeakerDevice(r)))})),(s=e==null?void 0:e.removed)==null||s.forEach(r=>p(this,null,function*(){var a;if(r.kind==="audiooutput"&&((a=this.getCurrentDevices().speaker)==null?void 0:a.deviceId)===r.deviceId){const c=(yield this.getSpeakerDevices()).find(d=>d.deviceId!==r.deviceId);c&&(yield this.setSpeakerDevice(c))}})))})}removeAllTracks(){this.destruct()}removeAudioTrack(){o(this,ut).disableTrack()}removeVideoTrack(){o(this,We).disableTrack(),o(this,We).terminateMiddlewareWebWorker()}removeDocumentEventListeners(){return p(this,null,function*(){document.removeEventListener("visibilitychange",this.onVisibilityChange)})}}Et=new WeakMap,ut=new WeakMap,We=new WeakMap,gi=new WeakMap,Un=new WeakMap,Td=new WeakMap,Vh=new WeakMap;vn([k.trace("MediaHandler.setupStreams")],on.prototype,"setupStreams",1);vn([k.trace("MediaHandler.enableAudio")],on.prototype,"enableAudio",1);vn([k.trace("MediaHandler.disableAudio")],on.prototype,"disableAudio",1);vn([k.trace("MediaHandler.setAudioDevice")],on.prototype,"setAudioDevice",1);vn([k.trace("MediaHandler.enableVideo")],on.prototype,"enableVideo",1);vn([k.trace("MediaHandler.disableVideo")],on.prototype,"disableVideo",1);vn([k.trace("MediaHandler.setVideoDevice")],on.prototype,"setVideoDevice",1);vn([k.trace("MediaHandler.updateVideoConstraints")],on.prototype,"updateVideoConstraints",1);vn([k.trace("MediaHandler.enableScreenShare")],on.prototype,"enableScreenShare",1);vn([k.trace("MediaHandler.disableScreenShare")],on.prototype,"disableScreenShare",1);vn([k.trace("MediaHandler.updateScreenshareConstraints")],on.prototype,"updateScreenshareConstraints",1);vn([k.trace("MediaHandler.destruct")],on.prototype,"destruct",1);vn([k.trace("MediaHandler.onDeviceChange")],on.prototype,"onDeviceChange",1);function Kc(t,e,n){switch(!0){case Be.isChromiumBased():switch(e){case"NotAllowedError":return n.includes("by system")?"SYSTEM_DENIED":t==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case Be.isSafari():switch(e){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case Be.isFirefox():switch(e){case"NotFoundError":case"NotReadableError":return"SYSTEM_DENIED";case"NotAllowedError":return"DENIED";case"AbortError":default:return"COULD_NOT_START"}default:return"COULD_NOT_START"}}const bL=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function Uh(t){var e,n;const i=(e=t.label)==null?void 0:e.toLowerCase();return((n=Be._bowser)==null?void 0:n.getOSName())==="macOS"&&i.includes("iphone")?(m.log("isVirtualDevice::ignore_macos_continuity"),!0):bL.some(s=>i==null?void 0:i.includes(s))}function kL(t,e){return p(this,null,function*(){if(!(t!=null&&t.length))return e;const n=new AudioContext,i=yield Promise.all(t==null?void 0:t.map(a=>a(n))),s=n.createMediaStreamSource(new MediaStream([e])),r=n.createMediaStreamDestination();try{let a=s;for(let c=0;c<i.length;c+=1)a.connect(i[c]),a=i[c];a.connect(r)}catch(a){return m.error("getTransformedAudioTrack::middleware_execution_failed",{error:a}),e}return r.stream.getAudioTracks()[0]})}var Kr;class wL{constructor(){S(this,Kr,void 0)}terminateMiddlewareWebWorker(){if(o(this,Kr))try{da(o(this,Kr)),T(this,Kr,void 0)}catch(e){m.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}getTransformedVideoTrack(e,n,i){return p(this,null,function*(){if(!(e!=null&&e.length))return n;const s=document.createElement("canvas"),r=yield Promise.all(e==null?void 0:e.map(g=>g({canvas:s,WorkerTimers:TS})));if(i.disablePerFrameCanvasRendering){const g=s.captureStream().getVideoTracks()[0];return Object.defineProperty(g,"originalSettings",{value:n.getSettings()}),g}const a=document.createElement("video"),c=new MediaStream;c.addTrack(n);const d=s.getContext("2d");a.srcObject=c,a.autoplay=!0,this.terminateMiddlewareWebWorker();const h=()=>p(this,null,function*(){if(n.enabled===!1||n.readyState==="ended"){this.terminateMiddlewareWebWorker(),a.remove(),s.remove();return}try{d.drawImage(a,0,0);for(let g=0;g<r.length;g+=1)typeof r[g]=="function"&&(yield r[g](s,d))}catch(g){m.error("getTransformedVideoTrack::middleware_execution_failed",{error:g})}});try{a.play()}catch(g){}a.addEventListener("play",()=>{s.width=a.width||n.getSettings().width,s.height=a.width||n.getSettings().height,T(this,Kr,Yd(h,50))},!1);const u=s.captureStream().getVideoTracks()[0];return Object.defineProperty(u,"originalSettings",{value:n.getSettings()}),u})}}Kr=new WeakMap;const Mg={gross:{width:{ideal:192},height:{ideal:144}},qvga:{width:{ideal:384},height:{ideal:288}},pvga:{width:{ideal:480},height:{ideal:360}},vga:{width:{ideal:640},height:{ideal:480}},hd:{width:{ideal:1280},height:{ideal:720}},hd_cropped:{width:{ideal:900},height:{ideal:720}},fhd:{width:{ideal:1920},height:{ideal:1080}}},_L=[[320,[{rid:"q",maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"}]],[640,[{rid:"q",scaleResolutionDownBy:2,maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:7e5,maxFramerate:30,scalabilityMode:"L1T1"}]],[1280,[{rid:"q",scaleResolutionDownBy:2,maxBitrate:5e5,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:13e5,maxFramerate:30,scalabilityMode:"L1T1"}]],[1920,[{rid:"q",scaleResolutionDownBy:2,maxBitrate:9e5,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:15e5,maxFramerate:30,scalabilityMode:"L1T1"}]]],IL=t=>{var e;const n="getSettings"in t&&t.getSettings().width||"getConstraints"in t&&t.getConstraints().width||"originalSettings"in t&&((e=t.originalSettings)==null?void 0:e.width);let i=_L;re.hasFeature(ue.OVERRIDE_HIVE_SIMULCAST_DYNAMIC)&&(i=JSON.parse(re.getValue(ue.OVERRIDE_HIVE_SIMULCAST_DYNAMIC)));const s=i.map(([c])=>c).sort((c,d)=>c-d);let r=Number.MAX_VALUE,a=0;return s.forEach((c,d)=>{Math.abs(c-n)<r&&(r=Math.abs(c-n),a=d)}),i[a][1]};var De=(t=>(t.WEBCAM="webcam",t.WEBCAM_BACKUP="webcam_backup",t.MIC="mic",t.SCREENSHARE_VIDEO="screenshare_video",t.SCREENSHARE_AUDIO="screenshare_audio",t))(De||{});const CL=fC(),xr=qn(CL.config.media);function RL(t){var e,n;const i={};return t.audio&&(i.audio={enableStereo:(e=t.audio.enableStereo)!=null?e:!1,enableHighBitrate:(n=t.audio.enableHighBitrate)!=null?n:!1}),i.video=t.video.quality,i}var zr,Bh;class PL{constructor(e,n){S(this,zr,void 0),S(this,Bh,void 0),y(this,"getScreenShareConstraints",()=>{var i,s,r,a,c,d,h,u,g,E,b;const w=(i=o(this,zr))==null?void 0:i.screenshare,M=(r=(s=w==null?void 0:w.width)==null?void 0:s.max)!=null?r:1920,D=(c=(a=w==null?void 0:w.height)==null?void 0:a.max)!=null?c:1080,F=(h=(d=w==null?void 0:w.frameRate)==null?void 0:d.max)!=null?h:5;let Y=(g=(u=w==null?void 0:w.frameRate)==null?void 0:u.ideal)!=null?g:5;const X=w==null?void 0:w.displaySurface,A=w==null?void 0:w.selfBrowserSurface;re.getValue(ue.VAL_MIN_FRAMERATE)&&(Y=parseInt((E=re.getValue(ue.VAL_MIN_FRAMERATE))==null?void 0:E.toString(),10));let $={width:{max:M},height:{max:D},frameRate:{ideal:Y,max:F}};if(re.hasFeature(ue.SCREENSHARE_CONSTRAINTS)){const me=(b=re.getValue(ue.SCREENSHARE_CONSTRAINTS))==null?void 0:b.toString();$=JSON.parse(me)}return X!==void 0&&["monitor","browser","window"].includes(X)&&($=ee(H({},$),{displaySurface:X})),A!==void 0&&($=ee(H({},$),{selfBrowserSurface:A})),{audio:!0,video:$}}),y(this,"getAudioConstraints",i=>{var s,r,a,c,d,h,u,g;const E={},b=(s=o(this,zr))==null?void 0:s.audio,w=b!=null&&b.enableStereo?2:1;return Be.isFirefox()||Be.isWebKitBased()?(E.audio={deviceId:i,autoGainControl:(r=b==null?void 0:b.autoGainControl)!=null?r:!0,echoCancellation:(a=b==null?void 0:b.echoCancellation)!=null?a:!0,noiseSuppression:(c=b==null?void 0:b.noiseSupression)!=null?c:!0,channelCount:w},E):(E.audio={},E.audio.optional=[i?{sourceId:i}:{sourceId:"default"},{channelCount:w},{echoCancellation:(d=b==null?void 0:b.echoCancellation)!=null?d:!0},{googEchoCancellation:(h=b==null?void 0:b.echoCancellation)!=null?h:!0},{googAutoGainControl:(u=b==null?void 0:b.autoGainControl)!=null?u:!0},{googNoiseSuppression:(g=b==null?void 0:b.noiseSupression)!=null?g:!0},{googHighpassFilter:!0}],E)}),y(this,"getVideoConstraints",i=>{var s,r,a,c;const d={},h=(s=o(this,zr))==null?void 0:s.video;let u=Mg.vga;if(typeof h=="string"?u=Mg[h]:h!==void 0&&(u.height.ideal=h.height.ideal,u.width.ideal=h.width.ideal),u.frameRate={ideal:(a=(r=u.frameRate)==null?void 0:r.ideal)!=null?a:24},Be.isChromiumBased()&&(u.frameRate.max=30),re.hasFeature(ue.VIDEO_CONSTRAINTS)){const g=(c=re.getValue(ue.VIDEO_CONSTRAINTS))==null?void 0:c.toString();u=JSON.parse(g)}return d.video=u,typeof d.video=="boolean"||(i?d.video.deviceId={exact:i}:d.video.facingMode="user"),d}),T(this,Bh,e),T(this,zr,n)}getUpdatedVideoConstraints(e){return e}}zr=new WeakMap,Bh=new WeakMap;class Uu extends Error{constructor(e,n,i){super(n),y(this,"constraints"),y(this,"name"),this.name=e,this.constraints=i}}class AL{constructor(){y(this,"permissions"),this.permissions={audio:"NOT_REQUESTED",video:"NOT_REQUESTED",screenshare:"NOT_REQUESTED"}}getAudioInputDevices(e){return p(this,null,function*(){let n=e;return e||(n=yield this.getAvailableDevices()),n.filter(i=>i.kind==="audioinput")})}getVideoInputDevices(e){return p(this,null,function*(){let n=e;return e||(n=yield this.getAvailableDevices()),n.filter(i=>i.kind==="videoinput")})}getAudioOutputDevices(e){return p(this,null,function*(){let n=e;return e||(n=yield this.getAvailableDevices()),n.filter(i=>i.kind==="audiooutput")})}}var ML=Object.defineProperty,OL=Object.getOwnPropertyDescriptor,zn=(t,e,n,i)=>{for(var s=i>1?void 0:i?OL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&ML(e,n,s),s},za,An,Bu,Og;let mn=(Og=class extends AL{constructor(t,e){super(),y(this,"availableDevices"),S(this,za,void 0),S(this,An,void 0),S(this,Bu,void 0),T(this,Bu,t),T(this,An,new PL(t,e)),T(this,za,new AbortController),this.availableDevices=[],this.getAvailableDevices()}get constraintsBuilder(){return o(this,An)}destruct(){return p(this,null,function*(){var t;(t=o(this,za))==null||t.abort()})}handlePermissionErrors(t,e){const n=Kc(t,e.name,e.message);return this.permissions[t]=n,L.emit(x.MEDIA_PERMISSION_ERROR,{message:n,constraints:e.constraints,kind:t}),n}getAudioAndVideoTrack(t,e){return p(this,null,function*(){const n={audio:o(this,An).getAudioConstraints(t).audio,video:o(this,An).getVideoConstraints(e).video};try{m.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(n)});const i=yield navigator.mediaDevices.getUserMedia(n);m.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(n)});const s=i.getAudioTracks()[0];let r=i.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",re.hasFeature(ue.OBS_QUALITY)&&r.label.includes("OBS Virtual")){const a=(yield this.getVideoInputDevices()).find(c=>c.label.includes("OBS Virtual"));r=yield this.getVideoTrack(a.deviceId)}return L.emit(x.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),L.emit(x.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:s,videoTrack:r}}catch(i){throw m.error("WebMediaInterface.getAudioAndVideoTrack",{error:i}),new O("Couldnt fetch audio and video track","1605")}})}getAudioTrack(t,e){return p(this,null,function*(){let n=yield this.getAudioInputDevices();if(n.length===0)throw this.permissions.audio="NO_DEVICES_AVAILABLE",L.emit(x.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new O("No audio devices available","1606");const i=s=>p(this,null,function*(){let r;try{n=n.filter(c=>c.deviceId!==s),r=o(this,An).getAudioConstraints(s),m.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(r)});const[a]=(yield navigator.mediaDevices.getUserMedia(r)).getAudioTracks();return m.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(r)}),a}catch(a){const c=Kc("audio",a.name,a.message),d=new Uu(a.name,a.message,r);if(c==="COULD_NOT_START"){const h=n.shift();if(!h)throw d;m.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(r),error:a});const u=o(this,An).getAudioConstraints(h.deviceId);return m.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(u)}),i(h.deviceId)}throw d}});try{const s=yield i(e);return s.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",L.emit(x.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),s}catch(s){throw s.constraints&&this.handlePermissionErrors("audio",s),new O(s.message,"1601")}})}getVideoTrack(t){return p(this,null,function*(){var e;const n=re.hasFeature(ue.OBS_QUALITY),i=(e=yield this.getCurrentDeviceLabel(t))==null?void 0:e.includes("OBS Virtual"),s=n&&i,r=yield this.getVideoInputDevices();if(r.length===0)throw this.permissions.video="NO_DEVICES_AVAILABLE",L.emit(x.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new O("No video devices available","1607");const a=c=>p(this,null,function*(){try{let d=c;const{video:h}=d;s&&typeof h!="boolean"&&(d={video:{deviceId:h.deviceId}}),m.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(d)});const[u]=(yield navigator.mediaDevices.getUserMedia(d)).getVideoTracks();if(s&&typeof h!="boolean"&&typeof h.width=="object"){const{width:g,height:E}=u.getSettings(),{ideal:b}=h.width;u.applyConstraints({width:{ideal:b},height:{ideal:Math.floor(E*b/g)},frameRate:h.frameRate})}return m.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(d)}),u}catch(d){const h=Kc("video",d.name,d.message),u=new Uu(d.name,d.message,c);if(h==="COULD_NOT_START"){const g=r.shift();if(!g)throw u;m.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(c),error:d});const E=o(this,An).getVideoConstraints(g.deviceId);return m.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(E)}),a({video:E.video})}throw u}});try{const c=o(this,An).getVideoConstraints(t),d=yield a(c);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",L.emit(x.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),d}catch(c){throw c.constraints&&this.handlePermissionErrors("video",c),new O(c.message,"1602")}})}getScreenShareTracks(){return p(this,null,function*(){const t=e=>p(this,null,function*(){try{m.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),ne.screenShareRequested();const n=yield navigator.mediaDevices.getDisplayMedia(e);return m.info("getDisplayMediaWithoutTimeout::received_display_media",{constraints:JSON.stringify(e)}),n}catch(n){const i=Kc("video",n.name,n.message),s=new Uu(n.name,n.message,e),r={video:!0};if(xR(e,r)||!re.hasFeature(ue.SCREEENSHARE_CONSTRAINTS_RETRY))throw s;if(i==="COULD_NOT_START")return t(r);throw s}});try{const e=o(this,An).getScreenShareConstraints(),n=yield t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",L.emit(x.MEDIA_PERMISSION_UPDATE,{message:this.permissions.screenshare,kind:"screenshare"})),{audioTrack:n.getAudioTracks()[0],videoTrack:n.getVideoTracks()[0]}}catch(e){throw e.constraints&&this.handlePermissionErrors("screenshare",e),new O(e.message,"1612")}})}getCurrentDeviceLabel(t){return p(this,null,function*(){const e=yield this.getDevice(t||"default");return e==null?void 0:e.label})}getAvailableDevices(){return p(this,null,function*(){try{const t=yield navigator.mediaDevices.enumerateDevices();return this.availableDevices=t,t}catch(t){throw m.error("enumerate_devices_failed",{error:t}),new O("Failed to get available devices","1609")}})}getAvailableDevicesByKind(t){return p(this,null,function*(){try{return(yield navigator.mediaDevices.enumerateDevices()).filter(({kind:e})=>t===e)}catch(e){throw m.error("enumerate_devices_failed",{error:e}),new O("Failed to get available devices by kind","1609")}})}getDevice(t){return p(this,null,function*(){try{return(yield navigator.mediaDevices.enumerateDevices()).filter(e=>e.deviceId===t)[0]}catch(e){throw m.error("enumerate_devices_failed",{error:e}),new O("Failed to get device","1609")}})}onDeviceChange(t){return p(this,null,function*(){Be.supportsDeviceChangeEvent()&&navigator.mediaDevices.addEventListener("devicechange",e=>p(this,null,function*(){var n,i;const s=u=>`${u.kind}-${u.deviceId}-${u.groupId}`,r=this.availableDevices,a=new Set(r.map(u=>s(u))),c=yield this.getAvailableDevices(),d=new Set(c.map(u=>s(u))),h={added:c.filter(u=>!a.has(s(u))),removed:r.filter(u=>!d.has(s(u))),devices:c};if((n=h.added)!=null&&n.length||(i=h.removed)!=null&&i.length){m.info("repopulated_full_device_list",{devices:JSON.stringify(c)});const u=[...h.added,...h.removed];u.some(g=>g.kind==="audioinput")&&ne.devices("AUDIO",c==null?void 0:c.filter(g=>g.kind==="audioinput")),u.some(g=>g.kind==="videoinput")&&ne.devices("VIDEO",c==null?void 0:c.filter(g=>g.kind==="videoinput")),u.some(g=>g.kind==="audiooutput")&&ne.devices("SPEAKER",c==null?void 0:c.filter(g=>g.kind==="audiooutput")),t(e,h,!1)}}),{signal:o(this,za).signal})})}},za=new WeakMap,An=new WeakMap,Bu=new WeakMap,Og);zn([k.trace("WebMediaInterface.destruct")],mn.prototype,"destruct",1);zn([k.trace("WebMediaInterface.handlePermissionErrors")],mn.prototype,"handlePermissionErrors",1);zn([k.trace("WebMediaInterface.getAudioAndVideoTrack")],mn.prototype,"getAudioAndVideoTrack",1);zn([k.trace("WebMediaInterface.getAudioTrack")],mn.prototype,"getAudioTrack",1);zn([k.trace("WebMediaInterface.getVideoTrack")],mn.prototype,"getVideoTrack",1);zn([k.trace("WebMediaInterface.getScreenShareTracks")],mn.prototype,"getScreenShareTracks",1);zn([k.trace("WebMediaInterface.getAvailableDevices")],mn.prototype,"getAvailableDevices",1);zn([k.trace("WebMediaInterface.getAvailableDevicesByKind")],mn.prototype,"getAvailableDevicesByKind",1);zn([k.trace("WebMediaInterface.getDevice")],mn.prototype,"getDevice",1);zn([k.trace("WebMediaInterface.onDeviceChange")],mn.prototype,"onDeviceChange",1);mn=zn([Lt("1600")],mn);const _0=mn,Jo={setItem:(t,e)=>{try{localStorage.setItem(t,e)}catch(n){m.error("LocalStorage::setItem::crashed",{error:n,localStorage:{key:t,value:e}})}},getItem:t=>{try{return localStorage.getItem(t)}catch(e){m.error("LocalStorage::getItem::crashed",{error:e,localStorage:{key:t}})}return null}},DL=(t=0)=>new Promise(e=>setTimeout(e,t)),NL=(t,e,n)=>{const i=typeof n=="number"?n:250,s=t.createMediaStreamSource(e),r=t.createAnalyser();r.fftSize=2048,s.connect(r);const a=new Uint8Array(r.fftSize);let c=!1;setTimeout(()=>{c=!0},i);function d(){return c?Promise.resolve(!0):(r.getByteTimeDomainData(a),a.some(h=>h!==128&&h!==0)?Promise.resolve(!1):DL().then(d))}return d().then(h=>(s.disconnect(),h),h=>{throw s.disconnect(),h})},LL=typeof AudioContext!="undefined"?AudioContext:null;class om{constructor(e){y(this,"_AudioContext"),y(this,"audioContext"),y(this,"_audioContextRefContainers");const n=H({AudioContext:LL},e);Object.defineProperties(this,{_AudioContext:{value:n.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:om}})}getOrCreate(e){if(!this._audioContextRefContainers.has(e)&&(this._audioContextRefContainers.add(e),this._AudioContext&&!this.audioContext))try{this.audioContext=new this._AudioContext}catch(n){}return this.audioContext}release(e){this._audioContextRefContainers.has(e)&&(this._audioContextRefContainers.delete(e),!this._audioContextRefContainers.size&&this.audioContext&&(this.audioContext.close(),this.audioContext=null))}}const Dg=new om,xL=3,VL=250;function UL(t){const e={},n=Dg.getOrCreate(e);let i=xL;function s(){return i-=1,NL(n,t.srcObject,VL).then(r=>r?i>0?s():!0:!1).catch(()=>!0)}return s().finally(()=>{Dg.release(e)})}function Ng(t){return p(this,null,function*(){const e=new Audio,n=new MediaStream;n.addTrack(t),e.srcObject=n;let i=!1;try{const s=e.play();s&&(yield s),i=yield UL(e),i&&m.info("checkIfAudioTrackIsSilent::silence_detected")}catch(s){m.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:s})}finally{e.pause(),e.remove()}return i})}var BL=Object.defineProperty,FL=Object.getOwnPropertyDescriptor,I0=(t,e,n,i)=>{for(var s=i>1?void 0:i?FL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&BL(e,n,s),s};let ul=class extends Ca{constructor(t,e,n){var i;super(),y(this,"constructorName",this.constructor.name),y(this,"userSelectedDevice"),y(this,"mediaInterface"),y(this,"isNonPreferredDevice"),y(this,"_mediaTrack"),y(this,"transformedMediaTrack"),y(this,"middlewares",[]),y(this,"currentDevice"),y(this,"userPreferredDeviceKey",`Dyte::${this.constructorName}::UserDeviceID`),y(this,"setUserPreferredDevice",s=>Jo.setItem(this.userPreferredDeviceKey,s)),y(this,"getUserPreferredDevice",()=>Jo.getItem(this.userPreferredDeviceKey)),this.mediaInterface=t,e&&this.setMediaTrack(e),this.userSelectedDevice=(i=this.getUserPreferredDevice())!=null?i:void 0,this.isNonPreferredDevice=n,this.onTrackEnded=this.onTrackEnded.bind(this),this.onTrackMuted=this.onTrackMuted.bind(this)}disableTrack(){var t,e;this.removeMediaTrackListeners(),(t=this._mediaTrack)==null||t.stop(),this._mediaTrack=void 0,(e=this.transformedMediaTrack)==null||e.stop(),this.transformedMediaTrack=void 0}get mediaTrack(){return this._mediaTrack}setMediaTrack(t){return p(this,null,function*(){const e=n=>{m.error(`${this.constructorName}.setMediaTrack.error`,{error:n})};try{this.disableTrack()}catch(n){e(n)}this._mediaTrack=yield this.conditionallyChangeTrack(t),yield this.setTransformedTrack();try{this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(n){e(n)}})}get trackEnabled(){return!!this.mediaTrack&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}muteTrack(){if(!this.mediaTrack){m.warn("BaseMediaHandler.muteTrack Tried muting with no track present");return}this.transformedMediaTrack&&(this.transformedMediaTrack.enabled=!1),this.mediaTrack.enabled=!1}unmuteTrack(){return p(this,null,function*(){try{this.mediaTrack?this.mediaTrack.enabled=!0:yield this.enableTrack(!1)}catch(t){throw m.error(`${this.constructorName}.unmuteTrack.error`,{error:t}),this.disableTrack(),new O("Failed to unmute track","1611")}})}getCurrentDeviceId(){var t,e;const{kind:n}=this.mediaTrack;switch(n){case"audio":{const i=this.mediaTrack.getConstraints();return this.userSelectedDevice?(e=(t=i==null?void 0:i.deviceId)!=null?t:i==null?void 0:i.advanced[0].deviceId)!=null?e:this.mediaTrack.getSettings().deviceId:this.mediaTrack.getSettings().deviceId}default:return this.mediaTrack.getSettings().deviceId}}setCurrentDevice(){return p(this,null,function*(){var t;if(!this.mediaTrack){this.currentDevice=void 0;return}const e=this.getCurrentDeviceId();((t=this.currentDevice)==null?void 0:t.deviceId)!==e&&(this.currentDevice=yield this.mediaInterface.getDevice(e))})}setDevice(t){return p(this,null,function*(){if(!t)throw m.warn(`${this.constructorName}.setDevice No device received`),new O("No device received!","1603");this.userSelectedDevice=t.deviceId,this.setUserPreferredDevice(t.deviceId),yield this.onSetDevice(t)})}addMiddleware(t){return p(this,null,function*(){if(Be.isWebKitBased()&&!re.hasFeature(ue.ALLOW_SAFARI_MEDIA_MIDDLEWARES))return{success:!1,message:"Middlewares are not supported in this WebKit engine based browser."};if(this.middlewares.includes(t))return{success:!1,message:"This middleware has been applied, already. Skipping."};try{return this.middlewares.push(t),this.trackEnabled&&(yield this.setTransformedTrack()),{success:!0,message:"Successfully added the middleware."}}catch(e){return m.error("While adding middleware",{error:e}),this.removeMiddleware(t),{success:!1,message:e==null?void 0:e.message}}})}removeMiddleware(t){return p(this,null,function*(){const e=this.middlewares.indexOf(t,0);if(e>-1)try{return this.middlewares.splice(e,1),yield this.setTransformedTrack(!0),{success:!0,message:"Successfully removed the middleware."}}catch(n){return m.error("While removing middleware",{error:n}),{success:!1,message:n==null?void 0:n.message}}return{success:!1,message:"No such middleware was found. Skipping."}})}removeAllMiddlewares(){return p(this,null,function*(){var t;if((t=this.middlewares)!=null&&t.length)try{return this.middlewares=[],yield this.setTransformedTrack(!0),{success:!0,message:"Successfully removed all the middlewares."}}catch(e){return m.error("While removing all the middlewares",{error:e}),{success:!1,message:e==null?void 0:e.message}}return{success:!1,message:"No middlewares were found. Skipping."}})}addMediaTrackListeners(){var t,e,n;this.mediaTrack&&(m.info(`${this.constructorName}.addMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(n=this.mediaTrack)==null?void 0:n.kind}`),this.mediaTrack.addEventListener("ended",this.onTrackEnded),this.mediaTrack.addEventListener("mute",this.onTrackMuted))}removeMediaTrackListeners(){var t,e,n;this.mediaTrack&&(m.info(`${this.constructorName}.removeMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(n=this.mediaTrack)==null?void 0:n.kind}`),m.info(`${this.constructorName}.removeMediaTrackListeners`),this.mediaTrack.removeEventListener("ended",this.onTrackEnded),this.mediaTrack.removeEventListener("mute",this.onTrackMuted))}};I0([k.trace("BaseMediaHandler.unmuteTrack")],ul.prototype,"unmuteTrack",1);ul=I0([Lt("1600")],ul);const C0=ul;var jL=Object.defineProperty,WL=Object.getOwnPropertyDescriptor,cm=(t,e,n,i)=>{for(var s=i>1?void 0:i?WL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&jL(e,n,s),s};const Fu="[Dyte]nonSilentDeviceLabels";class Jl extends C0{onSetDevice(e){return p(this,null,function*(){if(!e)throw m.warn("AudioMediaHandler.setDevice No device received"),new O("No device received!","1603");if(e.kind!=="audioinput")throw m.warn("AudioMediaHandler.setDevice Received non audio device"),new O("Non audio device received while setting device!","1603");try{const n=this.trackEnabled;yield this.setMediaTrack(yield this.mediaInterface.getAudioTrack(!n,this.userSelectedDevice)),this.userSelectedDevice=void 0}catch(n){throw m.error("AudioMediaHandler.setDevice.error",{error:n}),this.disableTrack(),new O(n.message,"1604")}})}enableTrack(e){return p(this,null,function*(){if(this.trackEnabled){m.warn("AudioMediaHandler.enableTrack Track already enabled!");return}const n=yield this.mediaInterface.getAudioTrack(e,this.userSelectedDevice);yield this.setMediaTrack(n)})}setTransformedTrack(e){return p(this,null,function*(){var n;if(!e&&!((n=this.middlewares)!=null&&n.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=yield kL(this.middlewares,this.mediaTrack),this.emit("trackChanged")}catch(i){m.error("AudioMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}})}onTrackEnded(){return p(this,null,function*(){m.info("AudioMediaHandler.TrackEnded"),this.emit("trackEnded");const e=this.mediaTrack.enabled;this.disableTrack(),yield this.enableTrack(!e),yield this.setTransformedTrack(),this.emit("trackChanged")})}onTrackMuted(){m.info("AudioMediaHandler.TrackMuted"),this.emit("trackMuted")}conditionallyChangeTrack(e){return p(this,null,function*(){var n;if(!e||this.userSelectedDevice)return e;let i=e;const s=yield this.mediaInterface.getAudioInputDevices(),r=this.isNonPreferredDevice?s.filter(d=>d&&!this.isNonPreferredDevice(d)):s;if(!(r!=null&&r.length))return i;r.find(d=>d.deviceId===e.getSettings().deviceId)||(i.stop(),m.info("localmediahandler::setupstreams::found_audio_non_preferred"),i=yield this.mediaInterface.getAudioTrack(!1,r[0].deviceId));const a=JSON.parse(Jo.getItem(Fu));if(a!=null&&a.devices.some(d=>d.label===i.label))return i;if(!(yield Ng(i))){const d=(n=a==null?void 0:a.devices.concat({label:i.label}))!=null?n:[{label:i.label}];return Jo.setItem(Fu,JSON.stringify({devices:d})),i}m.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const c=i.getSettings().deviceId;return r.filter(d=>d.deviceId!==c).some(d=>p(this,null,function*(){if(i=yield this.mediaInterface.getAudioTrack(!1,d.deviceId),!(yield Ng(i))){const h=a.devices.concat({label:i.label});return Jo.setItem(Fu,JSON.stringify({devices:h})),m.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return m.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1})),i})}}cm([k.trace("AudioMediaHandler.setTransformedTrack")],Jl.prototype,"setTransformedTrack",1);cm([k.trace("AudioMediaHandler.onTrackEnded")],Jl.prototype,"onTrackEnded",1);cm([k.trace("AudioMediaHandler.conditionallyChangeTrack")],Jl.prototype,"conditionallyChangeTrack",1);const HL=Jl;var yo;class qL{constructor(e){S(this,yo,void 0),y(this,"currentDevice"),T(this,yo,e)}setupSpeaker(e){return p(this,null,function*(){var n,i;if(!(o(this,yo)instanceof _0))return;let s=e;if(e||([s]=(yield o(this,yo).getAvailableDevicesByKind("audiooutput")).filter(a=>!Uh(a))),!s)throw new O("No speaker found","1608");if(((n=this.currentDevice)==null?void 0:n.deviceId)===s.deviceId)return;this.currentDevice=s;const r=document.querySelectorAll("audio");(i=r[0])!=null&&i.setSinkId&&r.forEach(a=>p(this,null,function*(){if(typeof a.sinkId!="undefined"&&this.currentDevice.deviceId&&a.sinkId!==this.currentDevice.deviceId)try{yield a.setSinkId(this.currentDevice.deviceId)}catch(c){}}))})}}yo=new WeakMap;const GL=qL;class $L extends Ca{constructor(e){super(),y(this,"mediaInterface"),y(this,"audioMediaTrack"),y(this,"videoMediaTrack"),this.mediaInterface=e}get trackEnabled(){return!!this.videoMediaTrack}enableScreenShare(){return p(this,null,function*(){var e,n;try{const{audioTrack:i,videoTrack:s}=yield this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=i,this.videoMediaTrack=s,this.addMediaTrackListeners(),((n=(e=this.mediaInterface)==null?void 0:e.permissions)==null?void 0:n.screenshare)==="ACCEPTED")return;this.mediaInterface.permissions&&(this.mediaInterface.permissions.screenshare="ACCEPTED",L.emit(x.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch(i){}})}disableScreenShare(){var e,n;this.removeMediaTrackListeners(),(e=this.audioMediaTrack)==null||e.stop(),(n=this.videoMediaTrack)==null||n.stop(),this.videoMediaTrack=void 0,this.audioMediaTrack=void 0}updateConstraints(e){return p(this,null,function*(){if(!this.videoMediaTrack)throw new O("No media track enabled!","1610");const n=this.mediaInterface;if(!n.constraintsBuilder)throw new O("update constraints not supported for non web clients","1100");try{this.videoMediaTrack.applyConstraints(n.constraintsBuilder.getUpdatedVideoConstraints(e)),this.addMediaTrackListeners()}catch(i){m.error("ScreenShareHandler.updateConstraints.error",{error:i})}})}addMediaTrackListeners(){var e,n;(e=this.videoMediaTrack)==null||e.addEventListener("ended",this.onTrackEnded.bind(this)),Be.isWebKitBased()&&((n=this.videoMediaTrack)==null||n.addEventListener("mute",this.onTrackEnded.bind(this)))}removeMediaTrackListeners(){var e,n;(e=this.videoMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded),(n=this.videoMediaTrack)==null||n.removeEventListener("mute",this.onTrackEnded)}onTrackEnded(){this.emit("trackEnded")}}const JL=$L;var KL=Object.defineProperty,zL=Object.getOwnPropertyDescriptor,Kl=(t,e,n,i)=>{for(var s=i>1?void 0:i?zL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&KL(e,n,s),s},Eo,bd;class kc extends C0{constructor(e,n,i){super(e,n,i),S(this,Eo,void 0),S(this,bd,{disablePerFrameCanvasRendering:!1}),T(this,Eo,new wL)}onSetDevice(e){return p(this,null,function*(){if(!e)throw m.warn("VideoMediaHandler.setDevice No device received"),new O("No device received!","1603");if(e.kind!=="videoinput")throw m.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new O("Non video device received while setting video device!","1603");if(!(this.mediaTrack&&this.mediaTrack.enabled)){m.warn("VideoMediaHandler.setDevice Tried switching device with video disabled",{devices:[e]}),this.currentDevice=e;return}try{yield this.setMediaTrack(yield this.mediaInterface.getVideoTrack(this.userSelectedDevice))}catch(n){throw m.error("VideoMediaHandler.setDevice.error",{error:n}),this.disableTrack(),new O("Failed to change device","1600")}})}enableTrack(){return p(this,null,function*(){if(this.trackEnabled){m.warn("VideoMediaHandler.enableTrack Track already enabled!");return}yield this.setMediaTrack(yield this.mediaInterface.getVideoTrack(this.userSelectedDevice))})}setTransformedTrack(e){return p(this,null,function*(){var n;if(!e&&!((n=this.middlewares)!=null&&n.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=yield o(this,Eo).getTransformedVideoTrack(this.middlewares,this.mediaTrack,o(this,bd)),this.emit("trackChanged")}catch(i){m.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}})}setVideoMiddlewareGlobalConfig(e){return p(this,null,function*(){T(this,bd,e)})}updateConstraints(e){return p(this,null,function*(){if(!this._mediaTrack)throw new O("No media track enabled!","1610");const n=this.mediaInterface;if(!n.constraintsBuilder)throw new O("update constraints not supported for non web clients","1100");try{this._mediaTrack.applyConstraints(n.constraintsBuilder.getUpdatedVideoConstraints(e)),yield this.setTransformedTrack(),this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(i){m.error("VideoMediaHandler.updateConstraints.error",{error:i})}})}terminateMiddlewareWebWorker(){o(this,Eo).terminateMiddlewareWebWorker()}onTrackEnded(){return p(this,null,function*(){m.info("VideoMediaHandler.TrackEnded"),this.disableTrack(),this.emit("trackEnded")})}onTrackMuted(){m.info("VideoMediaHandler.TrackMuted"),this.emit("trackMuted")}conditionallyChangeTrack(e){return p(this,null,function*(){if(!e||this.userSelectedDevice)return e;let n=e;const i=yield this.mediaInterface.getVideoInputDevices(),s=this.isNonPreferredDevice?i.filter(r=>!this.isNonPreferredDevice(r)):i;return!(s!=null&&s.length)||window.FAST_DYTE||s.find(r=>r.deviceId===e.getSettings().deviceId)||(n.stop(),m.info("localmediahandler::setupstreams::found_video_non_preferred"),n=yield this.mediaInterface.getVideoTrack(s[0].deviceId)),n})}}Eo=new WeakMap,bd=new WeakMap;Kl([k.trace("VideoMediaHandler.setTransformedTrack")],kc.prototype,"setTransformedTrack",1);Kl([k.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],kc.prototype,"setVideoMiddlewareGlobalConfig",1);Kl([k.trace("VideoMediaHandler.onTrackEnded")],kc.prototype,"onTrackEnded",1);Kl([k.trace("VideoMediaHandler.conditionallyChangeTrack")],kc.prototype,"conditionallyChangeTrack",1);const YL=kc,Lg=qn(Xp());var dn,Yr,kd,So;const To=class{constructor(t){if(S(this,dn,void 0),S(this,Yr,void 0),S(this,kd,void 0),S(this,So,void 0),!t)throw new O("Could not load preset.","0904");T(this,dn,t.config),T(this,kd,t.name),T(this,Yr,t.ui||qn(Xp().ui)),T(this,So,t.permissions.plugins.config)}static fromResponse(t){return new To(t)}static default(){return new To(Lg)}static init(t,e=!0){return!t||e?new To(Lg):new To(t)}get setupScreen(){return{isEnabled:!0}}get waitingRoom(){return{isEnabled:!0}}get controlBar(){return{isEnabled:!0,elements:{chat:!0,fullscreen:!0,invite:!1,layout:!1,participants:!0,plugins:!0,polls:!0,reactions:!1,screenshare:!0}}}get header(){return{isEnabled:!0,elements:{logo:o(this,Yr).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return o(this,dn).viewType}get livestreamViewerQualities(){return o(this,dn).livestreamViewerQualities||[]}get maxVideoStreams(){return o(this,dn).maxVideoStreams}get maxScreenShareCount(){return o(this,dn).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(o(this,So)).filter(t=>o(this,So)[t].disabled)}get designTokens(){return o(this,Yr).designTokens}get configDiff(){return o(this,Yr).configDiff}get mediaConstraints(){var t,e,n,i,s,r,a,c,d,h,u,g,E,b,w,M,D,F,Y,X,A,$,me,Ie;return{audio:{enableStereo:(i=(n=(e=(t=o(this,dn))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:n.enableStereo)!=null?i:xr.audio.enableStereo,enableHighBitrate:(c=(a=(r=(s=o(this,dn))==null?void 0:s.media)==null?void 0:r.audio)==null?void 0:a.enableHighBitrate)!=null?c:xr.audio.enableHighBitrate},video:{quality:(g=(u=(h=(d=o(this,dn))==null?void 0:d.media)==null?void 0:h.video)==null?void 0:u.quality)!=null?g:xr.video.quality,frameRate:(M=(w=(b=(E=o(this,dn))==null?void 0:E.media)==null?void 0:b.video)==null?void 0:w.frameRate)!=null?M:xr.video.frameRate},screenshare:{quality:(X=(Y=(F=(D=o(this,dn))==null?void 0:D.media)==null?void 0:F.screenshare)==null?void 0:Y.quality)!=null?X:xr.screenshare.quality,frameRate:(Ie=(me=($=(A=o(this,dn))==null?void 0:A.media)==null?void 0:$.screenshare)==null?void 0:me.frameRate)!=null?Ie:xr.screenshare.frameRate}}}get name(){return o(this,kd)}};let QL=To;dn=new WeakMap,Yr=new WeakMap,kd=new WeakMap,So=new WeakMap;var XL=Object.defineProperty,ZL=Object.getOwnPropertyDescriptor,R0=(t,e,n,i)=>{for(var s=i>1?void 0:i?ZL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&XL(e,n,s),s},bo;class dm extends fn{constructor(e){super(),S(this,bo,void 0),y(this,"state","IDLE"),y(this,"playbackUrl"),y(this,"ingestionCredentials"),y(this,"viewerCount"),T(this,bo,e),this.viewerCount=0}setLivestreamState(e){const n=this.state;this.state=e,n!==e&&this.emitCurrentLivestreamState()}emitCurrentLivestreamState(){this.emit("livestreamUpdate",this.state)}start(){return p(this,arguments,function*(e={manualIngestion:!1}){if(!o(this,bo).permissions.canLivestream)throw m.error("DyteLivestream::start::permission_denied"),new O("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const n=Pt(),{playbackUrl:i,ingestionCredentials:s}=yield n.startLivestreaming(e);this.playbackUrl=i,this.ingestionCredentials=s,e!=null&&e.manualIngestion&&this.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}catch(n){throw m.error("DyteRecording::stop::livestream_failed_to_start",{error:n}),this.setLivestreamState("IDLE"),new O("Error while starting livestream","1900")}})}stop(){return p(this,null,function*(){if(!o(this,bo).permissions.canLivestream)throw m.error("DyteLivestream::stop::permission_denied"),new O("User does not have permission to stop livestreaming","1901");if(this.state!=="LIVESTREAMING"&&this.state!=="WAITING_ON_MANUAL_INGESTION")throw m.error("DyteLivestream::stop::inconsistent_state"),new O("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),yield Pt().stopLivestreaming()}catch(e){throw m.error("DyteLivestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new O("Error while stopping livestream","1900")}})}}bo=new WeakMap;R0([k.trace("livestream.start")],dm.prototype,"start",1);R0([k.trace("livestream.stop")],dm.prototype,"stop",1);var e2=Object.defineProperty,t2=Object.getOwnPropertyDescriptor,n2=(t,e,n,i)=>{for(var s=i>1?void 0:i?t2(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&e2(e,n,s),s},ko,wo,is;class P0{constructor(e,n){y(this,"livestream"),S(this,ko,void 0),S(this,wo,void 0),S(this,is,void 0),T(this,wo,e),this.livestream=new dm(e),T(this,is,n),this.setupEvents()}fetchInitialLivestreamingState(){return p(this,null,function*(){const e=Pt(),{status:n,playbackUrl:i,manualIngest:s,ingestionCredentials:r}=yield e.getActiveLivestream();this.livestream.playbackUrl=i,this.livestream.ingestionCredentials=r,n==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),n==="INVOKED"&&s&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")})}setupEvents(){o(this,is).on(z.startedLivestream,e=>p(this,null,function*(){this.livestream.playbackUrl=e.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{o(this,wo).permissions.canLivestream&&(yield this.fetchInitialLivestreamingState())}catch(n){m.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}})),o(this,is).on(z.livestreamingInvoked,e=>p(this,null,function*(){if(e.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{o(this,wo).permissions.canLivestream&&(yield this.fetchInitialLivestreamingState())}catch(n){m.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}})),o(this,is).on(z.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),o(this,is).on(z.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),o(this,is).on(z.roomPeerCount,e=>{this.livestream.viewerCount=e.count,this.livestream.emit("viewerCountUpdate",e.count)}),L.on(x.PEER_JOINED_INTERNAL,e=>p(this,null,function*(){var n;((n=e.flags)==null?void 0:n.hiddenParticipant)===!0&&e.recorderType==="LIVESTREAMER"&&(T(this,ko,e.id),this.livestream.setLivestreamState("LIVESTREAMING"))})),L.on(x.PEER_CLOSED,e=>{e.id===o(this,ko)&&(T(this,ko,void 0),this.livestream.setLivestreamState("IDLE"))}),L.onAsync(x.LEAVE_MEDIA_ROOM,()=>p(this,null,function*(){this.livestream.playbackUrl||(m.info("Fetching livestreaming state on leave stage"),yield this.fetchInitialLivestreamingState())})),L.on(x.SOCKET_SERVICE_ROOM_JOINED,()=>p(this,null,function*(){try{yield this.fetchInitialLivestreamingState()}catch(e){m.error("Error: LivestreamController.fetchLivestream")}}))}}ko=new WeakMap,wo=new WeakMap,is=new WeakMap;n2([k.trace("LivestreamController.setupEvents")],P0.prototype,"setupEvents",1);var i2=Object.defineProperty,s2=Object.getOwnPropertyDescriptor,wc=(t,e,n,i)=>{for(var s=i>1?void 0:i?s2(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&i2(e,n,s),s},Gt,qs,Gs,Fh,A0;class Aa{constructor({name:e,socketHandler:n,meetingId:i}){S(this,Fh),y(this,"name",""),S(this,Gt,{}),S(this,qs,""),S(this,Gs,void 0),y(this,"rateLimitConfig",{maxInvocations:5,period:1}),y(this,"bulkRateLimitConfig",{maxInvocations:5,period:1}),y(this,"listeners",{}),this.name=e,T(this,Gs,n),T(this,qs,i)}set(e,n,i=!0,s=!1){return p(this,null,function*(){o(this,Gt)[e]=n,i&&this.remoteSet(e,n),s&&(this.listeners[e]&&this.listeners[e].forEach(r=>r({[e]:o(this,Gt)[e]})),this.listeners["*"]&&this.listeners["*"].forEach(r=>r({[e]:o(this,Gt)[e]})))})}remoteSet(e,n){o(this,Gs).storeInsertKeys(o(this,qs),this.name,[{key:e,payload:n}])}bulkSet(e){return p(this,null,function*(){e.forEach(({key:n,payload:i})=>{o(this,Gt)[n]=i}),o(this,Gs).storeInsertKeys(o(this,qs),this.name,e)})}update(e,n,i=!0){return p(this,null,function*(){Q(this,Fh,A0).call(this,e,n,i)})}delete(e,n=!0,i=!1){return p(this,null,function*(){if(o(this,Gt)[e]&&delete o(this,Gt)[e],n)return o(this,Gs).storeDeleteKeys(o(this,qs),this.name,[{key:e}]);i&&(this.listeners[e]&&(this.listeners[e].forEach(s=>s({[e]:void 0})),delete this.listeners[e]),this.listeners["*"]&&this.listeners["*"].forEach(s=>s({[e]:void 0})))})}bulkDelete(e){return p(this,null,function*(){return e.forEach(({key:n})=>{o(this,Gt)[n]&&delete o(this,Gt)[n]}),o(this,Gs).storeDeleteKeys(o(this,qs),this.name,e)})}get(e){if(o(this,Gt)[e])return o(this,Gt)[e]}getAll(){return o(this,Gt)}get rateLimits(){return this.rateLimitConfig}updateRateLimits(e,n){this.rateLimitConfig.maxInvocations=e,this.rateLimitConfig.period=n}get bulkRateLimits(){return this.bulkRateLimitConfig}updateBulkRateLimits(e,n){this.bulkRateLimitConfig.maxInvocations=e,this.bulkRateLimitConfig.period=n}subscribe(e,n){if(this.listeners[e]){this.listeners[e].push(n);return}this.listeners[e]=[n]}unsubscribe(e,n){var i;if(n){this.listeners[e]=((i=this.listeners[e])==null?void 0:i.filter(s=>s!==n))||[];return}this.listeners[e]&&delete this.listeners[e]}populate(e){T(this,Gt,e)}}Gt=new WeakMap,qs=new WeakMap,Gs=new WeakMap,Fh=new WeakSet,A0=function(t,e,n=!0){let i;const s=o(this,Gt)[t],r=Object.prototype.toString.call(e),a=Object.prototype.toString.call(s);if(r!==a){this.set(t,e);return}switch(a){case"[object Array]":i=[...s,...e];break;case"[object Object]":i=H(H({},s),e);break;case"[object Map]":i=new Map([...s,...e]);break;case"[object Set]":i=new Set([...s,...e]);break;default:i=e;break}this.set(t,i,n)};wc([an(Pa,"rateLimitConfig")],Aa.prototype,"remoteSet",1);wc([an(Pa,"bulkRateLimitConfig")],Aa.prototype,"bulkSet",1);wc([an(Pa,"rateLimitConfig")],Aa.prototype,"update",1);wc([an(Pa,"rateLimitConfig")],Aa.prototype,"delete",1);wc([an(Pa,"bulkRateLimitConfig")],Aa.prototype,"bulkDelete",1);var la,ua,wd,ju,hl,rr,jh,M0;class r2{constructor(e,n){S(this,wd),S(this,jh),y(this,"stores",new Map),S(this,la,void 0),S(this,ua,""),S(this,hl,void 0),S(this,rr,new Map),T(this,la,n),T(this,ua,e.getValue("meetingId")),T(this,hl,e),Q(this,jh,M0).call(this)}create(e){const n=new Aa({name:e,socketHandler:o(this,la),meetingId:o(this,ua)});return o(this,la).storeGetKeys(o(this,ua),e,[]),new Promise((i,s)=>{const r=setTimeout(()=>s(Error("Failed")),3e3);o(this,rr).set(e,{rejectTimeout:r,resolve:i,store:n})})}}la=new WeakMap,ua=new WeakMap,wd=new WeakSet,ju=function(){return o(this,hl).getValue("peerId")},hl=new WeakMap,rr=new WeakMap,jh=new WeakSet,M0=function(){[ie.storeInsertKeys,ie.storeGetKeys,ie.storeDeleteKeys].forEach(t=>{o(this,la).on(t,e=>p(this,null,function*(){var n,i;if(e.pluginId!==o(this,ua))return;const s=(n=e.storeItems)==null?void 0:n.map(a=>{var c;return{timestamp:a.timestamp,peerId:a.peerId,payload:JSON.parse((c=a.payload)!=null&&c.length?new TextDecoder().decode(a.payload):"{}"),key:a.storeKey}});if(t===ie.storeGetKeys){const a=o(this,rr).get(e.storeName),c=this.stores.get(e.storeName)||(a==null?void 0:a.store);o(this,rr).get(e.storeName)&&(this.stores.set(e.storeName,a.store),a.resolve(c),clearTimeout(a.rejectTimeout),o(this,rr).delete(e.storeName)),s.forEach(d=>{c.set(d.key,d.payload,!1,!1)});return}const r=this.stores.get(e.storeName)||((i=o(this,rr).get(e.storeName))==null?void 0:i.store);r!==void 0&&(t===ie.storeInsertKeys&&s.forEach(({key:a,peerId:c,payload:d})=>{c!==o(this,wd,ju)&&r.set(a,d,!1,!0)}),t===ie.storeDeleteKeys&&s.forEach(({key:a,peerId:c})=>{c!==o(this,wd,ju)&&r.delete(a,!1,!0)}))}))})};function ar(t){var e,n,i,s,r,a,c,d,h,u,g,E,b;return t?{media:{audio:{enabled:t.audioEnabled,trackId:(e=t.audioTrack)==null?void 0:e.id,permission:"mediaPermissions"in t?(n=t.mediaPermissions)==null?void 0:n.audio:null},video:{enabled:t.videoEnabled,trackId:(i=t.videoTrack)==null?void 0:i.id,permission:"mediaPermissions"in t?(s=t.mediaPermissions)==null?void 0:s.video:null},screenshare:{enabled:t.screenShareEnabled,permission:"mediaPermissions"in t?(r=t.mediaPermissions)==null?void 0:r.screenshare:null,audio:{enabled:(c=(a=t.screenShareTracks)==null?void 0:a.audio)==null?void 0:c.enabled,trackId:(h=(d=t.screenShareTracks)==null?void 0:d.audio)==null?void 0:h.id},video:{enabled:(g=(u=t.screenShareTracks)==null?void 0:u.video)==null?void 0:g.enabled,trackId:(b=(E=t.screenShareTracks)==null?void 0:E.video)==null?void 0:b.id}}}}:{}}var a2=Object.defineProperty,o2=Object.getOwnPropertyDescriptor,Ma=(t,e,n,i)=>{for(var s=i>1?void 0:i?o2(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&a2(e,n,s),s};const c2=.8,d2=1.2;var Ya,Qa,Ls,Vr,Xa,Ur,Za,Wu,xg,qi,zc,xs,eo,Yc,Gi,Hu,Qc,qu,Vg;let Ai=(Vg=class extends fn{constructor(t,e,n,i){super(),S(this,Vr),S(this,Ur),S(this,Wu),S(this,eo),S(this,Qc),y(this,"id"),y(this,"userId"),y(this,"name"),y(this,"picture"),y(this,"isHost"),y(this,"customParticipantId"),y(this,"flags"),y(this,"device"),y(this,"videoTrack"),y(this,"audioTrack"),y(this,"screenShareTracks"),y(this,"videoEnabled"),y(this,"audioEnabled"),y(this,"screenShareEnabled"),y(this,"producers"),y(this,"manualProducerConfig"),S(this,Ya,void 0),y(this,"supportsRemoteControl",!1),S(this,Qa,void 0),y(this,"presetName"),S(this,Ls,void 0),S(this,qi,void 0),S(this,zc,void 0),S(this,xs,new Map),S(this,Gi,1),S(this,Hu,al(A=>{if(!this.videoTrack)return;const{clientWidth:$,clientHeight:me}=A,{width:Ie,height:fe}=this.videoTrack.getSettings();if(!Ie||!fe)return;const Je=fe/me,ht=Ie/$,V=Math.max(Je,ht);V>d2&&o(this,Gi)===1?(T(this,Gi,0),L.emit(x.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:o(this,Gi)})):V<c2&&o(this,Gi)===0&&(T(this,Gi,1),L.emit(x.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:o(this,Gi)}))},2e3)),T(this,Ls,t);const{id:s,userId:r,displayName:a,device:c,picture:d,isHost:h,flags:u,clientSpecificId:g,stageStatus:E,customParticipantId:b,audioMuted:w,audioTrack:M,videoEnabled:D=!1,videoTrack:F,producers:Y,metadata:X}=e;this.id=s,this.userId=r,this.name=a,this.device=c,this.picture=d,this.isHost=h,this.flags=u,this.manualProducerConfig=$R,T(this,Qa,E!=null?E:"ON_STAGE"),this.customParticipantId=b!=null?b:g,this.audioEnabled=!w,this.audioTrack=M,this.videoEnabled=D,this.videoTrack=F,this.screenShareTracks={audio:void 0,video:void 0},this.producers=Y!=null?Y:[],this.presetName=X==null?void 0:X.preset_name,T(this,Ya,!1),T(this,qi,n),T(this,zc,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),Q(this,Qc,qu).call(this)}get clientSpecificId(){return this.customParticipantId}get stageStatus(){return o(this,Qa)}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(m.info("DyteParticipant::setVideoEnabled::videoUpdate",H({},ar(this))),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(m.info("DyteParticipant::setAudioEnabled::audioUpdate",H({},ar(this))),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}))}setScreenShareEnabled(t,e=!0){this.screenShareEnabled=t,e&&this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}setupEvents(){this.on("videoUpdate",Q(this,Qc,qu))}pin(){return p(this,null,function*(){if(!o(this,Ur,Za))throw new O("Can`t pin participant without joining room","1205");if(!o(this,qi).permissions.pinParticipant)throw new O("You do not have permission to pin participants.","1201");return o(this,Vr,Xa).pinPeer(this.id)})}unpin(){return p(this,null,function*(){if(!o(this,Ur,Za))throw new O("Can`t unpin participant without joining room","1205");if(!o(this,qi).permissions.pinParticipant)throw new O("You do not have permission to unpin participants.","1201");return o(this,Vr,Xa).pinPeer(null)})}setIsPinned(t,e=!0){var n;T(this,Ya,t);const i=t?"pinned":"unpinned";(n=o(this,eo,Yc))==null||n.updateSource(this.id,{pinned:t}),e&&this.emit(i,this)}disableAudio(){return p(this,null,function*(){const t=this.id;if(m.info("DyteParticipant::disable_audio",{dyteParticipant:{id:t}}),!o(this,Ur,Za))throw new O("Can`t disable participant audio without joining room","1205");if(o(this,qi).permissions.canDisableParticipantAudio)return o(this,Vr,Xa).disableAudio(t);throw m.error("DyteParticipant::unauthorized_disable_audio",{dyteParticipant:{id:t}}),new O("Unauthorized: User does not have permission to disable participant audio.","1201")})}kick(){return p(this,null,function*(){const t=this.id;if(m.info("DyteParticipant::kick",{dyteParticipant:{id:t}}),!o(this,Wu,xg))throw new O("Can`t kick participant without joining room","1205");if(o(this,qi).permissions.kickParticipant){yield L.emitAsync(x.KICK_PEER,{peerId:t});return}throw m.error("DyteParticipant::unauthorized_kick",{dyteParticipant:{id:t}}),new O("Unauthorized: User does not have permission to kick participants.","1201")})}disableVideo(){return p(this,null,function*(){const t=this.id;if(m.info("DyteParticipant::disable_video",{dyteParticipant:{id:t}}),!o(this,Ur,Za))throw new O("Can`t disable participant video without joining room","1205");if(o(this,qi).permissions.canDisableParticipantVideo)return o(this,Vr,Xa).disableVideo(t);throw m.error("DyteParticipant::unauthorized_disable_video",{dyteParticipant:{id:t}}),new O("Unauthorized: User does not have permission to disable participant video.","1201")})}getPermissions(){return p(this,null,function*(){return o(this,zc).getUserPermissions(this.userId)})}setStageStatus(t){T(this,Qa,t),this.emit("stageStatusUpdate",this)}get isPinned(){return o(this,Ya)}registerVideoElement(t){var e,n,i,s;let r;(n=(e=o(this,xs).get(t))==null?void 0:e.observer)==null||n.disconnect(),"ResizeObserver"in window&&(r=new ResizeObserver(()=>o(this,Hu).call(this,t)),r.observe(t)),o(this,xs).set(t,{observer:r}),this.updateVideo(t),(s=o(this,eo,Yc))==null||s.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(i=this.raised)!=null?i:!1)}deregisterVideoElement(t){var e,n,i;t.srcObject=void 0,(n=(e=o(this,xs).get(t))==null?void 0:e.observer)==null||n.disconnect(),o(this,xs).delete(t),(i=o(this,eo,Yc))==null||i.removeSource(this.id)}updateVideo(t){var e;if(this.videoEnabled){if(this.videoTrack==null)return;const n=(e=t.srcObject)==null?void 0:e.getTracks()[0];if((n==null?void 0:n.id)===this.videoTrack.id)return;const i=new MediaStream;i.addTrack(this.videoTrack),t.srcObject=i}else t.srcObject=void 0;t.style.display=this.videoEnabled?"block":"none"}},Ya=new WeakMap,Qa=new WeakMap,Ls=new WeakMap,Vr=new WeakSet,Xa=function(){return o(this,Ls).getValue("roomNodeClient")},Ur=new WeakSet,Za=function(){return o(this,Ls).getValue("connectionHandler").mediaJoined},Wu=new WeakSet,xg=function(){return o(this,Ls).getValue("connectionHandler").socketJoined},qi=new WeakMap,zc=new WeakMap,xs=new WeakMap,eo=new WeakSet,Yc=function(){return o(this,Ls).getValue("pip")},Gi=new WeakMap,Hu=new WeakMap,Qc=new WeakSet,qu=function(){Array.from(o(this,xs).keys()).forEach(this.updateVideo)},Vg);Ma([k.trace("DyteParticipant.disableAudio")],Ai.prototype,"disableAudio",1);Ma([k.trace("DyteParticipant.kick")],Ai.prototype,"kick",1);Ma([k.trace("DyteParticipant.disableVideo")],Ai.prototype,"disableVideo",1);Ma([k.trace("DyteParticipant.getPermissions")],Ai.prototype,"getPermissions",1);Ma([k.trace("DyteParticipant.setStageStatus")],Ai.prototype,"setStageStatus",1);Ai=Ma([Lt("1200")],Ai);class to extends b0{constructor(e){const{onAddEvent:n="participantJoined",onDeleteEvent:i="participantLeft",onClearEvent:s="participantsCleared"}=e!=null?e:{};super({onAddEvent:n,onDeleteEvent:i,onClearEvent:s})}add(e,n=!0){return this.has(e.id)&&Object.is(this.get(e.id),e)===!1&&this.delete(e.id),super.add(e,n)}clear(e=!0,n=!1){return super.clear(e,n)}delete(e,n=!0,i=!1){return super.delete(e,n,i)}}var $s;class l2 extends Ca{constructor(){super(),S(this,$s,void 0),T(this,$s,new Map)}__set(e,n){return o(this,$s).set(e,n)}__clear(){return o(this,$s).clear()}get(e){return o(this,$s).get(e)}toArray(){return Array.from(o(this,$s).values())}}$s=new WeakMap;class u2{constructor(){y(this,"_orderedArray"),y(this,"_map"),this._map=new Map,this._orderedArray=[]}add(e,n){if(!this._map.has(e))return this._map.set(e,{peerId:e,priority:n}),this._orderedArray.splice(Math.max(n-1,0),0,e),this.index(e);const i=this.index(e);this.delete(e);const s=this.add(e,n);return i!==s?s:-1}delete(e){if(this._map.has(e)){const n=this.index(e);this._map.delete(e),this._orderedArray.splice(n,1)}}index(e){return this._map.has(e)?this._orderedArray.indexOf(e):-1}[Symbol.iterator](){return this._orderedArray[Symbol.iterator]()}}class h2{constructor(){y(this,"_activeSpeakerPeers"),y(this,"_compulsoryPeers"),this._activeSpeakerPeers=new u2,this._compulsoryPeers=new Set}add(e,n){if(!e)return-1;if(n<0)return this._compulsoryPeers.add(e),0;if(this.compulsoryPeers.includes(e)&&(n>0||n===246267631)){if(m.info("DyteSelectedPeer::removing_compulsory_peer",{selectedPeer:{peerId:e}}),this._removeFromCompulsoryPeer(e),n===246267631)return-1}else if(n===229490415)return this.delete(e),-1;return this._activeSpeakerPeers.add(e,n)}delete(e){m.info("DyteSelectedPeer::deleting_peer_from_selectedPeer",{selectedPeer:{peerId:e}}),this._removeFromCompulsoryPeer(e),this._activeSpeakerPeers.delete(e)}index(e){return this._activeSpeakerPeers.index(e)}get peers(){return Array.from(new Set(this.compulsoryPeers.concat(this.activeSpeakerPeers)))}get compulsoryPeers(){return Array.from(this._compulsoryPeers.values())}get activeSpeakerPeers(){return Array.from(this._activeSpeakerPeers)}_removeFromCompulsoryPeer(e){this._compulsoryPeers.delete(e)}}const O0=new h2;var p2=Object.defineProperty,m2=Object.getOwnPropertyDescriptor,yn=(t,e,n,i)=>{for(var s=i>1?void 0:i?m2(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&p2(e,n,s),s};const f2=["ACTIVE_GRID","PAGINATED","MANUAL"];var Mn,Br,no,Fr,io,so,Xc,jr,cn,Ug;let Qt=(Ug=class extends fn{constructor(t,e,n){super(),S(this,Br),S(this,Fr),S(this,so),y(this,"waitlisted"),y(this,"joined"),y(this,"active"),y(this,"videoSubscribed"),y(this,"audioSubscribed"),y(this,"pinned"),y(this,"all"),S(this,Mn,void 0),S(this,jr,void 0),S(this,cn,void 0),y(this,"rateLimitConfig",{maxInvocations:5,period:1}),y(this,"viewMode"),y(this,"currentPage"),y(this,"lastActiveSpeaker"),y(this,"selectedPeers",O0),T(this,Mn,t),T(this,jr,e),T(this,cn,n),this.waitlisted=new to,this.joined=new to,this.videoSubscribed=new to,this.audioSubscribed=new to,this.active=this.videoSubscribed,this.pinned=new to,this.all=new l2,this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return o(this,Mn).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}setupEvents(){L.on(x.E2EE_ACTIVE_CONSUMER,({peerId:t})=>{var e;((e=o(this,Mn).getValue("modules").e2ee)==null?void 0:e.enabled)!==!0&&this.emit("media_decode_error",{reason:`Got encrypted media for participantId ${t}, but encryption wasn't enabled in init.defaults`,code:"1702"})})}get count(){return this.joined.size}get maxActiveParticipantsCount(){var t;return(t=o(this,Mn))==null?void 0:t.getValue("maxPreferredStreams")}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new O("0 <= Max active participants count limit <= 24","1203");o(this,Mn).setValue("maxPreferredStreams",t),o(this,so,Xc)&&L.emit(x.UPDATE_ACTIVE)}get pageCount(){if(this.viewMode==="PAGINATED"){const t=this.selectedPeers.compulsoryPeers.length,e=this.joined.toArray().filter(n=>n.stageStatus==="ON_STAGE");return Math.ceil((e.length-t)/Math.max(this.maxActiveParticipantsCount-t,1))}return 0}acceptWaitingRoomRequest(t){var e,n;if(!o(this,Fr,io))throw new O("Can`t accept waiting room request without joining room","1205");const i=(n=(e=this.waitlisted.get(t))==null?void 0:e.userId)!=null?n:t;return o(this,cn).acceptWaitingRoomRequest([i])}acceptAllWaitingRoomRequest(t){return p(this,null,function*(){const e=t.map(n=>{var i,s;return(s=(i=this.waitlisted.get(n))==null?void 0:i.userId)!=null?s:n});return o(this,cn).acceptWaitingRoomRequest(e)})}rejectWaitingRoomRequest(t){return p(this,null,function*(){var e,n;if(!o(this,Fr,io))throw new O("Can`t reject waiting room request without joining room","1205");const i=(n=(e=this.waitlisted.get(t))==null?void 0:e.userId)!=null?n:t;o(this,cn).rejectWaitingRoomRequest([i])})}setViewMode(t){return p(this,null,function*(){if(m.info("DyteParticipants::set_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),!(e=>f2.includes(e))(t))throw m.error("DyteParticipants::setViewMode::invalid_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),new O(`Invalid view mode: ${t}. Try ACTIVE_GRID, PAGINATED or MANUAL.`,"1207");if(this.viewMode===t){m.info("DyteParticipants::setViewMode::view_mode_same_as_previous");return}if(t==="MANUAL")throw new O("Manual Subscription is not enabled for your Organization. Please contact support.","1208");this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,L.emit(x.UPDATE_ACTIVE,{page:this.currentPage})):t==="ACTIVE_GRID"&&(this.currentPage=0,L.emit(x.UPDATE_ACTIVE)),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})})}subscribe(t){return p(this,arguments,function*(e,n=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new O("MANUAL subscription mode was not activated.","1206");const i=[];e.forEach(s=>{const r=this.joined.get(s);if(r){if(n.includes("audio")){r.manualProducerConfig=ee(H({},r.manualProducerConfig),{audio:!0}),this.videoSubscribed.add(r);const a=r.producers.find(c=>c.kind==="audio"&&!c.screenShare);a&&i.push(a)}if(n.includes("video")){r.manualProducerConfig=ee(H({},r.manualProducerConfig),{video:!0}),this.audioSubscribed.add(r);const a=r.producers.find(c=>c.kind==="video"&&!c.screenShare);a&&i.push(a)}if(n.includes("screenshareAudio")){r.manualProducerConfig=ee(H({},r.manualProducerConfig),{screenshareAudio:!0});const a=r.producers.find(c=>c.kind==="audio"&&c.screenShare);i.push(a)}if(n.includes("screenshareVideo")){r.manualProducerConfig=ee(H({},r.manualProducerConfig),{screenshareVideo:!0});const a=r.producers.find(c=>c.kind==="video"&&c.screenShare);i.push(a)}}}),yield o(this,Br,no).createConsumers(i)})}unsubscribe(t){return p(this,arguments,function*(e,n=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new O("MANUAL subscription mode was not activated.","1206");const i=[];e.forEach(s=>{const r=this.joined.get(s);if(r){if(n.includes("audio")){r.manualProducerConfig=ee(H({},r.manualProducerConfig),{audio:!1});const a=r.producers.find(c=>c.kind==="audio"&&!c.screenShare);a&&i.push(a)}if(n.includes("video")){r.manualProducerConfig=ee(H({},r.manualProducerConfig),{video:!1});const a=r.producers.find(c=>c.kind==="video"&&!c.screenShare);a&&i.push(a)}if(n.includes("screenshareAudio")){r.manualProducerConfig=ee(H({},r.manualProducerConfig),{screenshareAudio:!1});const a=r.producers.find(c=>c.kind==="audio"&&c.screenShare);i.push(a)}if(n.includes("screenshareVideo")){r.manualProducerConfig=ee(H({},r.manualProducerConfig),{screenshareVideo:!1});const a=r.producers.find(c=>c.kind==="video"&&c.screenShare);i.push(a)}}}),yield o(this,Br,no).closeConsumers(i)})}getPeerIdsForCurrentPage(){m.info("DyteParticipants::getPeerIdsForCurrentPage()",{pageNavigation:{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}});const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(a=>this.joined.has(a)),n=Array.from(this.pinned.keys()).filter(a=>!e.includes(a)),i=Array.from(this.joined.toArray().filter(a=>a.stageStatus==="ON_STAGE").map(a=>a.id)),s=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-n.length)),r=this.currentPage*(this.maxActiveParticipantsCount-e.length-n.length);return e.concat(n,i.slice(s,r))}setPage(t){return p(this,null,function*(){if(m.info("DyteParticipants::set_page",{pageNavigation:{settingPage:t,viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),this.viewMode==="PAGINATED"){if(!Number.isInteger(t))throw m.error("DyteParticipants::invalid_page_number"),new O(`Invalid page: ${t}. Page must be an integer and greater than 0 and less than or equal to .pageCount`,"1202");this.currentPage=t,L.emit(x.UPDATE_ACTIVE,{page:t}),this.emit("pageChanged",{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount})}})}disableAllAudio(t){return p(this,null,function*(){if(m.info("DyteParticipants::disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),!o(this,so,Xc))throw new O("Can`t disable all audio without joining room","1205");if(o(this,jr).permissions.canAllowParticipantAudio)return o(this,Br,no).muteAll(t);throw m.error("DyteParticipants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new O("Unauthorized: User does not have permission to disable peer audio.","1201")})}disableAllVideo(){return p(this,null,function*(){if(m.info("DyteParticipants::disable_all_video"),!o(this,so,Xc))throw new O("Can`t disable all video without joining room","1205");if(o(this,jr).permissions.canAllowParticipantVideo)return o(this,Br,no).muteAllVideo();throw m.error("DyteParticipants::unauthorized_disable_all_video"),new O("Unauthorized: User does not have permission to disable peer video.","1201")})}disableAudio(t){return p(this,null,function*(){this.joined.get(t).disableAudio()})}disableVideo(t){return p(this,null,function*(){this.joined.get(t).disableVideo()})}kick(t){return p(this,null,function*(){yield L.emitAsync(x.KICK_PEER,{peerId:t})})}kickAll(){return p(this,null,function*(){if(m.info("DyteParticipants::kick_all"),o(this,Mn).getValue("viewType")!=="LIVESTREAM"&&!o(this,Fr,io))throw new O("Can`t kick all without joining room","1205");if(!o(this,jr).permissions.kickParticipant)throw m.error("DyteParticipants::unauthorized_kick_all"),new O("Unauthorized: User does not have permission to kick peers.","1201");const t=re.hasFeature(ue.PROPAGATE_KICK_ALL);o(this,cn).kickAll(t)})}broadcastMessage(t,e,n){return p(this,null,function*(){if(m.info("DyteParticipants::broadcastMessage"),!o(this,Fr,io))throw new O("Can`t broadcast message without joining room","1205");if(!(t!=null&&t.trim()))throw new O("`type` must be a non-empty string.","1209");if(n)if("meetingIds"in n)yield o(this,cn).broadcastToMeetings(t,n.meetingIds,e);else{let i=[];"participantIds"in n?i=n.participantIds:i=this.joined.toArray().filter(s=>{var r;return(r=n.presetNames)==null?void 0:r.includes(s.presetName)}).map(s=>s.id),yield o(this,cn).broadcastToPeers(t,i,e)}else yield o(this,cn).broadcastMessage(t,e)})}getAllJoinedPeers(t,e,n){return p(this,null,function*(){return(yield o(this,cn).getRoomPeers(t,e,n)).peers.map(Di.formatSocketServiceMessage)})}updatePermissions(t,e){return p(this,null,function*(){const n=this.joined.toArray().filter(s=>t.includes(s.id)).map(s=>s.userId),i=[...new Set(n)];if(!i.length)throw new O("Cannot update permissions, no valid userIDs found","1204");o(this,cn).updatePermissions(i,e)})}getParticipantsInMeetingPreJoin(){return p(this,null,function*(){return o(this,cn).getRoomPeersNonPaginated()})}},Mn=new WeakMap,Br=new WeakSet,no=function(){return o(this,Mn).getValue("roomNodeClient")},Fr=new WeakSet,io=function(){var t;return((t=o(this,Mn).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},so=new WeakSet,Xc=function(){var t;return((t=o(this,Mn).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},jr=new WeakMap,cn=new WeakMap,Ug);yn([k.trace("DyteParticipants.setViewMode")],Qt.prototype,"setViewMode",1);yn([k.trace("DyteParticipants.setPage")],Qt.prototype,"setPage",1);yn([k.trace("DyteParticipants.disableAllAudio")],Qt.prototype,"disableAllAudio",1);yn([k.trace("DyteParticipants.disableAllVideo")],Qt.prototype,"disableAllVideo",1);yn([k.trace("DyteParticipants.disablePeerAudio")],Qt.prototype,"disableAudio",1);yn([k.trace("DyteParticipants.disablePeerVideo")],Qt.prototype,"disableVideo",1);yn([k.trace("DyteParticipants.kickPeer")],Qt.prototype,"kick",1);yn([k.trace("DyteParticipants.kickAll")],Qt.prototype,"kickAll",1);yn([k.trace("DyteParticipants.broadcastMessage"),an(Pa,"rateLimitConfig")],Qt.prototype,"broadcastMessage",1);yn([k.trace("DyteParticipants.getAllJoinedPeers"),an({maxInvocations:10,period:60})],Qt.prototype,"getAllJoinedPeers",1);yn([k.trace("DyteParticipant.updatePermissions"),an({maxInvocations:1e3,period:60})],Qt.prototype,"updatePermissions",1);yn([k.trace("DyteParticipants.getParticipantsInMeetingPreJoin")],Qt.prototype,"getParticipantsInMeetingPreJoin",1);Qt=yn([Lt("1200")],Qt);var ks=(t=>(t.NEW="new",t.CONNECTING="connecting",t.RECONNECTING="reconnecting",t.DISCONNECTED="disconnected",t.CONNECTED="connected",t.FAILED="failed",t.CLOSED="closed",t))(ks||{}),bt=(t=>(t[t.HIVE=1]="HIVE",t[t.ROOM_NODE=2]="ROOM_NODE",t[t.CF=3]="CF",t))(bt||{}),g2=Object.defineProperty,v2=Object.getOwnPropertyDescriptor,Rr=(t,e,n,i)=>{for(var s=i>1?void 0:i?v2(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&g2(e,n,s),s};const D0=class{constructor(t,e,n,i){switch(y(this,"participants"),y(this,"self"),y(this,"selectedPeers",O0),y(this,"maxSpatialLayerUpdates",new Map),y(this,"consumerPeerMap"),y(this,"events"),y(this,"roomSocketHandler"),y(this,"context"),y(this,"videoPeerConsumerMap",new Map),y(this,"updateConsumerSpatialLayers",al(()=>{const s={},r=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(r.entries()).forEach(([a,c])=>{s[c]===void 0&&(s[c]={layer:c,consumerIds:[]}),s[c].consumerIds.push(a)}),Object.keys(s).forEach(a=>{const c=s[a];m.log(`Switching max spatial layer to ${c.layer}`,{consumerIds:c.consumerIds}),this.roomNodeClient.switchConsumersToLayer(c.consumerIds,c.layer)})},2e3)),y(this,"updateConsumers",(s,r)=>{let a=Promise.resolve();r.length>0&&(m.info("Closing consumers for producers",{producers:r}),a=this.roomNodeClient.closeConsumers(r)),a.then(()=>{s.length!==0&&(m.info("Consuming producers",{producers:s}),this.roomNodeClient.createConsumers(s).catch(c=>m.error("Error activating peers",{error:c})))}).catch(c=>m.error("Error deactivating peers",{error:c}))}),y(this,"updateConsumersDebounced",al(this.updateConsumers,200,{trailing:!0})),this.context=t,this.roomSocketHandler=n,this.participants=new Qt(t,e,this.roomSocketHandler),this.self=e,this.consumerPeerMap=new Map,i){case bt.HIVE:{this.events=_n;break}case bt.CF:{this.events=Wn;break}default:this.events=_n}e.config.viewType!=="CHAT"&&this.setupEventsGlobal(),this.setupEvents()}get roomNodeClient(){return this.context.getValue("roomNodeClient")}get mediaJoined(){var t;return((t=this.roomNodeClient)==null?void 0:t.mediaJoined)===!0}get pip(){return this.context.getValue("pip")}setupEvents(){this.roomSocketHandler.on(z.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),L.on(x.SOCKET_PEERS,t=>p(this,null,function*(){const e=re.hasFeature(ue.DEBUG_SOCKET_JOIN);if(e){const n=t&&(t==null?void 0:t.length)<20?{peers:JSON.stringify(t.map(i=>i.peerId))}:void 0;m.info("Processing socket peers",n)}t==null||t.forEach(n=>{n.waitlisted||this.onParticipantJoined(this.fromSocketService(n))}),e&&m.info("Processed socket peers")})),this.roomSocketHandler.on(this.events.peerJoinedBroadcast,({participant:t})=>{re.hasFeature(ue.DEBUG_SOCKET_JOIN)&&m.info("events.peerJoinedBroadcast",{peers:t.peerId}),this.onMediaJoined(t.peerId,t.producerStates,t.capabilities)}),this.roomSocketHandler.on(this.events.selfJoinComplete,({participants:t,selectedPeers:e,roomState:n})=>{if(re.hasFeature(ue.DEBUG_SOCKET_JOIN)){const r=t&&(t==null?void 0:t.length)<20?{peers:JSON.stringify(t.map(a=>a.peerId))}:void 0;m.info("events.selfJoinComplete",r)}t.forEach(({peerId:r,producerStates:a,capabilities:c})=>this.onMediaJoined(r,a,c));const{audioPeers:i,compulsoryPeers:s}=e!=null?e:{};n.pinnedPeerIds.length!==0&&this.onParticipantPinned(n.pinnedPeerIds[0]),this.computeActivateParticipants(i!=null?i:[],s),L.emit(x.UPDATE_ACTIVE,{createAllConsumers:!0})}),L.on(x.MAX_SPATIAL_LAYER_CHANGE,({peerId:t,maxSpatialLayer:e})=>{const n=this.videoPeerConsumerMap.get(t);n&&(this.maxSpatialLayerUpdates.set(n,e),this.updateConsumerSpatialLayers())}),L.on(x.NEW_PRODUCER,({peerId:t,producer:e})=>{const n=this.participants.joined.get(t);if(!n){m.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:e==null?void 0:e.producerId,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}},dyteParticipant:{id:t}});return}if(n.producers.push(e),m.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}}),this.participants.viewMode==="MANUAL"){let i=!1;const s=e.kind==="audio",r=e.kind==="video",a=n.manualProducerConfig;(s&&(a.audio&&!e.screenShare||a.screenshareAudio&&e.screenShare)||r&&(a.video&&!e.screenShare||a.screenshareVideo&&e.screenShare))&&(i=!0),i?this.roomNodeClient.createConsumers([e]):m.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}});return}(e==null?void 0:e.kind)==="audio"&&this.participants.audioSubscribed.get(t)||(e==null?void 0:e.kind)==="video"&&this.participants.videoSubscribed.get(t)||e!=null&&e.screenShare?this.roomNodeClient.createConsumers([e]).catch(i=>{m.error("ParticipantController::createConsumer failed",{error:i})}):m.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}})}),L.on(x.PRODUCER_CLOSED,({peerId:t,producerId:e})=>{const n=this.participants.joined.get(t);if(!n){m.warn("ParticipantController::NEW_PRODUCER::participant not found",{dyteParticipant:{id:t}});return}n.producers=n.producers.filter(i=>i.producerId!==e)}),L.on(x.PRODUCER_TOGGLE,({peerId:t,producerId:e,paused:n,kind:i})=>{const s=this.participants.joined.get(t);if(s){i==="audio"&&s.setAudioEnabled(!n);const r=s.producers.find(a=>a.producerId===e);r&&(r.pause=n)}}),this.roomSocketHandler.on(this.events.globalPeerPinBroadcast,t=>{let e;if(t&&(e=t.participantId),!this.mediaJoined)return;const n=e;this.onParticipantPinned(n);const i=this.participants.joined.get(n);i&&this.roomNodeClient.activatePeers(i.producers).catch(s=>{m.error("unable to create consumers",{error:s})})}),this.roomSocketHandler.on(this.events.selectedPeer,({audioPeers:t,compulsoryPeers:e})=>{this.mediaJoined&&this.onSelectedPeers(e.concat(t))}),this.roomSocketHandler.on(this.events.selectedPeerDiff,({entries:t})=>{if(!this.mediaJoined)return;const e=t.map(n=>({peerId:n.peerId,priority:n.priority}));this.updateActiveParticipantsWithPriorities(e,!0)})}waitingRoomRequestHandler(t){const e=t.requests.filter(i=>!this.participants.waitlisted.toArray().find(s=>s.userId===i.userId)),n=this.participants.waitlisted.toArray().filter(i=>!t.requests.find(s=>s.userId===i.userId));e.forEach(i=>this.participants.waitlisted.add(new Ai(this.context,{id:i.peerId,displayName:i.displayName,audioMuted:!0,videoEnabled:!1,audioTrack:void 0,videoTrack:void 0,stageStatus:"OFF_STAGE",userId:i.userId,flags:{},isHost:!1,customParticipantId:i.customParticipantId,picture:i.picture,metadata:{preset_name:i.presetName}},this.self,this.roomSocketHandler))),n.forEach(i=>this.participants.waitlisted.delete(i.id))}get maxPreferredStreams(){return this.participants.maxActiveParticipantsCount}selectPagePeers(t){return p(this,null,function*(){const{compulsoryPeers:e}=this.selectedPeers,n=e.filter(c=>this.participants.joined.has(c)),i=Array.from(this.participants.pinned.keys()).filter(c=>!n.includes(c)),s=Array.from(this.participants.joined.toArray().filter(c=>c.stageStatus==="ON_STAGE").map(c=>c.id)),r=Math.max((t-1)*(this.maxPreferredStreams-n.length-i.length)),a=t*(this.maxPreferredStreams-n.length-i.length);return n.concat(i,s.slice(r,a))})}selectActivePeers(){const t=new Map,e=Array.from(this.participants.joined.toArray().filter(h=>h.stageStatus==="ON_STAGE").map(h=>(t.set(h.id,!0),h.id))),n=this.selectedPeers.peers,i=this.participants.pinned.toArray().reduce((h,u)=>(u.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(u.id):h.push(u.id),h),[]),s=this.self.stageStatus==="ON_STAGE"?1:0,r=this.participants.maxActiveParticipantsCount-s,a=new Set(n.concat(i).filter(h=>h!==this.self.id&&t.has(h)));let c=Array.from(a);const d=r-a.size;if(d>=0){const h=e.filter(u=>!a.has(u)&&u!==this.self.id).slice(0,d);c=Array.from(a).concat(h)}else c=c.slice(0,r);return c}updateActive(t,e){return p(this,null,function*(){const{page:n,createAllConsumers:i}=e!=null?e:{};let{strategies:s}=e!=null?e:{},r,a;switch(t){case"PAGINATED":{if(!n)return;r=yield this.selectPagePeers(n),m.debug("ParticipantController::updateActive::updating_current_page_peers",{peerIds:r}),s!=null||(s={video:this.updateParticipantsMap.bind(this)}),a=this.updateConsumersDebounced;break}case"ACTIVE_GRID":{r=this.selectActivePeers(),m.debug("ParticipantController::updateActive::updating_current_selected_peers",{peerIds:r}),s!=null||(s={video:this.updateParticipantsMapMinReplacement.bind(this),audio:this.updateParticipantsMap.bind(this)}),a=this.updateConsumers;break}default:throw new Error(`View mode ${t} not supported`)}let c,d;const h=this.updateGrid(r,s);i?(c=this.mapPeerIdsToProducers(r,["audio","video","screenshare"]),d=[]):(c=[...this.mapPeerIdsToProducers([...h.video.add],["video"]),...this.mapPeerIdsToProducers([...h.audio.add],["audio"])],d=[...this.mapPeerIdsToProducers([...h.video.remove],["video"]),...this.mapPeerIdsToProducers([...h.audio.remove],["audio"])]),!(c.length===0&&d.length===0)&&a(c,d)})}computeActivateParticipants(t,e){const n=t.map((s,r)=>({peerId:s,priority:r+1})),i=e==null?void 0:e.map((s,r)=>({peerId:s,priority:-(r+1)}));n.push(...i!=null?i:[]),n.length>0&&this.updateActiveParticipantsWithPriorities(n)}fromSocketService(t){const e=D0.formatSocketServiceMessage(t);return new Ai(this.context,ee(H({},e),{isHost:!1,videoEnabled:!1,audioMuted:!0,videoTrack:void 0,audioTrack:void 0}),this.self,this.roomSocketHandler)}updatePipSource(t,e){var n,i;e?(n=this.pip)==null||n.enableSource(t):(i=this.pip)==null||i.disableSource(t)}onMediaJoined(t,e,n){if(!this.mediaJoined||t===this.self.id)return;const i=this.participants.joined.get(t);if(!i){m.warn(`Received media.peerJoinedBroadcast for non-existent peer ${t}`);return}e.forEach(s=>{s.kind===ci.AUDIO&&!s.screenShare?i.setAudioEnabled(!s.pause):s.kind===ci.VIDEO&&!s.screenShare&&(i.setVideoEnabled(!s.pause),this.updatePipSource(i.id,!s.pause)),i.producers.push(ee(H({},s),{producingTransportId:s.producingTransportId,kind:s.kind===ci.AUDIO?"audio":"video",producingPeerId:t,mimeType:s.mimeType}))}),this.roomNodeClient.handlePeerCapabilities(t,n),re.hasFeature(ue.FORCE_VIDEO_CODEC)||this.roomNodeClient.shareWebcam(this.self.videoTrack)}updateParticipantsMapMinReplacement(t,e){const n=Array.from(t.keys()),i=new Map(t),s=[],r=[],a=new Set(e),c=[];return n.forEach((d,h)=>{(!a.has(d)||!this.participants.joined.get(d))&&c.push(h)}),e.forEach(d=>{if(t.get(d))return;if(n.length<e.length){n.push(d),s.push(d);return}const h=c.shift();r.push(n[h]),n[h]=d,s.push(n[h])}),n.forEach((d,h)=>{a.has(d)||r.concat(n.splice(h,1))}),Array.from(t.keys()).forEach(d=>{t.delete(d,!a.has(d))}),n.forEach(d=>{if(!this.participants.joined.get(d)){m.warn("updateActiveParticipants::participant_not_in_joined_list",{dyteParticipant:{id:d}});return}t.add(this.participants.joined.get(d),!i.get(d))}),t.emit("participantsUpdate"),[s,r]}updateParticipantsMap(t,e){const n=Array.from(t.keys()),i=[],s=[];return n.forEach(r=>{e.includes(r)||(t.delete(r,!0),s.push(r))}),e.forEach(r=>{t.get(r)||(t.add(this.participants.joined.get(r)),i.push(r))}),t.emit("participantsUpdate"),[i,s]}updatePinnedParticipants(){this.participants.pinned.forEach(t=>{t.setIsPinned(!1),this.participants.pinned.delete(t.id)})}setupEventsGlobal(){this.roomSocketHandler.on(z.joinRoom,({peer:t})=>{if(!t.waitlisted){const e=re.hasFeature(ue.DEBUG_SOCKET_JOIN);e&&m.info("Processing socket join",{peers:t.peerId}),this.onParticipantJoined(this.fromSocketService(t)),e&&m.info("Processed socket join",{peers:t.peerId})}}),this.roomSocketHandler.on(z.leaveRoom,t=>{const{peerId:e}=t.peer;this.selectedPeers.delete(e),this.onParticipantLeave(e)}),L.on(x.SOCKET_SERVICE_ROOM_JOINED,()=>{this.self.permissions.acceptWaitingRequests&&this.roomSocketHandler.getWaitingRoomRequests()}),this.self.permissions.on("permissionsUpdate",t=>{const{acceptWaitingRequests:e}=t;e!==void 0&&(e?this.roomSocketHandler.getWaitingRoomRequests():this.participants.waitlisted.clear())}),L.on(x.SOCKET_SERVICE_DISCONNECTED,()=>{this.participants.joined.clear(),this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear(),this.participants.pinned.clear(),this.participants.currentPage=0,this.participants.viewMode="ACTIVE_GRID",this.participants.emit("viewModeChanged",{viewMode:"ACTIVE_GRID",currentPage:this.participants.currentPage,pageCount:this.participants.pageCount})}),L.on(x.CONSUMER_PAUSED,({id:t})=>{this.processConsumerPaused(t)}),L.on(x.CONSUMER_RESUMED,({id:t})=>{this.processConsumerResumed(t)}),L.on(x.NEW_CONSUMER,({id:t})=>{this.processNewConsumer(t)}),L.on(x.CONSUMER_CLOSED,({id:t})=>{this.processConsumerClosed(t)}),L.on(x.ROOM_MESSAGE,t=>p(this,[t],function*({payload:e,type:n,timestamp:i}){this.participants.emit("broadcastedMessage",{type:n,payload:e,timestamp:i})})),L.on(x.MESSAGE,t=>p(this,[t],function*({payload:e,type:n,timestamp:i}){n!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:n,payload:e,timestamp:i})})),L.on(x.LOW_CONSUMER_SCORE,({peerId:t,score:e,kind:n})=>{const i=this.participants.joined.get(t);i&&(i.emit("poorConnection",{score:e,kind:n}),this.participants.emit("poorConnection",{participantId:t,score:e,kind:n}))}),L.on(x.CONSUMER_SCORE_UPDATE,({score:t,kind:e,appData:n,peerId:i,scoreStats:s})=>{var r;const a=e==="video"&&((r=n==null?void 0:n.screenShare)!=null?r:!1),c=this.participants.joined.get(i);c&&(c.emit("mediaScoreUpdate",{kind:e,isScreenshare:a,score:t,participantId:i,scoreStats:s}),this.participants.emit("mediaScoreUpdate",{kind:e,isScreenshare:a,score:t,participantId:i,scoreStats:s}))}),L.onAsync(x.KICK_PEER,t=>p(this,[t],function*({peerId:e}){const n=this.participants.joined.get(e);this.roomNodeClient.kick(e),yield this.roomSocketHandler.kick(e),n?n.emit("kicked"):this.participants.joined.emit("kicked",{id:e})})),L.on(x.UPDATE_ACTIVE,(...t)=>p(this,[...t],function*({page:e,createAllConsumers:n}={}){yield this.updateActive(e?"PAGINATED":"ACTIVE_GRID",{page:e,createAllConsumers:n})}))}onParticipantPinned(t){return p(this,null,function*(){if(!t){this.self.isPinned&&this.self.setIsPinned(!1),this.participants.pinned.size!==0&&this.updatePinnedParticipants();return}if(t===this.self.id){this.participants.pinned.size!==0&&this.updatePinnedParticipants(),this.self.setIsPinned(!0);return}const e=this.participants.joined.get(t);this.self.isPinned&&this.self.setIsPinned(!1),this.updatePinnedParticipants(),e.setIsPinned(!0),this.participants.pinned.add(e)})}onParticipantJoined(t){return p(this,null,function*(){var e,n,i;if(this.self.id!==t.id&&!((e=t.flags)!=null&&e.recorder)&&!((n=t.flags)!=null&&n.hidden_participant)&&!((i=t.flags)!=null&&i.hiddenParticipant)&&(this.participants.videoSubscribed.delete(t.id),this.participants.audioSubscribed.delete(t.id),this.participants.joined.add(t),this.participants.waitlisted.delete(t.id),t.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&L.emit(x.UPDATE_STAGE_REQUESTS,{request:{displayName:t.name,userId:t.userId,peerId:t.id},add:!0})),L.emit(x.PEER_JOINED_INTERNAL,t),this.self.config.viewType===zt.Webinar&&t.stageStatus!=="ON_STAGE"||this.roomNodeClient===void 0||this.participants.videoSubscribed.size>=this.maxPreferredStreams)return;const s=this.participants.currentPage;this.updateActive(s?"PAGINATED":"ACTIVE_GRID",{page:s})})}onParticipantLeave(t){return p(this,null,function*(){const e=this.participants.joined.get(t);this.participants.joined.delete(t,!0,!0),this.participants.pinned.delete(t,!0,!0),this.participants.waitlisted.delete(t,!0,!0),this.roomNodeClient&&(this.roomNodeClient.handlePeerLeaving(t),this.roomNodeClient.closeConsumers(e==null?void 0:e.producers)),e&&e.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&L.emit(x.UPDATE_STAGE_REQUESTS,{request:{displayName:e.name,userId:e.userId,peerId:e.id},add:!1});const{currentPage:n}=this.participants,i=this.maxPreferredStreams*(n-1),s=this.participants.videoSubscribed.get(t);i===0?this.participants.setViewMode("ACTIVE_GRID"):this.participants.joined.size<=i?n===2?this.participants.setViewMode("ACTIVE_GRID"):this.participants.setPage(n-1):s&&this.updateActive(n?"PAGINATED":"ACTIVE_GRID",{page:n})})}processMedia(t){var e;const n=this.roomNodeClient.getConsumers(),{peerId:i,kind:s,appData:r,track:a,producerId:c,rtpReceiver:d,paused:h}=(e=n.get(t))!=null?e:{};if(!i)return m.warn("processMedia::Peer ID is undefined",{consumer:{id:t,kind:s,peerId:i,appData:{supportsRemoteControl:!!(r!=null&&r.supportsRemoteControl),screenShare:!!(r!=null&&r.screenShare)},remotelyPaused:h,producerId:c}}),{};const u=r;return s==="video"&&u.screenShare!==!0&&this.videoPeerConsumerMap.set(i,t),m.info("ParticipantController::processMedia",{consumer:{id:t,peerId:i,kind:s,appData:u,remotelyPaused:h,producerId:c}}),this.consumerPeerMap.set(t,{type:s,peerId:i,appData:u,remotelyPaused:h,producerId:c}),{peerId:i,kind:s,appData:u,remotelyPaused:h,track:a,producerId:c,rtpReceiver:d}}processConsumerClosed(t){const{peerId:e,type:n,appData:i,remotelyPaused:s,producerId:r}=this.consumerPeerMap.get(t)||{},a=this.participants.joined.get(e);if(m.info("ParticipantController::processConsumerClosed",{consumer:{id:t,peerId:e,appData:i,kind:n,remotelyPaused:s,producerId:r}}),this.consumerPeerMap.delete(t),n==="video"&&i.screenShare!==!0&&this.videoPeerConsumerMap.delete(e),!a)return;const c=[];i&&i.screenShare?(a.setScreenShareEnabled(!1),ne.consumerSharedMediaState(t,{screen:!1}),a.screenShareTracks.video&&c.push(a.screenShareTracks.video.id),a.screenShareTracks.audio&&c.push(a.screenShareTracks.audio.id),a.screenShareTracks={audio:void 0,video:void 0}):n==="audio"?(a.setAudioEnabled(!1),a.audioTrack&&c.push(a.audioTrack.id),ne.consumerSharedMediaState(t,{audio:!1}),a.audioTrack=void 0):n==="video"&&(a.setVideoEnabled(!1),this.updatePipSource(a.id,!1),a.videoTrack&&c.push(a.videoTrack.id),ne.consumerSharedMediaState(t,{video:!1}),a.videoTrack=void 0),i.e2ee&&c.forEach(d=>{L.emit(x.E2EE_INACTIVE_CONSUMER,{peerId:e,trackId:d})})}processConsumerResumed(t){const{peerId:e,kind:n,appData:i,track:s,remotelyPaused:r,producerId:a,rtpReceiver:c}=this.processMedia(t);if(!e)return;m.info("ParticipantController::processConsumerResumed",{consumer:{id:t,peerId:e,kind:n,appData:i,remotelyPaused:r,producerId:a}});const d=this.participants.joined.get(e);if(d){if(i.e2ee&&L.emit(x.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:c,track:s}),i.screenShare){n==="video"?d.screenShareTracks.video=s:n==="audio"&&(d.screenShareTracks.audio=s),d.setScreenShareEnabled(!0),ne.consumerSharedMediaState(t,{screen:!0});return}n==="video"?(d.videoTrack=s,d.setVideoEnabled(!0),this.updatePipSource(d.id,!0),ne.consumerSharedMediaState(t,{video:!0})):n==="audio"&&(d.audioTrack=s,d.setAudioEnabled(d.audioEnabled),ne.consumerSharedMediaState(t,{audio:d.audioEnabled}))}}processConsumerPaused(t){m.info(`ParticipantController::processConsumerPaused called for consumerId: ${t}`);const{peerId:e,kind:n,track:i,appData:s,remotelyPaused:r,producerId:a}=this.processMedia(t);if(!e)return;m.info("ParticipantController::processConsumerPaused",{consumer:{id:t,peerId:e,kind:n,appData:s,remotelyPaused:r,producerId:a}});const c=this.participants.joined.get(e);c&&(i&&s.e2ee&&L.emit(x.E2EE_INACTIVE_CONSUMER,{peerId:e,trackId:i.id}),n==="video"?(c.videoTrack=i,c.setVideoEnabled(!1),this.updatePipSource(c.id,!1),ne.consumerSharedMediaState(t,{video:!1})):n==="audio"&&(c.audioTrack=i,c.setAudioEnabled(c.audioEnabled),ne.consumerSharedMediaState(t,{audio:c.audioEnabled})))}processNewConsumer(t){const{peerId:e,kind:n,remotelyPaused:i,track:s,appData:r,producerId:a,rtpReceiver:c}=this.processMedia(t);if(!e)return;m.info("ParticipantController::processNewConsumer",{consumer:{id:t,peerId:e,kind:n,remotelyPaused:i,appData:r,producerId:a}});const d=this.participants.joined.get(e);if(d){if(r.screenShare){n==="video"?d.screenShareTracks.video=s:n==="audio"&&(d.screenShareTracks.audio=s),(!i||this.self.permissions.isRecorder||re.hasFeature(ue.SCREEENSHARE_ERR_HACK))&&d.setScreenShareEnabled(!0),r.supportsRemoteControl&&(d.supportsRemoteControl=!0),this.participants.broadcastMessage("screenshareConsumerCreated",{producerId:a,peerId:e,screenShare:!0,consumerId:t,consumerPeerId:this.self.id}),m.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:t,peerId:e,kind:n,remotelyPaused:i,appData:r,producerId:a}});return}n==="video"?(d.videoTrack=s,i||(d.setVideoEnabled(!0),this.updatePipSource(d.id,!0)),ne.consumerSharedMediaState(t,{video:!i})):n==="audio"&&(d.audioTrack=s,i||d.setAudioEnabled(!0),ne.consumerSharedMediaState(t,{audio:!i})),!i&&r.e2ee&&L.emit(x.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:c,track:s})}}static formatSocketServiceMessage(t){var e,n,i,s,r,a;if(!t)return;const c=sm(t.stageType);return{id:t.peerId,userId:t.userId,name:t.displayName,displayName:t.displayName,stageType:c,customParticipantId:t.customParticipantId,presetId:t.presetId,picture:t.displayPictureUrl,waitlisted:t.waitlisted,stageStatus:c,metadata:{preset_name:(e=t.flags)==null?void 0:e.presetName},recorderType:(n=t.flags)==null?void 0:n.recorderType,flags:{hiddenParticipant:(i=t.flags)==null?void 0:i.hiddenParticipant,hidden_participant:(s=t.flags)==null?void 0:s.hiddenParticipant,recorder:((r=t.flags)==null?void 0:r.recorderType)!==void 0&&((a=t.flags)==null?void 0:a.recorderType)!=="NONE"}}}mapPeerIdsToProducers(t,e){const n=(i,s)=>i.filter(({kind:r,screenShare:a})=>s.includes(r)||a&&s.includes("screenshare"));return t.flatMap(i=>{const s=this.participants.joined.get(i);if(s)return n(s.producers,e)}).filter(i=>!!i)}updateGrid(t,e){let n=[],i=[],s=[],r=[];return e.video&&([n,s]=e.video(this.participants.videoSubscribed,t)),e.audio&&([i,r]=e.audio(this.participants.audioSubscribed,t)),{video:{add:n,remove:s},audio:{add:i,remove:r}}}onSelectedPeers(t,e){return p(this,null,function*(){this.participants.viewMode==="ACTIVE_GRID"&&this.computeActivateParticipants(t,e)})}updateActiveParticipantsWithPriorities(t,e=!1){if(!this.mediaJoined){m.warn("Skipped::ParticipantController::updateActiveParticipantsWithPriorities",{roomJoined:this.mediaJoined});return}t.forEach(i=>{this.selectedPeers.add(i.peerId,i.priority)});const n=this.selectedPeers.activeSpeakerPeers.at(0);n!==void 0&&n!==this.participants.lastActiveSpeaker&&(this.participants.lastActiveSpeaker=n,this.participants.emit("activeSpeaker",{peerId:n,volume:1})),e&&(this.participants.viewMode==="ACTIVE_GRID"?this.updateActive("ACTIVE_GRID"):this.participants.viewMode==="PAGINATED"&&this.updateActive("ACTIVE_GRID",{strategies:{audio:this.updateParticipantsMap.bind(this)}}))}};let Di=D0;Rr([k.trace("ParticipantController.setupEvents")],Di.prototype,"setupEvents",1);Rr([k.trace("ParticipantController.setupEvents")],Di.prototype,"setupEventsGlobal",1);Rr([k.trace("ParticipantController.processMedia")],Di.prototype,"processMedia",1);Rr([k.trace("ParticipantController.processConsumerClosed")],Di.prototype,"processConsumerClosed",1);Rr([k.trace("ParticipantController.processConsumerResumed")],Di.prototype,"processConsumerResumed",1);Rr([k.trace("ParticipantController.processConsumerPaused")],Di.prototype,"processConsumerPaused",1);Rr([k.trace("ParticipantController.processNewConsumer")],Di.prototype,"processNewConsumer",1);const Me=qn(Xp().permissions);var Z,_o,Ko,Wh,tn,ln;const Io=class extends fn{constructor(t,e,n,i=!1){if(super(),S(this,tn),S(this,Z,void 0),S(this,_o,void 0),S(this,Ko,void 0),S(this,Wh,s=>{var r,a,c;const d=s,{chat:h,connectedMeetings:u,plugins:g,polls:E,media:b}=d,w=Pl(d,["chat","connectedMeetings","plugins","polls","media"]);if(h&&(h.private&&Qi(o(this,Z).chat.private,h.private),h.public&&Qi(o(this,Z).chat.public,h.public),this.emit("chatUpdate")),u&&Qi(o(this,Z).connectedMeetings,u),b){const M=F=>{switch(F){case vs.NONE:return se.Allowed;case vs.ALLOWED:return se.Allowed;case vs.NOT_ALLOWED:return se.NotAllowed;case vs.CAN_REQUEST:return se.CanRequest;default:return}},D={audio:void 0,video:void 0,screenshare:void 0};(r=b.audio)!=null&&r.canProduce&&(D.audio={canProduce:M(b.audio.canProduce)}),(a=b.video)!=null&&a.canProduce&&(D.video={canProduce:M(b.video.canProduce)}),(c=b.screenshare)!=null&&c.canProduce&&(D.screenshare={canProduce:M(b.screenshare.canProduce)}),Qi(o(this,Z).media,D)}g&&(Qi(o(this,Z).plugins,g),this.emit("pluginsUpdate")),E&&(Qi(o(this,Z).polls,E),this.emit("pollsUpdate")),Object.keys(w).length!==0&&Qi(o(this,Z),w),this.emit("permissionsUpdate",s)}),!e)throw m.error("DytePermissionsPreset::load_preset_permissions_failed"),new O("Could not load preset permissions.","0904");T(this,Ko,t),T(this,_o,n),T(this,Z,e),i&&this.setupEvents()}setupEvents(){L.on(x.UPDATE_PERMISSIONS,o(this,Wh))}static fromResponse(t,e,n){return new Io(n,t,e,!0)}static default(t,e){return new Io(t,Me,e)}static init(t,e,n){let i;return n?i=new Io(t,n,e,!0):i=new Io(t,Me,e),i}get mediaRoomType(){const{sfu:t}=o(this,Ko).getValue("roomNodeOptions");return t===bt.CF?"CF":"HIVE"}get stageEnabled(){var t;return((t=o(this,Z))==null?void 0:t.stageEnabled)||o(this,_o)===zt.Webinar||o(this,_o)===zt.Livestream}get acceptStageRequests(){var t,e;return this.stageEnabled?((t=o(this,Z))==null?void 0:t.acceptStageRequests)||((e=o(this,Z))==null?void 0:e.canAcceptProductionRequests):!1}get stageAccess(){var t,e,n;return((t=o(this,Z))==null?void 0:t.stageAccess)===se.NotAllowed?se.NotAllowed:((e=o(this,Z))==null?void 0:e.stageAccess)===se.CanRequest?se.CanRequest:((n=o(this,Z))==null?void 0:n.stageAccess)===se.Allowed||o(this,Z).media.audio.canProduce===se.Allowed||o(this,Z).media.video.canProduce===se.Allowed||o(this,Z).media.screenshare.canProduce===se.Allowed?se.Allowed:o(this,Z).media.audio.canProduce===se.CanRequest||o(this,Z).media.video.canProduce===se.CanRequest||o(this,Z).media.screenshare.canProduce===se.CanRequest?se.CanRequest:se.NotAllowed}get acceptWaitingRequests(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.acceptWaitingRequests)!=null?e:Me.acceptWaitingRequests}get requestProduceVideo(){var t,e,n;return((n=(e=(t=o(this,Z))==null?void 0:t.media)==null?void 0:e.video)==null?void 0:n.canProduce)===se.CanRequest}get requestProduceAudio(){var t,e,n;return((n=(e=(t=o(this,Z))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:n.canProduce)===se.CanRequest}get requestProduceScreenshare(){var t,e,n;return((n=(e=(t=o(this,Z))==null?void 0:t.media)==null?void 0:e.screenshare)==null?void 0:n.canProduce)===se.CanRequest}get canAllowParticipantAudio(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.disableParticipantAudio)!=null?e:Me.disableParticipantAudio}get canAllowParticipantScreensharing(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.canAcceptProductionRequests)!=null?e:Me.canAcceptProductionRequests}get canAllowParticipantVideo(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.disableParticipantVideo)!=null?e:Me.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.kickParticipant)!=null?e:Me.kickParticipant}get pinParticipant(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.pinParticipant)!=null?e:Me.pinParticipant}get canRecord(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.canRecord)!=null?e:Me.canRecord}get waitingRoomType(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.waitingRoomType)!=null?e:Me.waitingRoomType}get waitingRoomBehaviour(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.waitingRoomType)!=null?e:Me.waitingRoomType}get plugins(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.plugins)!=null?e:Me.plugins}get polls(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.polls)!=null?e:Me.polls}get produceVideo(){return this.canProduceVideo}get requestProduce(){return o(this,Z).media.audio.canProduce===se.CanRequest||o(this,Z).media.video.canProduce===se.CanRequest||o(this,Z).media.screenshare.canProduce===se.CanRequest}get canProduceVideo(){var t;const e=(t=o(this,Z).media.video.canProduce)!=null?t:Me.media.video.canProduce;return this.stageEnabled&&(o(this,tn,ln)==="ACCEPTED_TO_JOIN_STAGE"||o(this,tn,ln)==="ON_STAGE")&&e===se.CanRequest?se.Allowed:this.stageEnabled&&(o(this,tn,ln)==="OFF_STAGE"||o(this,tn,ln)==="REQUESTED_TO_JOIN_STAGE")&&e===se.Allowed?se.NotAllowed:e}get produceScreenshare(){return this.canProduceScreenshare}get canProduceScreenshare(){var t;const e=(t=o(this,Z).media.screenshare.canProduce)!=null?t:Me.media.screenshare.canProduce;return this.stageEnabled&&(o(this,tn,ln)==="ACCEPTED_TO_JOIN_STAGE"||o(this,tn,ln)==="ON_STAGE")&&e===se.CanRequest?se.Allowed:this.stageEnabled&&(o(this,tn,ln)==="OFF_STAGE"||o(this,tn,ln)==="REQUESTED_TO_JOIN_STAGE")&&e===se.Allowed?se.NotAllowed:e}get produceAudio(){return this.canProduceAudio}get canProduceAudio(){var t;const e=(t=o(this,Z).media.audio.canProduce)!=null?t:Me.media.audio.canProduce;return this.stageEnabled&&(o(this,tn,ln)==="ACCEPTED_TO_JOIN_STAGE"||o(this,tn,ln)==="ON_STAGE")&&e===se.CanRequest?se.Allowed:this.stageEnabled&&(o(this,tn,ln)==="OFF_STAGE"||o(this,tn,ln)==="REQUESTED_TO_JOIN_STAGE")&&e===se.Allowed?se.NotAllowed:e}get chatPublic(){var t,e,n;return(n=(e=(t=o(this,Z))==null?void 0:t.chat)==null?void 0:e.public)!=null?n:Me.chat.public}get chatPrivate(){var t,e,n;return(n=(e=(t=o(this,Z))==null?void 0:t.chat)==null?void 0:e.private)!=null?n:Me.chat.private}get chatChannel(){var t,e,n;return(n=(e=(t=o(this,Z))==null?void 0:t.chat)==null?void 0:e.channel)!=null?n:Me.chat.channel}get chatMessage(){var t,e,n;return(n=(e=(t=o(this,Z))==null?void 0:t.chat)==null?void 0:e.message)!=null?n:Me.chat.message}get connectedMeetings(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.connectedMeetings)!=null?e:Me==null?void 0:Me.connectedMeetings}get hiddenParticipant(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.hiddenParticipant)!=null?e:Me.hiddenParticipant}get showParticipantList(){var t;return(t=o(this,Z).showParticipantList)!=null?t:Me.showParticipantList}get canChangeParticipantRole(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.canChangeParticipantPermissions)!=null?e:Me.canChangeParticipantPermissions}get canChangeParticipantPermissions(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.canChangeParticipantPermissions)!=null?e:Me.canChangeParticipantPermissions}get canChangeTheme(){return!1}get canPresent(){return o(this,Z).media.audio.canProduce===se.Allowed||o(this,Z).media.video.canProduce===se.Allowed||o(this,Z).media.screenshare.canProduce===se.Allowed}get acceptPresentRequests(){return this.acceptStageRequests}get canEditDisplayName(){var t;return(t=o(this,Z).canEditDisplayName)!=null?t:!1}get maxScreenShareCount(){return 1}get isRecorder(){return o(this,Z).isRecorder}get canSpotlight(){return o(this,Z).canSpotlight}get canLivestream(){return o(this,Z).canLivestream}get transcriptionEnabled(){return o(this,Z).transcriptionEnabled}};let y2=Io;Z=new WeakMap,_o=new WeakMap,Ko=new WeakMap,Wh=new WeakMap,tn=new WeakSet,ln=function(){return o(this,Ko).getValue("stageStatus")};var N0;class E2 extends fn{constructor(){super(...arguments),y(this,"localMediaHandler"),S(this,N0,void 0)}updatePermission(){return p(this,null,function*(){var e,n;const i=(h,u)=>{this.mediaPermissions[h]=u;const g={message:this.mediaPermissions[h],kind:h};u==="DENIED"?L.emit(x.MEDIA_PERMISSION_ERROR,g):L.emit(x.MEDIA_PERMISSION_UPDATE,g)};if(Be.getName()==="firefox")return;const s="microphone",r="camera",a=yield(e=navigator==null?void 0:navigator.permissions)==null?void 0:e.query({name:s}),c=yield(n=navigator==null?void 0:navigator.permissions)==null?void 0:n.query({name:r}),d=(h,u)=>{switch(u){case"granted":i(h,"ACCEPTED");break;case"denied":i(h,"DENIED");break;case"prompt":i(h,"NOT_REQUESTED");break}this.localMediaHandler.repopulateAvailableDevices()};a&&(a.onchange=()=>d("audio",a.state)),c&&(c.onchange=()=>d("video",c.state))})}populateMediaPermissionsInCallstats(e){return p(this,arguments,function*({message:n,kind:i}){switch(i){case"audio":{ne.mediaPermission("AUDIO",n),ne.mediaPermission("SPEAKER",n);break}case"video":{ne.mediaPermission("VIDEO",n);break}case"screenshare":{ne.mediaPermission("SCREENSHARE",n);break}}})}init(){return p(this,arguments,function*(e={},n=!1,i=null){var s,r,a,c,d,h;if(Be.init(),!this.localMediaHandler)try{let u=!0;if(i!=null&&i.getValue("defaults").mediaHandler)u=!1,this.localMediaHandler=i.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:g}=navigator;this.localMediaHandler=yield g.init()}else this.localMediaHandler=new on(i,e.constraints,(s=i==null?void 0:i.getValue("defaults"))==null?void 0:s.isNonPreferredDevice,(r=i==null?void 0:i.getValue("defaults"))==null?void 0:r.autoSwitchAudioDevice);if(L.on(x.MEDIA_PERMISSION_UPDATE,g=>p(this,null,function*(){if(this.populateMediaPermissionsInCallstats({message:g.message,kind:g.kind}),g.message==="NOT_REQUESTED")switch(g==null?void 0:g.kind){case"audio":this.rawAudioTrack&&(m.info("Disabling audio due to media permission update"),this.disableAudio());break;case"video":this.rawVideoTrack&&(m.info("Disabling video due to media permission update"),this.disableVideo());break;default:break}this.emit("mediaPermissionUpdate",g)})),L.on(x.MEDIA_PERMISSION_ERROR,g=>p(this,null,function*(){const{kind:E,message:b,constraints:w}=g;this.populateMediaPermissionsInCallstats({message:b,kind:E}),E==="audio"?(m.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):E==="video"&&(m.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),m.error("SelfController::mediaPermissionError",{error:{message:b},constraints:w,mediaPermissionsErrors:{kind:E,message:b}}),this.emit("mediaPermissionError",g),this.emit("mediaPermissionUpdate",{message:b,kind:E})})),u){m.info(`Setting up DyteSelfMedia streams using media handler. audio:${(a=e==null?void 0:e.audio)!=null?a:!0} video:${(c=e==null?void 0:e.video)!=null?c:!0}`);const g=this.localMediaHandler.setupStreams({video:(d=e==null?void 0:e.video)!=null?d:!0,audio:(h=e==null?void 0:e.audio)!=null?h:!0});n||(yield g)}}catch(u){m.error("DyteSelf::init::Failed To Setup Streams",{error:{name:u.name,message:u.message}})}})}get audioTrack(){return this.localMediaHandler.audioTrack}get rawAudioTrack(){return this.localMediaHandler.rawAudioTrack}get mediaPermissions(){return this.localMediaHandler.permissions}addAudioMiddleware(e){return p(this,null,function*(){return this.localMediaHandler.addAudioMiddleware(e)})}removeAudioMiddleware(e){return p(this,null,function*(){return this.localMediaHandler.removeAudioMiddleware(e)})}removeAllAudioMiddlewares(){return p(this,null,function*(){return this.localMediaHandler.removeAllAudioMiddlewares()})}get videoTrack(){return this.localMediaHandler.videoTrack}get rawVideoTrack(){return this.localMediaHandler.rawVideoTrack}addVideoMiddleware(e){return p(this,null,function*(){return this.localMediaHandler.addVideoMiddleware(e)})}setVideoMiddlewareGlobalConfig(){return p(this,arguments,function*(e={disablePerFrameCanvasRendering:!1}){return this.localMediaHandler.setVideoMiddlewareGlobalConfig(e)})}removeVideoMiddleware(e){return p(this,null,function*(){return this.localMediaHandler.removeVideoMiddleware(e)})}removeAllVideoMiddlewares(){return p(this,null,function*(){return this.localMediaHandler.removeAllVideoMiddlewares()})}get screenShareTracks(){return this.localMediaHandler.screenShareTracks}get audioEnabled(){return this.localMediaHandler.audioEnabled}get videoEnabled(){return this.localMediaHandler.videoEnabled}get screenShareEnabled(){return this.localMediaHandler.screenShareEnabled}enableAudio(){return p(this,null,function*(){yield this.localMediaHandler.enableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})}enableVideo(){return p(this,null,function*(){yield this.localMediaHandler.enableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})}disableAudio(){return p(this,null,function*(){this.localMediaHandler.disableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})}enableScreenShare(){return p(this,null,function*(){yield this.localMediaHandler.enableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})}disableScreenShare(){return p(this,null,function*(){yield this.localMediaHandler.disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})}disableVideo(){return p(this,null,function*(){yield this.localMediaHandler.disableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})}getCurrentDevices(){return this.localMediaHandler.getCurrentDevices()}getAudioDevices(){return p(this,null,function*(){return yield this.localMediaHandler.getAudioDevices()})}getVideoDevices(){return p(this,null,function*(){return yield this.localMediaHandler.getVideoDevices()})}getSpeakerDevices(){return p(this,null,function*(){return yield this.localMediaHandler.getSpeakerDevices()})}getDeviceById(e,n){let i;return n==="audio"?i="audioinput":n==="video"?i="videoinput":n==="speaker"&&(i="audiooutput"),this.localMediaHandler.getDeviceById(e,i)}setDevice(e){return p(this,null,function*(){switch(e.kind){case"audioinput":try{yield this.localMediaHandler.setAudioDevice(e)}catch(n){}finally{this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":yield this.localMediaHandler.setSpeakerDevice(e);break;case"videoinput":try{yield this.localMediaHandler.setVideoDevice(e)}catch(n){}finally{this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})})}}N0=new WeakMap;const ro={},Cs={executeWithLock({methodName:t,lockName:e,timeout:n}){return(i,s,r)=>{const a=r.value;return r.value=function(...c){if(ro[e]){const u=new Error(`Unsupported concurrent calls on Dyte method: ${t}.`);throw u.name="UnsupportedConcurrentMethodExecution",m.error("DyteLocker::UnsupportedConcurrentMethodExecution",{error:{stack:u.stack},dyteLocker:{methodName:t,lockName:e}}),u}ro[e]=!0;const d=setTimeout(()=>delete ro[e],n),h=a.apply(this,c);return Promise.resolve(h).then(()=>{delete ro[e],clearTimeout(d)}).catch(()=>{delete ro[e],clearTimeout(d)}),h},r}}};var S2=Object.defineProperty,T2=Object.getOwnPropertyDescriptor,Xt=(t,e,n,i)=>{for(var s=i>1?void 0:i?T2(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&S2(e,n,s),s},ao,Zt,oo,pi,Vs,Wr,yt,It,ct,mt,co,lo,Zc,Gu,Bg;let wt=(Bg=class extends E2{constructor(t,e,n,i,s){var r;super(),S(this,Vs),S(this,yt),S(this,ct),S(this,Zc),y(this,"name"),y(this,"picture"),y(this,"customParticipantId"),y(this,"waitlistStatus"),S(this,ao,void 0),S(this,Zt,void 0),S(this,oo,void 0),y(this,"role"),y(this,"userId"),y(this,"organizationId"),y(this,"supportsRemoteControl",!1),y(this,"device"),S(this,pi,void 0),y(this,"hidden",!1),y(this,"presetName"),y(this,"roomState","init"),S(this,co,new Set),S(this,lo,new Set),T(this,pi,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=(r=e.customParticipantId)!=null?r:e.clientSpecificId,this.waitlistStatus="none",T(this,Zt,n),T(this,ao,i),this.hidden=!1,T(this,oo,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=Be.isElectron(),this.device=Be.getDeviceInfo(),this.presetName=s,i.viewType!==zt.Chat&&this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),Q(this,Zc,Gu).call(this)}get stageStatus(){return o(this,pi).getValue("stageStatus")}get id(){return o(this,pi).getValue("peerId")}static __init__(t,e,n,i,s,r=!1){return p(this,null,function*(){var a,c,d,h,u;let g=(c=(a=t.getValue("defaults"))==null?void 0:a.audio)!=null?c:!0,E=(h=(d=t.getValue("defaults"))==null?void 0:d.video)!=null?h:!0;n.canProduceAudio!=="ALLOWED"&&(g=!1),n.canProduceVideo!=="ALLOWED"&&(E=!1);const b=new wt(t,e,n,i,s);if(i.viewType===zt.Chat)return b;const w=RL(i.mediaConstraints);return Qi(w,(u=t.getValue("defaults"))==null?void 0:u.mediaConfiguration),yield b.init({audio:g,video:E,constraints:w},r,t),b.setupEvents(),b})}cleanupEvents(){this.removeAllListeners("videoUpdate"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("VIDEO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_LIST_UPDATED"),this.localMediaHandler.removeAllListeners("SCREENSHARE_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("SCREENSHARE_ENDED"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_SILENT"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_AUDIO"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_VIDEO"),o(this,Zt).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",Q(this,Zc,Gu)),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",()=>p(this,null,function*(){if(m.info("DyteSelf::setupEvents::AUDIO_TRACK_CHANGE",H({},ar(this))),o(this,ct,mt)&&this.audioEnabled)try{yield o(this,yt,It).shareMic(this.audioTrack)}catch(t){m.error("DyteSelf::setupEvents::Error while sharing mic",{error:t}),this.localMediaHandler.disableAudio()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})),this.localMediaHandler.on("VIDEO_TRACK_CHANGE",()=>p(this,null,function*(){if(m.info("DyteSelf::setupEvents::VIDEO_TRACK_CHANGE",H({},ar(this))),o(this,ct,mt)&&this.rawVideoTrack===void 0)m.info("DyteSelf::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&o(this,ct,mt))try{const t=yield o(this,yt,It).shareWebcam(this.videoTrack);t&&t.id!==this.videoTrack.id&&re.hasFeature(ue.EXP_RESHARE)&&(yield o(this,yt,It).shareWebcam(this.videoTrack))}catch(t){m.error("DyteSelf::setupEvents::failed shareWebcam",{error:t}),this.videoEnabled&&(yield this.localMediaHandler.disableVideo())}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})),this.localMediaHandler.on("DEVICE_CHANGE",t=>p(this,[t],function*({device:e}){this.emit("deviceUpdate",{device:e})})),this.localMediaHandler.on("DEVICE_LIST_UPDATED",t=>{this.emit("deviceListUpdate",t)}),this.localMediaHandler.on("SCREENSHARE_TRACK_CHANGE",()=>p(this,null,function*(){if(!o(this,ct,mt)){m.error("DyteSelf.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{yield o(this,yt,It).shareScreen(this.screenShareTracks)}catch(t){m.error("DyteSelf::setupEvents::Error while sharing screen",{error:t}),this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare())}m.info("DyteSelf::setupEvents::SCREENSHARE_TRACK_CHANGE",H({},ar(this))),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})),this.localMediaHandler.on("SCREENSHARE_ENDED",()=>p(this,null,function*(){m.log("Disabling screenshare due to SCREENSHARE_ENDED"),yield this.disableScreenShare(),m.info("DyteSelf::setupEvents::SCREENSHARE_ENDED",H({},ar(this)))})),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{ne.mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",()=>p(this,null,function*(){o(this,ct,mt)&&(yield o(this,yt,It).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),ne.videoOff()})),o(this,Zt).on("permissionsUpdate",t=>{var e,n,i;(e=t==null?void 0:t.media)!=null&&e.audio&&o(this,Zt).canProduceAudio!==se.Allowed&&(this.disableAudio(),m.info(`Disabled audio due to dynamic preset change: canProduceAudio: ${this.permissions.canProduceAudio}`)),(n=t==null?void 0:t.media)!=null&&n.video&&o(this,Zt).canProduceVideo!==se.Allowed&&(this.disableVideo(),m.info(`Disabled video due to dynamic preset change: canProduceVideo: ${this.permissions.canProduceVideo}`)),(i=t==null?void 0:t.media)!=null&&i.screenshare&&o(this,Zt).canProduceScreenshare!==se.Allowed&&(this.disableScreenShare(),m.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return o(this,Zt)}get config(){return o(this,ao)}get roomJoined(){var t;return o(this,ao).viewType===zt.Livestream&&this.stageStatus!=="ON_STAGE"?((t=o(this,pi).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:o(this,ct,mt)}setName(t){if(!t)throw new O("Name cannot be empty.","1103");this.name=t}setupTracks(){return p(this,arguments,function*(t={}){t.forceReset,yield this.disableAudio(),yield this.disableVideo(),this.localMediaHandler.removeAudioTrack(),this.localMediaHandler.removeVideoTrack(),t.audio&&(yield this.enableAudio()),t.video&&(yield this.enableVideo())})}destructMediaHandler(){return p(this,null,function*(){return this.localMediaHandler.destruct()})}removeDocumentEventListeners(){return p(this,null,function*(){return this.localMediaHandler.removeDocumentEventListeners()})}enableAudio(){return p(this,null,function*(){if(this.permissions.canProduceAudio!==se.NotAllowed&&!(o(this,Zt).canProduceAudio===se.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if(ne.audioOn(),yield this.localMediaHandler.enableAudio(),o(this,ct,mt)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{yield o(this,yt,It).shareMic(this.audioTrack)}catch(t){m.error("DyteSelf::enableAudio::Error while sharing mic",{error:t}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return;o(this,yt,It).unmuteSelf()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}})}enableVideo(){return p(this,null,function*(){if(o(this,Zt).canProduceVideo!==se.NotAllowed&&!(o(this,Zt).canProduceVideo===se.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if(ne.videoOn(),yield this.localMediaHandler.enableVideo(),o(this,ct,mt)&&this.stageStatus==="ON_STAGE")try{yield o(this,yt,It).shareWebcam(this.videoTrack)}catch(t){m.error("DyteSelf::enableVideo::Error while sharing video",{error:t}),this.videoEnabled&&this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),m.info("DyteSelf.enableVideo",H({},ar(this)))}})}updateVideoConstraints(t){return p(this,null,function*(){if(!this.localMediaHandler.updateVideoConstraints)throw new O("Unsupported","1102");yield this.localMediaHandler.updateVideoConstraints(t)})}enableScreenShare(){return p(this,null,function*(){if(!o(this,ct,mt))throw new O("Can`t enable screenshare without joining room","1105");if(o(this,Zt).canProduceScreenshare!==se.NotAllowed&&!(o(this,Zt).canProduceScreenshare===se.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.screenShareEnabled&&(yield this.localMediaHandler.enableScreenShare(),this.screenShareTracks.audio||this.screenShareTracks.video)){try{yield o(this,yt,It).shareScreen(this.screenShareTracks)}catch(t){m.error("DyteSelf::enableScreenShare::Error while sharing screen",{error:t}),this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare())}this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}})}updateScreenshareConstraints(t){return p(this,null,function*(){if(!this.localMediaHandler.updateScreenshareConstraints)throw new O("Unsupported","1102");yield this.localMediaHandler.updateScreenshareConstraints(t)})}disableAudio(){return p(this,null,function*(){this.audioEnabled&&(this.localMediaHandler.disableAudio(),o(this,ct,mt)&&o(this,yt,It).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),ne.audioOff())})}disableVideo(){return p(this,null,function*(){this.videoEnabled&&(yield this.localMediaHandler.disableVideo(),o(this,ct,mt)&&(yield o(this,yt,It).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),ne.videoOff())})}disableScreenShare(){return p(this,null,function*(){this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare(),o(this,ct,mt)&&(yield o(this,yt,It).disableScreenShare()),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))})}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var n;T(this,oo,t);const i=t?"pinned":"unpinned";(n=o(this,Vs,Wr))==null||n.updateSource(this.id,{pinned:t}),e&&this.emit(i,this)}get isPinned(){return o(this,oo)}pin(){return p(this,null,function*(){if(!o(this,ct,mt))throw new O("Can`t pin participants without joining room","1105");return this.show(),o(this,yt,It).pinPeer(this.id)})}unpin(){return p(this,null,function*(){if(!o(this,ct,mt))throw new O("Can`t unpin participants without joining room","1105");return o(this,yt,It).pinPeer(null)})}hide(){return p(this,null,function*(){if(!o(this,ct,mt))throw new O("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})})}show(){if(!o(this,ct,mt))throw new O("Can`t toggle participant tile without joining room","1105");this.hidden=!1,this.emit("toggleTile",{hidden:this.hidden})}setDevice(t){return p(this,null,function*(){var e,n,i;if(!t)throw new O("No device selected","1104");const s=this.getCurrentDevices();if(t.deviceId&&(((e=s==null?void 0:s.audio)==null?void 0:e.deviceId)===t.deviceId||((n=s==null?void 0:s.video)==null?void 0:n.deviceId)===t.deviceId||((i=s==null?void 0:s.speaker)==null?void 0:i.deviceId)===t.deviceId)&&(m.warn("DyteSelf.setDevice.setting_to_in_use_device",{devices:[t]}),re.hasFeature(ue.SKIP_SETTING_IN_USE_DEVICE)))throw new O("Cannot set device currently in use","1106");switch(t.kind){case"audioinput":try{yield this.localMediaHandler.setAudioDevice(t)}catch(r){o(this,ct,mt)&&(yield o(this,yt,It).muteSelf()),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":yield this.localMediaHandler.setSpeakerDevice(t);break;case"videoinput":try{yield this.localMediaHandler.setVideoDevice(t)}catch(r){o(this,ct,mt)&&(yield o(this,yt,It).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}})}cleanUpTracks(){var t,e,n,i;(t=this.audioTrack)==null||t.stop(),(e=this.rawAudioTrack)==null||e.stop(),(n=this.videoTrack)==null||n.stop(),(i=this.rawVideoTrack)==null||i.stop()}registerVideoElement(t,e=!1){var n,i;e?o(this,co).add(t):o(this,lo).add(t),this.updateVideo(t),e||(i=o(this,Vs,Wr))==null||i.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(n=this.raised)!=null?n:!1)}deregisterVideoElement(t,e=!1){t.srcObject=void 0,e?o(this,co).delete(t):(o(this,lo).delete(t),o(this,Vs,Wr).removeSource(this.id))}updateVideo(t,e=!1){var n,i,s;if(this.videoEnabled){if(this.videoTrack==null)return;const r=(n=t.srcObject)==null?void 0:n.getTracks()[0];if((r==null?void 0:r.id)===this.videoTrack.id)return;const a=new MediaStream;a.addTrack(this.videoTrack),t.srcObject=a,e||(i=o(this,Vs,Wr))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(s=o(this,Vs,Wr))==null||s.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},ao=new WeakMap,Zt=new WeakMap,oo=new WeakMap,pi=new WeakMap,Vs=new WeakSet,Wr=function(){return o(this,pi).getValue("pip")},yt=new WeakSet,It=function(){return o(this,pi).getValue("roomNodeClient")},ct=new WeakSet,mt=function(){var t;return((t=o(this,pi).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},co=new WeakMap,lo=new WeakMap,Zc=new WeakSet,Gu=function(){Array.from(o(this,lo)).forEach(t=>this.updateVideo(t,!1)),Array.from(o(this,co)).forEach(t=>this.updateVideo(t,!0))},Bg);Xt([k.trace("DyteSelf.cleanupEvents")],wt.prototype,"cleanupEvents",1);Xt([k.trace("DyteSelf.setupEvents")],wt.prototype,"setupEvents",1);Xt([k.trace("DyteSelf.setupTracks")],wt.prototype,"setupTracks",1);Xt([k.trace("DyteSelf.destructMediaHandler")],wt.prototype,"destructMediaHandler",1);Xt([k.trace("DyteSelf.removeDocumentEventListeners")],wt.prototype,"removeDocumentEventListeners",1);Xt([Cs.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),k.trace("DyteSelf.enableAudio")],wt.prototype,"enableAudio",1);Xt([Cs.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),k.trace("DyteSelf.enableVideo")],wt.prototype,"enableVideo",1);Xt([k.trace("DyteSelf.updateVideoConstraints")],wt.prototype,"updateVideoConstraints",1);Xt([k.trace("DyteSelf.enableScreenShare"),Cs.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3})],wt.prototype,"enableScreenShare",1);Xt([k.trace("DyteSelf.updateScreenshareConstraints")],wt.prototype,"updateScreenshareConstraints",1);Xt([Cs.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),k.trace("DyteSelf.disableAudio")],wt.prototype,"disableAudio",1);Xt([Cs.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),k.trace("DyteSelf.disableVideo")],wt.prototype,"disableVideo",1);Xt([Cs.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3}),k.trace("DyteSelf.disableScreenShare")],wt.prototype,"disableScreenShare",1);Xt([k.trace("DyteSelf.setDevice")],wt.prototype,"setDevice",1);wt=Xt([Lt("1100")],wt);var b2=Object.defineProperty,k2=Object.getOwnPropertyDescriptor,w2=(t,e,n,i)=>{for(var s=i>1?void 0:i?k2(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&b2(e,n,s),s};let Hr;var ed,Fg;const L0=(Fg=class{constructor(t,e){y(this,"socket"),S(this,ed,void 0),T(this,ed,e),this.socket=t,this.handleSocketEvents()}static create(t,e){return Hr||(Hr=new L0(t,e)),Hr}static cleanup(){var t;try{(t=Hr==null?void 0:Hr.socket)==null||t.disconnect()}catch(e){m.error("roomSocketHandler::cleanup")}Hr=void 0}joinRoom(t){return p(this,null,function*(){var e;this.socket.joinAttempted=!0;const n={capabilities:[],peer:{displayName:(e=t.name)!=null?e:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},i=this.socket.sendMessagePromise(z.joinRoom,VA.toBinary(n));try{const{peer:s}=qr.fromBinary((yield i).payload);o(this,ed).getValue("connectionHandler").socketJoined=!0,L.emit(x.SOCKET_SERVICE_ROOM_JOINED,{peer:s});const r=this.getRoomState(),a=this.getRoomPeersNonPaginated(),[{room:c},{peers:d}]=yield Promise.all([r,a]);return L.emit(x.ROOM_STATE,c),L.emit(x.SOCKET_PEERS,d),{peer:s}}catch(s){throw m.error("RoomSocketHandler.joinRoom.failed",{error:s}),new O("Error: RoomSocketHandler.joinRoom failed.","0002",s)}})}getAllAddedParticipants(){return p(this,null,function*(){try{return TM.fromBinary((yield this.socket.sendMessagePromise(z.getAllAddedParticipants)).payload).participants.map(t=>{var e=t,{id:n}=e,i=Pl(e,["id"]);return ee(H({},i),{userId:n})})}catch(t){return[]}})}getRoomPeers(t,e,n){return p(this,null,function*(){let i;try{const s={seachQuery:t,limit:e,offset:n},r=yield this.socket.sendMessagePromise(z.getRoomPeersInfo,CA.toBinary(s));i=_u.fromBinary(r.payload)}catch(s){m.error("getRoomPeers::binary_decode_error",{error:s})}return i})}getRoomPeersNonPaginated(){return p(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(z.getRoomPeersInfo);t=_u.fromBinary(e.payload)}catch(e){m.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getStagePeers(){return p(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(z.getRoomPeersInfo);t=_u.fromBinary(e.payload)}catch(e){m.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getPeerInfo(t){return p(this,null,function*(){let e;try{const n=yield this.socket.sendMessagePromise(z.getPeerInfo,o0.toBinary({peerId:t}));e=qr.fromBinary(n.payload)}catch(n){m.error("getPeerInfo::binary_decode_error",{error:n})}return e})}getRoomState(){return p(this,null,function*(){let t=ng.create();try{const e=yield this.socket.sendMessagePromise(z.getRoomInfo);t=ng.fromBinary(e.payload)}catch(e){m.error("getRoomState::binary_decode_error",{error:e})}return t})}getRoomStageState(){return p(this,null,function*(){let t=ag.create();try{const e=yield this.socket.sendMessagePromise(z.getRoomStageState);t=ag.fromBinary(e.payload)}catch(e){m.error("getRoomStageState::binary_decode_error",{error:e})}return t})}broadcastMessage(t,e){return p(this,null,function*(){const n={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(z.broadcastMessage,xa.toBinary(n))})}broadcastToMeetings(t,e,n){return p(this,null,function*(){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(n)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(z.broadcastToEntity,xa.toBinary(i))})}broadcastToPeers(t,e,n){return p(this,null,function*(){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(n)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(z.broadcastToEntity,xa.toBinary(i))})}leaveRoom(){return p(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(z.leaveRoom,BA.toBinary({}))})}kick(t){return p(this,null,function*(){const e={peerIds:[t]};this.socket.sendMessage(z.kick,d0.toBinary(e))})}kickAll(t=!1){return p(this,null,function*(){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(z.kickAll,s0.toBinary(e))})}getWaitingRoomRequests(){this.socket.sendMessage(z.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(z.acceptWaitingRoomRequests,CM.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(z.denyWaitingRoomRequests,PM.toBinary(e))}updatePermissions(t,e){return p(this,null,function*(){const n={updatePeersPresets:[]};return t.forEach(i=>{n.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(fd.updateUserPreset,sO.toBinary(n))})}handleSocketEvents(){this.socket.on(z.broadcastMessage,({payload:t})=>{try{const e=xa.fromBinary(t);L.emit(x.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){m.error("failed to decode broadcast message:",e)}}),this.socket.on(z.broadcastToEntity,({payload:t})=>{try{const e=xa.fromBinary(t);L.emit(x.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){m.error("failed to decode peer broadcast message:",e)}})}on(t,e){let n,i;switch(t){case z.joinRoom:case z.leaveRoom:case z.kick:case z.kickAll:{n=qr.fromBinary.bind(qr),i=qr.create();break}case z.getWaitingRoomRequests:{n=(s,r)=>s?rg.fromBinary(s,r):{requests:[]},i=rg.create();break}case z.recordingPaused:case z.recordingStarted:case z.recordingStopped:{n=fg.fromBinary.bind(fg);break}case fd.updateUserPreset:{n=og.fromBinary.bind(og);break}case Wn.peerJoinedBroadcast:case _n.peerJoinedBroadcast:{n=Yf.fromBinary.bind(Yf);break}case Wn.selfJoinComplete:case _n.selfJoinComplete:{n=kh.fromBinary.bind(kh);break}case Wn.globalPeerPinBroadcast:case _n.globalPeerPinBroadcast:{n=Zf.fromBinary.bind(Zf);break}case Wn.selectedPeer:case _n.selectedPeer:{n=bh.fromBinary.bind(bh);break}case Wn.selectedPeerDiff:case _n.selectedPeerDiff:{n=zf.fromBinary.bind(zf);break}case Wn.leaveRoom:case _n.leaveRoom:{n=wh.fromBinary.bind(wh);break}}this.socket.on(t,({payload:s})=>{let r=i;if(!n)return e(void 0);try{r=n(s)}catch(a){m.error("roomSocketHandler::on::binary_decode_error",{error:a})}return e(r)})}getUserPermissions(t){return p(this,null,function*(){const e={userIds:[t]};try{const n=yield this.socket.sendMessagePromise(fd.getUserPresets,QM.toBinary(e)),i=tO.fromBinary(n.payload).peerPresets[0],s=new TextDecoder().decode(i.preset),r=JSON.parse(s).permissions;return{chat:r.chat,polls:r.polls,plugins:r.plugins}}catch(n){throw m.error("Error in getting user preset",{error:n}),n}})}},ed=new WeakMap,Fg);let pl=L0;w2([k.trace("RoomSocketHandler.joinRoom")],pl.prototype,"joinRoom",1);var fr={},zl={};Object.defineProperty(zl,"__esModule",{value:!0});zl.Logger=void 0;class _2{constructor(e){}debug(){}warn(){}error(){}}zl.Logger=_2;Object.defineProperty(fr,"__esModule",{value:!0});var ml=fr.AwaitQueue=fr.AwaitQueueRemovedTaskError=fr.AwaitQueueStoppedError=void 0;const I2=zl,$i=new I2.Logger;class lm extends Error{constructor(e){super(e!=null?e:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,lm)}}fr.AwaitQueueStoppedError=lm;class Yl extends Error{constructor(e){super(e!=null?e:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Yl)}}fr.AwaitQueueRemovedTaskError=Yl;class C2{constructor(){this.pendingTasks=new Map,this.nextTaskId=0,this.stopping=!1}get size(){return this.pendingTasks.size}push(e,n){return p(this,null,function*(){if(n=n!=null?n:e.name,$i.debug(`push() [name:${n}]`),typeof e!="function")throw new TypeError("given task is not a function");if(n)try{Object.defineProperty(e,"name",{value:n})}catch(i){}return new Promise((i,s)=>{const r={id:this.nextTaskId++,task:e,name:n,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:a=>{if(r.completed)return;r.completed=!0,this.pendingTasks.delete(r.id),$i.debug(`resolving task [name:${r.name}]`),i(a);const[c]=this.pendingTasks.values();c&&!c.executedAt&&this.execute(c)},reject:a=>{if(!r.completed&&(r.completed=!0,this.pendingTasks.delete(r.id),$i.debug(`rejecting task [name:${r.name}]: %s`,String(a)),s(a),!this.stopping)){const[c]=this.pendingTasks.values();c&&!c.executedAt&&this.execute(c)}}};this.pendingTasks.set(r.id,r),this.pendingTasks.size===1&&this.execute(r)})})}stop(){$i.debug("stop()"),this.stopping=!0;for(const e of this.pendingTasks.values())$i.debug(`stop() | stopping task [name:${e.name}]`);this.stopping=!1}remove(e){$i.debug(`remove() [taskIdx:${e}]`);const n=Array.from(this.pendingTasks.values())[e];if(!n){$i.debug(`stop() | no task with given idx [taskIdx:${e}]`);return}n.reject(new Yl)}dump(){const e=Date.now();let n=0;return Array.from(this.pendingTasks.values()).map(i=>({idx:n++,task:i.task,name:i.name,enqueuedTime:i.executedAt?i.executedAt-i.enqueuedAt:e-i.enqueuedAt,executionTime:i.executedAt?e-i.executedAt:0}))}execute(e){return p(this,null,function*(){if($i.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{const n=yield e.task();e.resolve(n)}catch(n){e.reject(n)}})}}ml=fr.AwaitQueue=C2;function R2(t,e){const n=new Error(e);return n.name=t,n}class pc extends O{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,pc):this.stack=new Error(e).stack}}class rn extends O{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,rn):this.stack=new Error(e).stack}}class gr extends O{constructor(e){super(e),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,rn):this.stack=new Error(e).stack}}const jg=t=>new Promise(e=>setTimeout(e,t));function um(t,e){return p(this,null,function*(){return new Promise((n,i)=>p(this,null,function*(){const{strategy:s,maxRetryCount:r,delayTime:a}=H({strategy:"linear",maxRetryCount:3,delayTime:10},e);let c=0,d,h=!1;const u=g=>{h=!0,i(g)};for(;c<r;){try{const g=yield t(c,u);return n(g)}catch(g){if(d=g,h)break;if(c<r)s==="linear"?yield jg(a*(c+1)):s==="exponential"&&(yield jg(a*(c+Math.max(0,c-1))));else break}c+=1}return i(d)}))})}function P2(t){return t.map(e=>({channels:e.channels,clockRate:e.clockRate,mimeType:e.mimeType,sdpFmtpLine:e.sdpFmtpLine}))}function A2(t){return t.map(e=>({uri:e.uri}))}function td(t){return{codecs:P2(t.codecs),headerExtensions:A2(t.headerExtensions?t.headerExtensions:[])}}function M2(t){const e=RTCRtpReceiver.getCapabilities("audio"),n=RTCRtpReceiver.getCapabilities("video"),i=RTCRtpSender.getCapabilities("audio"),s=RTCRtpSender.getCapabilities("video");t&&(n.codecs=n.codecs.filter(({mimeType:a})=>t===a),s.codecs=s.codecs.filter(({mimeType:a})=>t===a));const r={audio:td(e),video:td(n)};return{sender:{audio:td(i),video:td(s)},receiver:r}}var At;class O2{constructor(e,n){S(this,At,void 0),y(this,"events"),y(this,"sfuType"),T(this,At,e),this.sfuType=n,this.events=n===bt.CF?Wn:_n}joinRoom(e,n,i,s=!1,r=null){return p(this,null,function*(){const a={roomUuid:e,displayName:n,prejoined:s,capabilities:i};return r&&(a.location=r),(yield o(this,At).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:jP.toBinary(a),timeout:5e3})).payload})}connectTransport(e){return p(this,null,function*(){const n=(yield o(this,At).sendMessagePromise(this.events.createWebRTCTransport,gP.toBinary(e))).payload,{transportId:i,description:s,producerIds:r}=t0.fromBinary(n),a={sdp:s==null?void 0:s.sdp,type:s.type};return{transportId:i,answer:a,producerIds:r}})}produce(e){return p(this,null,function*(){var n,i;const s=(yield o(this,At).sendMessagePromise(this.events.produce,XP.toBinary(e))).payload,r=N1.fromBinary(s);return{answer:{sdp:(n=r==null?void 0:r.description)==null?void 0:n.sdp,type:(i=r==null?void 0:r.description)==null?void 0:i.type},producerId:r.producerId}})}consume(e){return p(this,null,function*(){if(this.sfuType===bt.HIVE)throw new Error("Hive does not support socket consumer operations");const n=(yield o(this,At).sendMessagePromise(this.events.consume,YP.toBinary(e))).payload,{consumerIdsMap:{map:i},description:s}=O1.fromBinary(n);return{consumerStateMap:i,sessionDescription:s}})}closeProducer(e){return p(this,null,function*(){const n=(yield o(this,At).sendMessagePromise(this.events.closeProducer,r1.toBinary(e))).payload,{description:i}=j1.fromBinary(n);return i})}closeConsumer(e){return p(this,null,function*(){if(this.sfuType===bt.HIVE)throw new Error("Hive does not support socket consumer operations");return(yield o(this,At).sendMessagePromise(this.events.closeConsumer,o1.toBinary(e))).payload})}hostControlForPeer(e,n){return p(this,null,function*(){const i={audio:n==="audio",screeShare:!1,video:n==="video",participantId:e},s=(yield o(this,At).sendMessagePromise(this.events.hostControlPeer,p1.toBinary(i))).payload;if(!s)return!1;const{status:r}=K1.fromBinary(s);return r==="success"})}hostControlForAll(e){return p(this,null,function*(){const n={audio:e==="audio",screenShare:!1,video:e==="video"},i=(yield o(this,At).sendMessagePromise(this.events.hostControlAllPeers,f1.toBinary(n))).payload;if(!i)return!1;const{status:s}=Y1.fromBinary(i);return s==="success"})}kickAll(){return p(this,null,function*(){const e={propagateKickAcrossRooms:!1};o(this,At).sendMessagePromise(z.kickAll,s0.toBinary(e))})}kickPeer(e){return p(this,null,function*(){o(this,At).sendMessagePromise(z.kick,d0.toBinary(e))})}changeDisplayName(e){return p(this,null,function*(){const n=(yield o(this,At).sendMessagePromise(this.events.changeDisplayName,u1.toBinary(e))).payload;if(!n)return!1;const{status:i}=X1.fromBinary(n);return i==="success"})}notifySelfJoinComplete(){return p(this,null,function*(){const e={},n=(yield o(this,At).sendMessagePromise(this.events.selfJoinComplete,HP.toBinary(e))).payload;return kh.fromBinary(n)})}audioActivity(e){return p(this,null,function*(){o(this,At).sendMessage(this.events.audioActivity,yP.toBinary(e))})}}At=new WeakMap;class mc extends Nt.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}safeEmit(e,...n){const i=this.listenerCount(e);try{return this.emit(e,...n)}catch(s){return m.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:s}),Boolean(i)}}safeEmitAsPromise(e,...n){return p(this,null,function*(){const i={}.EVENT_PROMISE_TIMEOUT?parseInt({}.EVENT_PROMISE_TIMEOUT,10):1e4;return this.safeEmitAsPromiseWithTimeout(e,i,...n)})}safeEmitAsPromiseWithTimeout(e,n,...i){return p(this,null,function*(){return new Promise((s,r)=>{setTimeout(r,n,"event request timeout");try{this.emit(e.toString(),...i,s,r)}catch(a){m.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:a}),r(a)}})})}}class hm extends mc{constructor(){super(...arguments),y(this,"_sendWebStream",new MediaStream),y(this,"_sendScreenShareStream",new MediaStream),y(this,"_direction"),y(this,"pc"),y(this,"_transportReady",!1),y(this,"_mapMidTransceiver",new Map),y(this,"enableHighBitrate",!1),y(this,"enableStereo",!1),y(this,"enableDtx",!0)}get midTransceiverMap(){return this._mapMidTransceiver}close(){if(m.debug(`${this.name}::close()`),this.pc)try{this.pc.close()}catch(e){m.error(`${this.name}::pc.close()`,{error:e})}}restartIce(){return p(this,null,function*(){m.debug(`${this.name}::restartIce()`);const e=yield this.pc.createOffer({iceRestart:!0});return m.debug(`${this.name}::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:n=>p(this,null,function*(){m.info(`${this.name}::restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(n)}]`),yield this.pc.setRemoteDescription(n)})}})}init({direction:e,iceServers:n,iceTransportPolicy:i,additionalSettings:s,proprietaryConstraints:r,onTrackHandler:a}){m.debug("HandlerInterface::init()"),this._direction=e,this.pc=new RTCPeerConnection(H({iceServers:n||[],iceTransportPolicy:i||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"},s),r),a&&this.pc.addEventListener("track",c=>{a(c)}),this._addEventListeners()}connect(){return p(this,null,function*(){const e=this.pc.createDataChannel("dyte"),n=yield this.pc.createOffer();return yield this.pc.setLocalDescription(n),m.info(`connect offer: ${JSON.stringify(n)}`),{offerSdp:n,callback:i=>p(this,null,function*(){m.debug(`${this.name}::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this.pc.setRemoteDescription(i),e.close()})}})}getTransportStats(){return p(this,null,function*(){return this.pc.getStats()})}_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')}getReceiverStats(e){return p(this,null,function*(){this._assertRecvDirection();const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");return n.receiver.getStats()})}stopSending(e){return p(this,null,function*(){this._assertSendDirection(),m.debug(`stopSending() [localId:${e}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");n.sender.replaceTrack(null),this.pc.removeTrack(n.sender),n.direction="inactive";const i=yield this.pc.createOffer();return m.debug(`stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(i)}]`),yield this.pc.setLocalDescription(i),{offerSdp:i,callback:s=>p(this,null,function*(){m.debug(`stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(s)}]`),yield this.pc.setRemoteDescription(s),this.midTransceiverMap.delete(e)})}})}replaceTrack(e,n){return p(this,null,function*(){this._assertSendDirection(),n?m.debug(`replaceTrack() [localId:${e}, track.id:${n.id}]`):m.debug(`replaceTrack() [localId:${e}, no track]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");yield i.sender.replaceTrack(n)})}setMaxSpatialLayer(e,n){return p(this,null,function*(){this._assertSendDirection(),m.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${n}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const s=i.sender.getParameters();s.encodings.forEach((r,a)=>{a<=n?r.active=!0:r.active=!1}),yield i.sender.setParameters(s)})}setRtpEncodingParameters(e,n){return p(this,null,function*(){this._assertSendDirection(),m.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(n)}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const s=i.sender.getParameters();s.encodings.forEach((r,a)=>{s.encodings[a]=H(H({},r),n)}),yield i.sender.setParameters(s)})}getSenderStats(e){this._assertSendDirection();const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");return n.sender.getStats()}_addEventListeners(){this.pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this.pc.addEventListener("iceconnectionstatechange",()=>{switch(this.pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:m.warn("unknown state");break}}),this.pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),m.debug("negotiationneeded")}),this.pc.addEventListener("icegatheringstatechange",()=>{switch(this.pc.iceGatheringState){case"gathering":m.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":m.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:m.warn("unknown state");break}}),this.pc.addEventListener("icecandidateerror",e=>{m.warn("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this.pc.addEventListener("datachannel",e=>{m.info("data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:n}=e;n.onopen=()=>{m.info("data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},n.onclose=()=>{m.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},n.onerror=()=>{m.error("data channel error: ",{rtcChannel:{label:e.channel.label}})}}),this.addCustomEventListeners()}addCustomEventListeners(){}}class pm extends hm{static createFactory(){return()=>new pm}get name(){return"Chrome74"}init({direction:e,iceServers:n,iceTransportPolicy:i,additionalSettings:s,proprietaryConstraints:r,onTrackHandler:a}){this._direction=e,this.pc=new RTCPeerConnection(H({iceServers:n||[],iceTransportPolicy:i||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"},s),r),a&&this.pc.addEventListener("track",c=>{a(c)}),this._addEventListeners()}send(e){return p(this,arguments,function*({track:n,encodings:i,codecOptions:s,screenShare:r}){this._assertSendDirection();const a=this.pc.addTransceiver(n,{direction:"sendonly",streams:[r?this._sendScreenShareStream:this._sendWebStream],sendEncodings:i});if(!navigator.isReactNative){m.debug("creating new transceiver");const h=RTCRtpSender.getCapabilities(typeof n=="string"?n:n.kind);m.info(`senders available params: ${JSON.stringify(h)}`);const u=[];s&&s.length&&s.forEach(g=>{var E;const b=h.codecs.find(w=>w.mimeType.includes(g.name));if(g.parameters){m.debug(`codecOption.parameters:${JSON.stringify(g.parameters)}`);const w=((E=b.sdpFmtpLine)==null?void 0:E.split(";"))||[];w.push(...g.parameters);const M=Array.from(new Set(w).values());b.sdpFmtpLine=M.join(";")}u.push(b)}),m.info(`selected codecs: ${JSON.stringify(u)}`),a.setCodecPreferences(u)}const c=yield this.pc.createOffer();if(yield this.pc.setLocalDescription(c),s&&s.findIndex(({name:h})=>h==="opus")>=0){const{enableDtx:h,enableStereo:u}=this,g=this.enableHighBitrate?u?128e3:64e3:u?64e3:32e3;c.sdp=c.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${u?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${g}`),c.sdp+=`a=rtcp-fb:111 nack\r
24
+ `}this.midTransceiverMap.set(a.mid,a);const d=h=>p(this,null,function*(){return m.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),yield this.pc.setRemoteDescription(h),a.mid});return m.debug(`send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(c,void 0,2)}]`),{offerSdp:c,callback:d,sender:a.sender,mid:a.mid}})}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:n}=e;n.onmessage=i=>{this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(i.data)))}})}}class fl extends hm{constructor(e){super(),y(this,"supportsSendEncodings",!1),this.supportsSendEncodings=e.supportsSendEncodings}static createFactory(e){return()=>new fl(e)}get name(){return"Firefox60"}send(e){return p(this,arguments,function*({track:n,encodings:i,codecOptions:s,screenShare:r}){this._assertSendDirection();const a=this.supportsSendEncodings&&i!==void 0?{sendEncodings:i}:{},c=this.pc.addTransceiver(n,H({direction:"sendonly",streams:[r?this._sendScreenShareStream:this._sendWebStream]},a));if(!this.supportsSendEncodings&&i){i.reverse();const u=c.sender.getParameters();u.encodings=i,yield c.sender.setParameters(u)}const d=(u,g)=>{var E;const b=qo(u),w=b.media[b.media.length-1],M=w.rtp.filter(X=>g.some(A=>A.name===X.codec)),D=w.fmtp.filter(X=>M.some(A=>A.payload===X.payload)),F=(E=w.rtcpFb)==null?void 0:E.filter(X=>M.some(A=>A.payload===X.payload)),Y=M.map(X=>X.payload);return b.media[b.media.length-1].rtp=M,b.media[b.media.length-1].fmtp=D,b.media[b.media.length-1].rtcpFb=F,b.media[b.media.length-1].payloads=Y.join(" "),ih(b)},h=yield this.pc.createOffer();if(h.sdp=d(h.sdp,s),m.debug(`send() | calling pc.setLocalDescription() [offer:${JSON.stringify(h)}]`),yield this.pc.setLocalDescription(h),n==="audio"||n.kind==="audio"){const{enableDtx:u,enableStereo:g}=this,E=this.enableHighBitrate?g?128e3:64e3:g?64e3:32e3;h.sdp=h.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${u?"usedtx=1;":""}${g?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${E}`)}return this.midTransceiverMap.set(c.mid,c),{offerSdp:h,callback:u=>p(this,null,function*(){return m.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(u)}]`),yield this.pc.setRemoteDescription(u),c.mid}),sender:c.sender,mid:c.mid}})}setMaxSpatialLayer(e,n){return p(this,null,function*(){this._assertSendDirection(),m.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${n}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const s=i.sender.getParameters(),r=s.encodings.length-1-n;s.encodings.forEach((a,c)=>{c>=r?a.active=!0:a.active=!1}),yield i.sender.setParameters(s)})}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:n}=e;n.onmessage=i=>p(this,null,function*(){const s=yield i.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(s)))})})}}class mm extends hm{static createFactory(){return()=>new mm}get name(){return"Safari12"}send(e){return p(this,arguments,function*({track:n,encodings:i,codecOptions:s,screenShare:r}){this._assertSendDirection(),m.debug("Safari12::creating new transceiver");const a=this.pc.addTransceiver(n,{direction:"sendonly",streams:[r?this._sendScreenShareStream:this._sendWebStream],sendEncodings:i}),c=RTCRtpSender.getCapabilities(typeof n=="string"?n:n.kind);m.info(`Safari12::senders available params: ${JSON.stringify(c)}`);const d=[];s&&s.length>0&&s.forEach(u=>{var g;const E=c.codecs.find(b=>b.mimeType.includes(u.name));if(u.parameters){m.info(`Safari12::codecOption.parameters:, ${JSON.stringify(u.parameters)}`);const b=((g=E.sdpFmtpLine)==null?void 0:g.split(";"))||[];b.push(...u.parameters);const w=[...new Set(b).values()];E.sdpFmtpLine=w.join(";")}d.push(E)}),m.info(`Safari12::selected codecs: ${JSON.stringify(d)}`),a.setCodecPreferences(d);const h=yield this.pc.createOffer();if(yield this.pc.setLocalDescription(h),n==="audio"||n.kind==="audio"){const{enableStereo:u,enableDtx:g}=this,E=this.enableHighBitrate?u?128e3:64e3:u?64e3:32e3;h.sdp=h.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${g?"usedtx=1;":""}${u?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${E}`)}return this.midTransceiverMap.set(a.mid,a),{offerSdp:h,callback:u=>p(this,null,function*(){return m.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(u)}]`),yield this.pc.setRemoteDescription(u),a.mid}),sender:a.sender,mid:a.mid}})}addCustomEventListeners(){this.pc.ondatachannel=e=>{const{channel:n}=e;n.onmessage=i=>p(this,null,function*(){const s=String.fromCharCode(...new Uint8Array(i.data));this.safeEmit("datachannel",e.channel,s)})}}}function D2(t,e){return typeof t=="undefined"?e:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(t):JSON.parse(JSON.stringify(t))}var _d,Qr,vi,Si,fs,Id,$u,Hh,x0,qh,V0;class N2 extends mc{constructor(e){var n;super(),S(this,Si),S(this,Id),S(this,Hh),S(this,qh),y(this,"rtpReceiver"),y(this,"id"),y(this,"localId"),y(this,"producerId"),y(this,"producingTransportId"),y(this,"mimeType"),y(this,"track"),y(this,"peerId"),y(this,"appData"),y(this,"transceiver"),S(this,_d,void 0),S(this,Qr,void 0),S(this,vi,void 0),this.id=e.id,this.localId=e.localId,T(this,_d,e.handler),this.appData=e.appData,this.peerId=e.producingPeerId,this.producingTransportId=e.producingTransportId,T(this,vi,!1),this.producerId=e.producerId,this.track=e.track,T(this,Qr,(n=e.paused)!=null?n:!1),this.mimeType=e.mimeType,this.transceiver=e.transceiver,this.rtpReceiver=e.rtpReceiver,Q(this,Hh,x0).call(this)}get closed(){return o(this,vi)}get kind(){return this.track.kind}get paused(){return o(this,Qr)}close(e,n){o(this,vi)||(m.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,o(this,Si,fs)),T(this,vi,!0),n&&(Q(this,qh,V0).call(this),this.transceiver.stop()),this.safeEmit("close",e))}getStats(){return p(this,null,function*(){if(o(this,vi))throw new rn("closed");return o(this,_d).getReceiverStats(this.localId)})}pause(){if(m.debug("consumer::pause()",o(this,Si,fs)),o(this,vi)){m.error("consumer::pause() | Consumer closed",o(this,Si,fs));return}T(this,Qr,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(m.debug("consumer::resume()",o(this,Si,fs)),o(this,vi)){m.error("Consumer::resume() | Consumer closed",o(this,Si,fs));return}T(this,Qr,!1),this.track.enabled=!0,this.safeEmit("resume")}}_d=new WeakMap,Qr=new WeakMap,vi=new WeakMap,Si=new WeakSet,fs=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},Id=new WeakSet,$u=function(){m.debug('Consumer::track "ended" event',o(this,Si,fs)),this.safeEmit("trackended")},Hh=new WeakSet,x0=function(){this.track.addEventListener("ended",Q(this,Id,$u).bind(this))},qh=new WeakSet,V0=function(){try{this.track.removeEventListener("ended",Q(this,Id,$u)),this.track.stop()}catch(t){m.error("Consumer::destroyTrack()",ee(H({},o(this,Si,fs)),{error:t}))}};var ei,Co,Ro,Xr,Bn,Mt,Js,Po,bn,Fn;class L2 extends mc{constructor(e){var n,i;super(),S(this,bn),y(this,"id"),y(this,"localId"),S(this,ei,void 0),y(this,"kind"),y(this,"appData"),y(this,"rtpSender"),S(this,Co,void 0),S(this,Ro,void 0),S(this,Xr,void 0),S(this,Bn,!1),S(this,Mt,void 0),S(this,Js,void 0),S(this,Po,void 0),this.id=e.id,this.localId=e.localId,T(this,Mt,e.track),this.kind=(n=e.track)==null?void 0:n.kind,T(this,Js,e.disableTrackOnPause?!((i=e.track)!=null&&i.enabled):!1),T(this,Po,void 0),T(this,Co,e.stopTracks),T(this,Ro,e.disableTrackOnPause),T(this,Xr,e.zeroRtpOnPause),this.appData=e.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),T(this,ei,e.handler),this.rtpSender=e.rtpSender,this._handleTrack()}get closed(){return o(this,Bn)}get track(){return o(this,Mt)}get paused(){return o(this,Js)}get maxSpatialLayer(){return o(this,Po)}close(e){return p(this,null,function*(){if(o(this,Bn))return;if(m.debug(`Producer::close() ${e?`with reason ${e}`:""}`,o(this,bn,Fn)),T(this,Bn,!0),this._destroyTrack(),e===gl){this.safeEmit("close",{reason:e});return}const{offerSdp:n,callback:i}=yield o(this,ei).stopSending(this.localId),{answer:s}=yield this.safeEmitAsPromise("close",{offer:n,reason:e});i(s)})}getStats(){return p(this,null,function*(){if(o(this,Bn))throw new rn("closed");return o(this,ei).getSenderStats(this.localId)})}pause(){m.debug("Producer::pause()",o(this,bn,Fn)),o(this,Bn)&&m.error("Producer::pause() | Producer closed",o(this,bn,Fn)),T(this,Js,!0),o(this,Mt)&&o(this,Ro)&&(o(this,Mt).enabled=!1),o(this,Xr)&&o(this,ei).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(m.debug("Producer::resume()",o(this,bn,Fn)),o(this,Bn)){m.error("Producer::resume() | Producer closed",o(this,bn,Fn));return}T(this,Js,!1),o(this,Mt)&&o(this,Ro)&&(o(this,Mt).enabled=!0),o(this,Xr)&&o(this,ei).replaceTrack(this.localId,o(this,Mt)),this.emit("resume")}replaceTrack(e){return p(this,arguments,function*({track:n}){if(m.debug(`Producer::replaceTrack() trackId: ${n==null?void 0:n.id}`,o(this,bn,Fn)),o(this,Bn)){if(n&&o(this,Co))try{n.stop()}catch(i){m.error("Producer::replaceTrack",ee(H({},o(this,bn,Fn)),{error:i}))}throw new rn("closed")}else if(n&&n.readyState==="ended")throw new rn("track ended");if(n===o(this,Mt)){m.debug(`replaceTrack() | same track, ignored trackId: ${n.id}`,o(this,bn,Fn));return}(!o(this,Xr)||!o(this,Js))&&(yield o(this,ei).replaceTrack(this.localId,n)),this._destroyTrack(),T(this,Mt,n),this._handleTrack()})}setMaxSpatialLayer(e){return p(this,null,function*(){if(o(this,Bn))throw new rn("closed");if(this.kind!=="video")throw new pc("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");yield o(this,ei).setMaxSpatialLayer(this.localId,e),T(this,Po,e)})}setRtpEncodingParameters(e){return p(this,null,function*(){if(o(this,Bn))throw new rn("closed");if(typeof e!="object")throw new TypeError("invalid params");yield o(this,ei).setRtpEncodingParameters(this.localId,e)})}_onTrackEnded(){m.debug(`Producer::track "ended" event trackId: ${this.track.id}`,o(this,bn,Fn)),this.safeEmit("trackended",this.track.id)}_handleTrack(){o(this,Mt)&&o(this,Mt).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(o(this,Mt))try{o(this,Mt).removeEventListener("ended",this._onTrackEnded),o(this,Co)&&o(this,Mt).stop()}catch(n){m.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,ee(H({},o(this,bn,Fn)),{error:n}))}}}ei=new WeakMap,Co=new WeakMap,Ro=new WeakMap,Xr=new WeakMap,Bn=new WeakMap,Mt=new WeakMap,Js=new WeakMap,Po=new WeakMap,bn=new WeakSet,Fn=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function U0(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function Gh(t){return Math.random().toString(36).substring(2,2+t)}const nd=1;function Wg(t){const e=t;return delete e.payload._bolt,e}function x2(t){return t.payload&&U0(t.payload)}function B0(t){var e,n;return x2(t)&&(n=(e=t.payload._bolt)==null?void 0:e.id)!=null?n:""}var Ks;const Ao=class extends Nt.EventEmitter{constructor(t,e,n){super(),y(this,"channel"),y(this,"queue"),y(this,"serverProtocolVersion"),S(this,Ks,new Map),y(this,"respond",(i,s,r=!1)=>{let a;r?a=Ao.createErrorResponse(i,s):a=Ao.createResponse(i,s),this.channel.send(JSON.stringify(a))}),y(this,"notify",i=>{const s=Ao.createNotification(i);this.channel.send(JSON.stringify(s))}),y(this,"request",i=>p(this,null,function*(){const s=Ao.createRequest(i),r=new Promise((a,c)=>{const{id:d}=s.payload._bolt,h={id:d,method:s.type,resolve:u=>{this.queue.delete(d)&&(clearTimeout(h.timer),a(u))},timer:setTimeout(()=>{this.queue.delete(d)&&c(new Error(`request timeout for message id: ${d}`))},2e4),cancel:u=>{this.queue.delete(d)&&(clearTimeout(h.timer),c(u))}};this.queue.set(d,h)});return this.channel.send(JSON.stringify(s)),r})),y(this,"send",i=>{const s=JSON.stringify(i),r=16384;if(s.length>r){const a=r-200,c=Math.ceil(s.length/a),d=[];for(let u=0;u<c;u+=1){const g=u*a,E=(u+1)*a;d.push(s.slice(g,E))}const h=Ia();for(let u=0;u<c;u+=1){const g=d[u],E=JSON.stringify({id:h,count:c,chunkIndex:u,chunk:g});m.debug(`Sending message chunk over dc: ${E}`),this.channel.send(E)}}else m.debug(`Sending message over dc: ${s}`),this.channel.send(s)}),y(this,"processMessage",i=>{var s;o(this,Ks).has(i.id)||o(this,Ks).set(i.id,[]);const r=o(this,Ks).get(i.id);if(r[i.chunkIndex]=i,(r==null?void 0:r.length)===i.count&&!r.some(a=>a===void 0)){const a=o(this,Ks).get(i.id),c=a==null?void 0:a.reduce((h,u)=>h+u.chunk,"");o(this,Ks).delete(i.id);const d=JSON.parse(c);if(!d.payload||!U0(d.payload))throw new Error("corrupted incoming message over dc",{cause:{code:"CORRUPT_DC_MESSAGE",values:d}});if(this.processBoltHandshake(d))return;if(this.serverProtocolVersion=(s=d.payload._bolt)==null?void 0:s.version,!this.processResponseMsg(d))return d}}),y(this,"processResponseMsg",i=>{const{id:s}=i.payload._bolt,r=this.queue.get(s);return r?(m.debug(`resolving pending request with id: ${s}, complete response: ${JSON.stringify(i)}`),i.type==="error"?r.cancel(Wg(i)):r.resolve(Wg(i)),!0):!1}),y(this,"processBoltHandshake",i=>{var s,r;return i.type==="_bolt"||i.type==="handshake"?(this.respond((r=(s=i.payload._bolt)==null?void 0:s.id)!=null?r:Gh(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1}),this.label=e,this.transportId=n,this.channel=t,this.queue=new Map}};let Mo=Ao;Ks=new WeakMap,y(Mo,"createRequest",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:ee(H({},t.payload),{_bolt:{id:Gh(8),type:"REQUEST",version:nd}})}}),y(Mo,"createResponse",(t,e)=>{var n;if((n=e.payload)!=null&&n._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:ee(H({},e.payload),{_bolt:{id:t,type:"RESPONSE",version:nd}})}}),y(Mo,"createNotification",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:ee(H({},t.payload),{bolt:{id:Gh(8),type:"NOTIFY",version:nd}})}}),y(Mo,"createErrorResponse",(t,e)=>({type:"error",payload:{error:e.message,_bolt:{id:t,type:"RESPONSE",version:nd}}}));function V2(t){if(Promise.allSettled)return Promise.allSettled(t);const e=t.map(n=>n.then(i=>({status:"fulfilled",value:i})).catch(i=>({status:"rejected",reason:i})));return Promise.all(e)}const gl="transport closed";var Oo;const $h=class extends mc{constructor(t,{id:e,direction:n,handlerFactory:i,iceServers:s,iceTransportPolicy:r,proprietaryConstraints:a,additionalSettings:c,appData:d,config:h}){var u,g,E;super(),y(this,"awaitQueue"),y(this,"observer"),S(this,Oo,void 0),y(this,"id"),y(this,"serverId"),y(this,"direction"),y(this,"maxSctpMessageSize"),y(this,"handler"),y(this,"connectionState","new"),y(this,"producers"),y(this,"consumers"),y(this,"datachannels"),y(this,"connected",!1),y(this,"eventsDCReadyPromise"),y(this,"eventsDCReadyPromiseResolver"),y(this,"eventsDCFailureTimer"),y(this,"transportConnectionPromise"),y(this,"consumerTrackEvents"),y(this,"unknownTracksMap"),y(this,"appData"),m.debug(`constructor() [id: ${e}, direction: ${n}]`),T(this,Oo,t),this.id=e,this.direction=n;const b=D2(c,{});delete b.iceServers,delete b.iceTransportPolicy,delete b.bundlePolicy,delete b.rtcpMuxPolicy,delete b.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new ml,this.observer=new mc,this.handler=i(),this.handler.enableHighBitrate=(u=h==null?void 0:h.enableHighBitrate)!=null?u:!1,this.handler.enableStereo=(g=h==null?void 0:h.enableStereo)!=null?g:!1,this.handler.enableDtx=(E=h==null?void 0:h.enableDtx)!=null?E:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:n,iceServers:s,iceTransportPolicy:r,additionalSettings:c,proprietaryConstraints:a}),this.appData=d||{},this.transportConnectionPromise=new Promise(w=>{this.observer.once("connected",()=>{w(!0)}),this.observer.once("disconnect",()=>{w(!1)}),this.observer.once("close",()=>{w(!1)})}),this.eventsDCReadyPromise=new Promise(w=>{this.eventsDCReadyPromiseResolver=w}),this.handler.on("@connectionstatechange",w=>{w!==this.connectionState&&(m.debug(`connection state changed to ${w}`),this.connectionState=w,w==="connected"&&(this.connected=!0,this.observer.emit("connected")),w==="disconnected"&&(this.connected=!1,this.observer.emit("disconnect")),(w==="failed"||w==="closed")&&(this.connected=!1,this.observer.emit("close")),this.closed||this.safeEmit("connectionstatechange",w))}),this.handler.on("@icecandidate",({candidate:w})=>{this.closed||this.safeEmit("icecandidate",w)}),this.handler.on("dc_open",w=>{let M=this.datachannels.get(w.label);M||(M||(M=new Mo(w,w.label,this.serverId),this.datachannels.set(w.label,M)),this.eventsDCFailureTimer=setTimeout(()=>{w.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",w.label))},5e3))}),this.handler.on("datachannel",(w,M)=>{w.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const D=this.datachannels.get(w.label);if(!D){m.error("unregistered datachannel for message",{rtcChannel:{label:w.label,message:M}});return}try{const F=JSON.parse(M);m.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:F.id,count:F.count,chunkIndex:F.chunkIndex,chunk:F.chunk,transprtId:this.serverId}});const Y=D.processMessage(F);if(!Y)return;m.debug(`datachannel message with id:${F.id} on transport:${this.serverId}complete - ${JSON.stringify(Y)}`),this.emit(`datachannel:${w.label}`,D.label,Y)}catch(F){m.error("error parsing message",{error:F})}})}get closed(){return this.connectionState==="closed"}setServerId(t){this.serverId=t}getDatachannel(t){return this.datachannels.get(t)}get isEventsDCReady(){return this.eventsDCReadyPromise}close(){this.closed||(m.debug("Transport close called"),this.connectionState="closed",this.connected=!1,this.handler.close(),Array.from(this.producers.values()).forEach(t=>{t.close(gl).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(t=>{t.close(gl)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"),this.observer.emit("close"))}getStats(){return p(this,null,function*(){if(this.closed)throw new rn("closed");return this.handler.getTransportStats()})}connect(t){return p(this,null,function*(){try{if(yield this.awaitQueue.push(()=>p(this,null,function*(){const{offerSdp:e,callback:n}=yield this.handler.connect(),{transportId:i,answer:s}=yield t(e);this.setServerId(i),yield n(s)})),!(yield this.transportConnectionPromise))throw new Error("ice connection failed");if(o(this,Oo)===bt.HIVE&&!(yield this.isEventsDCReady))throw new Error("events datachannel not open")}catch(e){throw m.error("transport failed to connect:",{error:e}),e}})}restartIce(){return p(this,null,function*(){if(m.debug("restartIce()"),this.closed)throw new rn("closed");return this.handler.restartIce()})}canProduce(t){return p(this,null,function*(){const{track:e,appData:n}=t;if(e){if(this.direction!=="send")throw new pc("not a sending Transport");if(e.readyState==="ended")throw new rn("track ended");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(n&&typeof n!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!(yield this.transportConnectionPromise))throw new gr("transport not connected");return!0})}produce(t,e){return p(this,null,function*(){if(!(yield this.canProduce(t)))throw new Error("Cannot produce");const{track:n,encodings:i,codecOptions:s,stopTracks:r=!0,disableTrackOnPause:a=!0,zeroRtpOnPause:c=!1,appData:d={}}=t;m.debug(`produce() [track:${n.id}]`);const{producerId:h,localId:u,rtpSender:g}=yield this.awaitQueue.push(()=>p(this,null,function*(){const{offerSdp:E,callback:b,sender:w,mid:M}=yield this.handler.send({track:n,encodings:i,codecOptions:s,screenShare:d==null?void 0:d.screenShare}),{answer:D,producerId:F}=yield e({offer:E,kind:n.kind,paused:a?!n.enabled:!1,appData:ee(H({},d||{}),{mid:M}),codecOptions:s,producingTransportId:this.serverId}),Y=yield b(D);return{producerId:F,localId:Y,rtpSender:w}}),"producer");return this.createProducerObject({id:h,localId:u,track:n,stopTracks:r,disableTrackOnPause:a,zeroRtpOnPause:c,appData:d,handler:this.handler,rtpSender:g})})}createProducerObject(t){return p(this,null,function*(){const e=new L2(t);return this.producers.set(e.id,e),e.once("close",()=>{this.producers.delete(e.id)}),e})}closeProducer(t){return p(this,null,function*(){yield this.awaitQueue.push(t.close.bind(t),"producer")})}canConsume(){return p(this,null,function*(){if(this.closed)throw new rn("closed");if(this.direction!=="recv")throw new pc("not a receiving transport");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(!(yield this.transportConnectionPromise))throw new gr("transport not connected");return!0})}consume(t,e,n){return p(this,null,function*(){return this.awaitQueue.push(()=>p(this,null,function*(){const i={},{consumerStates:s,sessionDescription:r,failedProducers:a}=yield e(t);s.forEach((h,u)=>{i[u]=this.createConsumerObjectAndWaitForTrack(ee(H({},h),{producerId:u}))});const c=a;r&&(m.info("Session description found, sending negotiation request"),yield n(r));const d=[];return yield Promise.all(Object.entries(i).map(([h,u])=>u.then(g=>d.push(g)).catch(()=>{m.error(`Failed to create consumer object, producer: ${h}`,{error:{message:"This should not happen"},transport:{serverId:this.serverId}})}))),{consumers:d,failedProducers:c}}),"consumer")})}static parseCodecAndFmtpMappings(t,e){const n=qo(t.sdp),i={};return n.media.forEach(s=>{e.includes(s.mid.toString())&&(i[s.mid.toString()]={rtp:s.rtp,fmtp:s.fmtp,payloads:s.payloads,rtcpFb:s.rtcpFb})}),i}static setCodecAndFmtpMappings(t,e,n){const i=qo(t.sdp);return i.media=i.media.map(s=>{if(e.includes(s.mid.toString())){const r=H({},s);return r.rtp=n[s.mid.toString()].rtp,r.fmtp=n[s.mid.toString()].fmtp,r.payloads=n[s.mid.toString()].payloads,r.rtcpFb=n[s.mid.toString()].rtcpFb,r}return s}),ee(H({},t),{sdp:ih(i)})}closeConsumers(t,e){return p(this,null,function*(){try{const n=t.map(a=>a.transceiver.mid),i=$h.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,n);m.info("Stopping transceivers",{consumerIds:t.map(({id:a})=>a)}),t.forEach(a=>a.close(void 0,!0));let s=yield this.handler.pc.createOffer();m.info("Created offer for closing consumers",{sdp:s.sdp}),s=$h.setCodecAndFmtpMappings(s,n,i),m.info("Updated codec and fmtp mappings in close consumer offer",{sdp:s.sdp}),yield this.setLocalDescription(s),m.info("Successfully set local description in close consumers");const r=yield e(t,s);m.info("Received answer in close consumers",{sdp:r.sdp}),yield this.setRemoteDescription(r),m.info("Remote description was set successfully in close consumers",{sdp:r.sdp})}catch(n){m.error("Failed to close consumers",{error:n})}})}setRemoteOffer(t){return p(this,null,function*(){try{m.info("Received offer from SFU",{sdp:t.sdp}),yield this.setRemoteDescription(t);const e=yield this.handler.pc.createAnswer();m.info("Created answer corresponding to received offer",{sdp:e.sdp});const n=qo(e.sdp);return n.media=n.media.map(i=>{if(i.type==="audio"){const s=H({},i),r=s.fmtp.find(a=>a.payload===111);return r&&(r.config+=";stereo=1;sprop-stereo=1"),s.rtcpFb||(s.rtcpFb=[]),s.rtcpFb.some(a=>a.type==="nack")||s.rtcpFb.push({payload:parseInt(s.payloads,10),type:"nack"}),s}return i}),e.sdp=ih(n),m.info("Setting munged SDP",{sdp:e.sdp}),yield this.setLocalDescription(e),m.info("Successfully set local description",{sdp:e.sdp}),e}catch(e){throw m.error("Set remote offer failed",{error:e}),e}})}_ontrack(t){const{track:e,transceiver:n,streams:i}=t;m.info(`track event received [trackId: ${e.id}]`);let s;o(this,Oo)===bt.HIVE?s=`${i[0].id}:${e.kind}`:s=`${n.mid}:${e.kind}`,e.addEventListener("ended",()=>{m.info(`rtc consumer track ended [trackId: ${e.id}]`),this.unknownTracksMap.delete(s)});const r=this.consumerTrackEvents.get(s);r?(r(e,n),this.consumerTrackEvents.delete(s)):(m.warn(`track event handler not found ${s}`),this.unknownTracksMap.set(s,t))}sendErrorOverDC(t,e,n){const i=this.getDatachannel(t);if(!i)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:t}}});i.respond(e,n,!0)}sendResponseOverDC(t,e,n){const i=this.getDatachannel(t);if(!i)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:t}}});i.respond(e,n)}createConsumerObjectAndWaitForTrack(t){return p(this,null,function*(){const{consumerId:e,producerId:n,producingPeerId:i,producingTransportId:s,streamId:r,paused:a,screenShare:c,appData:d,kind:h,mimeType:u}=t,g=`${r}:${h}`,E=ee(H({},t),{name:"consumer creation task error",message:"consumer creation failed"});return new Promise((b,w)=>p(this,null,function*(){const M=setTimeout(()=>{this.consumerTrackEvents.delete(g),E.isTimedout=!0,w(E)},5e3),D=(Y,X)=>{try{if(Y.readyState==="ended")clearTimeout(M),w(E);else{const A=Y;A.enabled=!0,this.handler.midTransceiverMap.set(X.mid,X);const $=new N2({id:e,localId:X.mid,transceiver:X,track:A,paused:a,producerId:n,producingPeerId:i,producingTransportId:s,handler:this.handler,appData:ee(H({},d),{screenShare:c,peerId:i}),rtpReceiver:X.receiver,mimeType:u});this.consumers.set(e,$),$.once("close",()=>{this.consumers.delete($.id),this.handler.midTransceiverMap.delete(X.mid)}),m.info("consumer created for ",{consumer:{id:e,kind:h,appData:{screenShare:c},peerId:i,producerId:n}}),this.observer.emit("newconsumer",$),clearTimeout(M),b($)}}catch(A){m.warn("error while creating consumer:",A),clearTimeout(M),w(E)}},F=this.unknownTracksMap.get(g);F?(this.unknownTracksMap.delete(g),D(F.track,F.transceiver)):this.consumerTrackEvents.set(g,D)}))})}setRemoteDescription(t){return p(this,null,function*(){yield this.handler.pc.setRemoteDescription(t)})}setLocalDescription(t){return p(this,null,function*(){m.debug(`${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(t)}]`),yield this.handler.pc.setLocalDescription(t)})}retryFailedConsumerCreationTasks(t){return p(this,null,function*(){return V2(t.map(e=>p(this,null,function*(){return um(n=>p(this,null,function*(){return n>0&&m.warn(`retrying failed consumer creation task: ${JSON.stringify(e)}`),this.createConsumerObjectAndWaitForTrack(H({},e))}))})))})}sendDataChannelMessage(t,e){return p(this,null,function*(){const n=this.getDatachannel(t);if(!n)throw R2("DC_NOT_READY",`${t} datachannel not ready`);const i=(yield n.request(e)).payload;return m.info(`sendDataChannelMessage::response ${JSON.stringify(i)}`),i})}};let U2=$h;Oo=new WeakMap;function B2(){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){m.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return m.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=sv.getParser(t),n=e.getEngine();if(e.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(e.satisfies({chrome:">=55",chromium:">=55"}))return;if(e.satisfies({firefox:">=110"}))return"Firefox110";if(e.satisfies({firefox:">=60"}))return"Firefox60";if(e.satisfies({ios:{OS:">=14.3",firefox:">=30.0"}})||e.satisfies({safari:">=12.0"})&&typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(e.satisfies({safari:">=11"})||e.satisfies({"microsoft edge":">=11"})&&e.satisfies({"microsoft edge":"<=18"}))return;if(n.name&&n.name.toLowerCase()==="blink"){const i=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);return i?Number(i[1])>=74?"Chrome74":void 0:"Chrome74"}if(n.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":void 0;m.warn("Device::this._detectDevice() | browser not supported");return}m.warn("Device::this._detectDevice() | unknown device")}var Cd;class F2{constructor(e,{handlerName:n,handlerFactory:i}={}){if(y(this,"handlerFactory"),S(this,Cd,void 0),m.debug("constructor()"),T(this,Cd,e),n&&i)throw new TypeError("just one of handlerName or handlerInterface can be given");if(i)this.handlerFactory=i;else{if(n)m.debug(`Device::constructor() | handler given: ${n}`);else if(n=B2(),n)m.debug(`Device::constructor() | detected handler: ${n}`);else throw new Error("device not supported");switch(n){case"Chrome74":this.handlerFactory=pm.createFactory();break;case"Safari12":this.handlerFactory=mm.createFactory();break;case"Firefox60":this.handlerFactory=fl.createFactory({supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=fl.createFactory({supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${n}"`)}}}createTransport(e){const n=Ia();return new U2(o(this,Cd),ee(H({id:n},e),{handlerFactory:this.handlerFactory}))}}Cd=new WeakMap;const j2=2e3;var ps,zo,Jt,Kt,ga,Yo,Do,No,Zr,or,Lo,Qo,Rd,Pd,Jh,Kh,F0,zh,j0,Yh,W0,Qh,H0,Xh,Hg,Ad,Ju,Md,Ku;class W2 extends Nt.EventEmitter{constructor(e,n,i){switch(super(),S(this,Qo),S(this,Pd),S(this,Kh),S(this,zh),S(this,Yh),S(this,Qh),S(this,Xh),S(this,Ad),S(this,Md),S(this,ps,void 0),S(this,zo,void 0),S(this,Jt,void 0),S(this,Kt,void 0),S(this,ga,void 0),S(this,Yo,void 0),S(this,Do,void 0),S(this,No,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0}),S(this,Zr,void 0),S(this,or,"all"),S(this,Lo,void 0),T(this,ps,e),T(this,ga,n),T(this,Lo,i),T(this,zo,new F2(i)),T(this,Yo,new O2(n,i)),i){case bt.CF:{T(this,Do,Wn);break}case bt.HIVE:default:{T(this,Do,_n);break}}o(this,Qo,Rd).mediaState={send:{state:ks.NEW,reconnected:!1},recv:{state:ks.NEW,reconnected:!1}},re.hasFeature(ue.FORCE_RELAY)&&T(this,or,"relay"),Q(this,Pd,Jh).call(this)}get socket(){return o(this,ga)}get socketHandler(){return o(this,Yo)}get sendTransport(){return o(this,Jt)}get recvTransport(){return o(this,Kt)}get events(){return o(this,Do)}get nodeType(){return o(this,Lo)}createTransports(e){return p(this,null,function*(){var n,i,s,r,a,c,d,h;re.hasFeature(ue.FORCE_RELAY)&&(m.info("ICE Transport Policy set to relay"),T(this,or,"relay"));const u=yield Pt().getICEServers().catch(E=>(m.warn(`failed to get iceservers from server: ${E.message}`),[])),g=[];if(e.send){const E=re.hasFeature(ue.DISABLE_OPUS_DTX_CF),b=Q(this,zh,j0).call(this,{iceServers:u,additionalSettings:{encodedInsertableStreams:(n=o(this,ps).getValue("modules").e2ee)==null?void 0:n.enabled},config:{enableHighBitrate:(r=(s=(i=o(this,ps).getValue("defaults").mediaConfiguration)==null?void 0:i.audio)==null?void 0:s.enableHighBitrate)!=null?r:!1,enableStereo:(d=(c=(a=o(this,ps).getValue("defaults").mediaConfiguration)==null?void 0:a.audio)==null?void 0:c.enableStereo)!=null?d:!1,enableDtx:o(this,Lo)===bt.HIVE?!0:!!E},iceTransportPolicy:o(this,or)});g.push(b)}if(e.recv){const E=Q(this,Yh,W0).call(this,{iceServers:u,additionalSettings:{encodedInsertableStreams:(h=o(this,ps).getValue("modules").e2ee)==null?void 0:h.enabled},iceTransportPolicy:o(this,or)});g.push(E)}yield Promise.all(g)})}stopTransports(e){var n,i;if(e.send&&this.sendTransport!==void 0){const{id:s,serverId:r,direction:a}=o(this,Jt);m.info("Closing send transport",{transport:{id:s,serverId:r,type:a}}),o(this,Jt).close(),o(this,Jt).removeAllListeners(),T(this,Jt,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:s,serverId:r,direction:a}=o(this,Kt);m.info("Closing recv transport",{transport:{id:s,serverId:r,type:a}}),(n=o(this,Kt))==null||n.close(),(i=o(this,Kt))==null||i.removeAllListeners(),T(this,Kt,void 0)}Q(this,Pd,Jh).call(this)}stopAllTransports(){m.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}connectTransportWithRetry(e){return p(this,null,function*(){const{id:n,serverId:i,direction:s}=e;Q(this,Qh,H0).call(this,e);try{const r=re.hasFeature(ue.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3;return yield um((a,c)=>p(this,null,function*(){a>0&&m.debug(`Retrying transport connect, count: ${a}`,{transport:{id:n,serverId:i,type:s}});try{if(e.closed)throw new gr("Cannot reconnect closed transport");yield Q(this,Kh,F0).call(this,e)}catch(d){if(d instanceof gr){c(d);return}throw m.error("Failed to connect transport, retrying",{transport:e,error:d}),d}}),{delayTime:100,strategy:"exponential",maxRetryCount:r}),e}catch(r){throw m.error(`Failed to connect send transport after retry: ${e.id}`,{error:r,transport:{id:n,serverId:i,type:s}}),e.close(),e.removeAllListeners(),r}})}handleErrors(e){throw new Error("Method not implemented.")}}ps=new WeakMap,zo=new WeakMap,Jt=new WeakMap,Kt=new WeakMap,ga=new WeakMap,Yo=new WeakMap,Do=new WeakMap,No=new WeakMap,Zr=new WeakMap,or=new WeakMap,Lo=new WeakMap,Qo=new WeakSet,Rd=function(){return o(this,ps).getValue("connectionHandler")},Pd=new WeakSet,Jh=function(){T(this,Zr,{send:void 0,recv:void 0})},Kh=new WeakSet,F0=function(t){return p(this,null,function*(){const{id:e,direction:n}=t;if(m.info(`Connecting ${n} transport`,{transport:{id:e,type:n}}),!o(this,ga).isConnected)throw new gr("Socket is not connected");if(t.connectionState==="closed")throw new gr("Transport is closed");try{yield t.connect(i=>Q(this,Xh,Hg).call(this,n,i)),m.info(`Connected ${n} transport`,{transport:{id:e,serverId:t.serverId,type:n}})}catch(i){throw o(this,No).transportFailureCount[n]+=1,i.message==="ice connection failed"?new gr(i.message):i}})},zh=new WeakSet,j0=function(t){return p(this,null,function*(){var e,n;if(o(this,Jt)&&o(this,Jt).connected){m.info("Transport send is already connected",{transport:{id:(e=o(this,Jt))==null?void 0:e.id,serverId:(n=o(this,Jt))==null?void 0:n.serverId,type:"send"}});return}T(this,Jt,o(this,zo).createTransport(ee(H({},t),{direction:"send"}))),ne.configureSendTransport(o(this,Jt))})},Yh=new WeakSet,W0=function(t){return p(this,null,function*(){var e,n;if(o(this,Kt)&&o(this,Kt).connected){m.info("Transport recv is already connected",{transport:{id:(e=o(this,Kt))==null?void 0:e.id,serverId:(n=o(this,Kt))==null?void 0:n.serverId,type:"recv"}});return}T(this,Kt,o(this,zo).createTransport(ee(H({},t),{direction:"recv"}))),ne.configureRecvTransport(o(this,Kt))})},Qh=new WeakSet,H0=function(t){const{direction:e,id:n}=t;t.on("connectionstatechange",i=>p(this,null,function*(){Q(this,Md,Ku).call(this,{state:i,direction:e}),m.info(`Transport connection state changed for ${e} transport`,{transport:{id:n,serverId:t.serverId,type:e,status:i}});const s=()=>{const r=o(this,Zr)[e];r!==void 0&&(clearTimeout(r),o(this,Zr)[e]=void 0)};switch(i){case"connected":s(),o(this,No).lastConnectionTime=performance.now();break;case"disconnected":o(this,Zr)[e]=setTimeout(()=>p(this,null,function*(){yield Q(this,Ad,Ju).call(this,t)}),j2);break;case"failed":if(t.closed)return;s(),yield Q(this,Ad,Ju).call(this,t);break}})),t.on("icecandidate",i=>p(this,null,function*(){m.debug("Sending iceCandidate:",{iceCandidate:i})})),t.on("datachannel:events",(i,s)=>p(this,null,function*(){var r,a;m.debug("Got data channel message on event:",{rtcChannel:{label:i,message:s}});try{switch(s.type){case"handshake":{const c={type:"handshake",payload:{message:"pong"}};t.sendResponseOverDC(i,B0(s),c);break}case"hub-disconnect":{m.debug(`media hub disconnected, full_reconnect: ${(r=s.payload)==null?void 0:r.full_reconnect}`),((a=s.payload)==null?void 0:a.full_reconnect)===!0&&this.handleErrors("rejoin");break}case"error":break;default:break}}catch(c){m.error(`Unable to handle the incoming datachannel message on channel ${i}`)}})),t.on("dc_error",()=>{t.direction==="recv"&&(m.warn("Events datachannel did not open in 5s",{country:k.location.country}),this.handleErrors("reconnectRecvTransport"))})},Xh=new WeakSet,Hg=function(t,e){return p(this,null,function*(){const n=t==="recv";try{const{sdp:i,type:s}=e,r={consuming:n,description:{sdp:i,type:s,target:n?Pi.SUBSCRIBER:Pi.PUBLISHER},producers:[]};return o(this,Yo).connectTransport(r)}catch(i){throw m.error(`Error in ${t} transport connection:`,{error:i,country:k.location.country}),i}})},Ad=new WeakSet,Ju=function(t){return p(this,null,function*(){m.info("Called reconnect transport",{transport:t}),t.close(),t.removeAllListeners();const{direction:e}=t;switch(re.hasFeature(ue.HIVE_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED)&&o(this,ga).isConnected&&o(this,No).transportFailureCount[e]>2&&(m.warn(`Multiple disconnections in ${e} transport, forcing relay`),T(this,or,"relay")),yield this.createTransports({[e]:!0}),e){case"send":{yield this.connectTransportWithRetry(o(this,Jt)),m.info("Transport reconnected",{transport:o(this,Jt)}),L.emit(x.RESET_PRODUCER_STATE);break}case"recv":{yield this.connectTransportWithRetry(o(this,Kt)),m.info("Transport reconnected",{transport:o(this,Kt)}),L.emit(x.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:m.warn("Unknown transport direction",{transport:t})}Q(this,Md,Ku).call(this,{state:ks.CONNECTED,direction:e})})},Md=new WeakSet,Ku=function(t){const{state:e,direction:n}=t;o(this,Qo,Rd).mediaState[n]={state:e,reconnected:!0},L.emit(x.TRANSPORT_STATE_UPDATE,H({transport:n},o(this,Qo,Rd).mediaState[n]))};var Zh,q0;class H2{constructor(e){S(this,Zh),this.recvTransport=e,Q(this,Zh,q0).call(this)}create(e){return p(this,null,function*(){if(!e||e&&e.length===0)throw new Error("List of producers is required");const n={type:"create_consumer",payload:{producers:e.map(({producerId:a,producingTransportId:c,kind:d,mimeType:h})=>({producerId:a,producingTransportId:c,preferredCodec:H(H({},d==="video"&&h?{video:h}:{}),d==="audio"&&h?{audio:h}:{})}))}},i=yield this.recvTransport.sendDataChannelMessage("events",n),s=new Map;e.forEach(a=>s.set(a.producerId,a));const r=new Map;return Object.entries(i).forEach(([a,c])=>{const d=s.get(c.producerId);d&&r.set(c.producerId,{consumerId:a,producingTransportId:d.producingTransportId,producingPeerId:d.producingPeerId,kind:d.kind,paused:d.pause,streamId:c.streamId,trackId:c.trackId,screenShare:d.screenShare,mimeType:d.mimeType,appData:{}})}),{consumerStates:r}})}negotiate(e,n,i){return p(this,null,function*(){try{m.debug(`Received offer over dc: ${e.sdp} for transport`);const s=yield this.recvTransport.setRemoteOffer(e),r={type:"answer",payload:{type:s.type,sdp:s.sdp}};return m.debug(`datachannel answer: ${JSON.stringify(r)}`),this.recvTransport.sendResponseOverDC(i,n,r),s}catch(s){throw m.error("datachannel:events::Error:",s),s.code!=="DC_NOT_FOUND"&&this.recvTransport.sendErrorOverDC(i,n,s),s}})}close(e){return p(this,null,function*(){if(!e.length)return{};const n=e.map(a=>a.id);m.info(`Closing consumers: ${JSON.stringify(n)}`);const i={type:"close_consumers",payload:{consumers:n}},s=yield this.recvTransport.sendDataChannelMessage("events",i),{failedConsumers:r}=s;return{failedConsumers:r}})}}Zh=new WeakSet,q0=function(){this.recvTransport.on("datachannel:events",(t,e)=>p(this,null,function*(){try{switch(e.type){case"negotiation":{const{sdp:n}=e.payload,i={sdp:n,type:"offer"};this.negotiate(i,B0(e),t);break}default:break}}catch(n){m.error(`Unable to handle the incoming datachannel message on channel ${t}`)}}))};class q2{constructor(e,n,i,s){this.events=e,this.recvTransport=n,this.socket=i,this.socketHandler=s}create(e){return p(this,null,function*(){if(!e||e&&e.length===0)throw new Error("List of producers is required");const n=new Map,i=[];e.forEach(d=>{const{producingPeerId:h,producerId:u,producingTransportId:g}=d;n.set(u,h),i.push({producingPeerId:h,producerId:u,producingTransportId:g})});const s=yield this.socketHandler.consume({requests:i,consumingTransportId:this.recvTransport.serverId}),r=new Map;e.forEach(d=>r.set(d.producerId,d));const a=new Map,c=[];return Object.entries(s.consumerStateMap).forEach(([d,h])=>{const u=r.get(d);if(!u)return;if(h.errorCode){if(m.warn(`Consumer request failed for producer ${d}`,{error:{message:h.errorCode}}),h.errorCode==="not_found_track_error"){m.error(`Track not found for producer: ${u.producerId}. This will not be retried.`);return}c.push(u);return}let g={};try{g=JSON.parse(h.producerState.appData)}catch(E){}a.set(d,{consumerId:h.consumerId,producingTransportId:u.producingTransportId,producingPeerId:u.producingPeerId,kind:u.kind,paused:u.pause,streamId:h.producerTrack.streamId,trackId:h.producerTrack.trackId,screenShare:u.screenShare,mimeType:u.mimeType,appData:g})}),{consumerStates:a,sessionDescription:s.sessionDescription,failedProducers:c}})}negotiate(e){return p(this,null,function*(){try{m.info("Negotiating socket consumer",{transport:this.recvTransport}),m.debug(`setting remote offer: ${JSON.stringify(e)} on recvTransport`,{transport:this.recvTransport});const n=yield this.recvTransport.setRemoteOffer(e),i={transportId:this.recvTransport.serverId,description:{sdp:n.sdp,type:n.type,target:Pi.SUBSCRIBER}};return m.debug(`sending renegotiate request: ${JSON.stringify(i)} on recvTransport`,{transport:this.recvTransport}),yield this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,TP.toBinary(i)),m.info("Renegotiation done",{transport:this.recvTransport}),n}catch(n){m.error("Failed to renegotiate",{error:n});return}})}close(e){return p(this,null,function*(){if(!e.length)return{};const n=(i,s)=>p(this,null,function*(){const r=i.map(h=>h.localId);m.info(`Closing consumers: ${JSON.stringify(r)}`);const a={description:{sdp:s.sdp,type:s.type,target:Pi.SUBSCRIBER},consumerIds:r,consumingTransportId:this.recvTransport.serverId},c=yield this.socketHandler.closeConsumer(a),d=H1.fromBinary(c).description;return{sdp:d.sdp,type:d.type}});return this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(e,n),"close_consumer"),{}})}}class fm{constructor(e){this.socketHandler=e}static getMSIDFromSDP(e,n){return qo(e).media.filter(i=>n==="video"?i.type==="video":i.type==="audio").at(-1).msid}create(e){return p(this,arguments,function*({offer:n,kind:i,paused:s,appData:r,codecOptions:a,producingTransportId:c}){var d,h;const u=fm.getMSIDFromSDP(n.sdp,i),g={description:{sdp:n.sdp,type:n.type,target:Pi.PUBLISHER},paused:s,kind:i,msid:u,appData:JSON.stringify(r),screenShare:(d=r.screenShare)!=null?d:!1,mimeType:`${i}/${(h=a[0])==null?void 0:h.name}`,producingTransportId:c},{answer:E,producerId:b}=yield this.socketHandler.produce(g);return{answer:E,producerId:b}})}}var Xo,ha,lr,Zo,Od,Ti,ep,gs,ec,tp,G0,vl,np,ip,$0,sp,J0,rp,K0,ap,z0,op,qg,cp,Gg;class G2 extends W2{constructor(e,n,i){super(e,n,i),S(this,tp),S(this,vl),S(this,ip),S(this,sp),S(this,rp),S(this,ap),S(this,op),S(this,cp),S(this,Xo,void 0),S(this,ha,void 0),S(this,lr,void 0),S(this,Zo,void 0),S(this,Od,void 0),S(this,Ti,void 0),S(this,ep,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0}),S(this,gs,[]),S(this,ec,void 0),T(this,Xo,e),o(this,tp,G0).mediaState={send:{state:ks.NEW,reconnected:!1},recv:{state:ks.NEW,reconnected:!1}},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return o(this,ha)}get consumers(){return o(this,lr)}get producerIdToConsumerIdMap(){return o(this,Zo)}reset(){T(this,ha,new Map),T(this,lr,new Map),T(this,Zo,new Map)}setupTransports(e){return p(this,null,function*(){yield this.createTransports(e);let n,i;e.send&&(n=Q(this,ip,$0).call(this)),e.recv&&(i=Q(this,sp,J0).call(this)),yield Promise.all([n,i])})}createProducer(e,n){return p(this,null,function*(){var i;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const s=yield this.sendTransport.produce(e,Q(this,rp,K0).bind(this));return(i=e.appData)!=null&&i.e2ee&&L.emit(x.E2EE_ACTIVE_PRODUCER,s),Q(this,ap,z0).call(this,s,n),s}catch(s){throw m.error("Failed to create producer",{error:s}),o(this,ep).producerCreationFailureCount+=1,s}})}closeProducer(e,n){return p(this,null,function*(){var i;const s=this.producers.get(e);if(!s){m.warn(`Producer with ID ${e} was not found`);return}n!=null&&n.stopTrack&&s.track.stop();try{yield this.sendTransport.closeProducer(s),(i=o(this,Xo).getValue("modules").e2ee)!=null&&i.enabled&&L.emit(x.E2EE_INACTIVE_PRODUCER,s)}catch(r){m.error("Failed to close producer on server",{error:r,producer:s})}})}closeAllProducers(){return Promise.all(Array.from(o(this,ha).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}createConsumers(e){return p(this,null,function*(){o(this,ec)||clearTimeout(o(this,ec)),T(this,gs,o(this,gs).concat(e)),yield Q(this,vl,np).call(this)})}closeConsumer(e){return this.closeConsumers([e])}closeConsumers(e){return p(this,null,function*(){if(!o(this,Ti))return;const n=e.map(s=>this.consumers.get(s)).filter(s=>s!==void 0);if(n.length===0)return;const{failedConsumers:i}=yield o(this,Ti).close(n);i!=null&&i.length&&m.warn("Failed to close some consumers",{consumerIds:i})})}closeAllConsumers(){return this.closeConsumers(Array.from(o(this,lr).keys()))}switchConsumersToLayer(e,n){return p(this,null,function*(){const i=this.recvTransport.getDatachannel("events");if(!i){m.warn("events datachannel not found");return}const s={type:"switch_consumer_layer",payload:{consumerIds:e,layer:n}};yield i.request(s),m.info(`Consumers switched layers to ${n}`,{consumerIds:e})})}}Xo=new WeakMap,ha=new WeakMap,lr=new WeakMap,Zo=new WeakMap,Od=new WeakMap,Ti=new WeakMap,ep=new WeakMap,gs=new WeakMap,ec=new WeakMap,tp=new WeakSet,G0=function(){return o(this,Xo).getValue("connectionHandler")},vl=new WeakSet,np=function(){return p(this,null,function*(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const t=500,e=o(this,gs).splice(0,o(this,gs).length);try{const n=e.filter(({producerId:r})=>!this.producers.get(r));if(n.length===0)return;const{consumers:i,failedProducers:s}=yield this.recvTransport.consume(n,Q(this,op,qg).bind(this),o(this,Ti).negotiate.bind(o(this,Ti)));i.forEach(Q(this,cp,Gg).bind(this)),s!=null&&s.length&&(m.error("Failed to create consumers for producers",{producers:s}),T(this,gs,o(this,gs).concat(s)),T(this,ec,setTimeout(Q(this,vl,np).bind(this),t)))}catch(n){m.error("failed to consume on transport",{error:n})}})},ip=new WeakSet,$0=function(){return p(this,null,function*(){yield this.connectTransportWithRetry(this.sendTransport),T(this,Od,new fm(this.socketHandler))})},sp=new WeakSet,J0=function(){return p(this,null,function*(){switch(this.recvTransport.on("connect",()=>{o(this,Zo).clear()}),yield this.connectTransportWithRetry(this.recvTransport),this.nodeType){case bt.CF:{T(this,Ti,new q2(this.events,this.recvTransport,this.socket,this.socketHandler));break}case bt.HIVE:default:T(this,Ti,new H2(this.recvTransport))}})},rp=new WeakSet,K0=function(t){return o(this,Od).create(t)},ap=new WeakSet,z0=function(t,e){t.on("close",(n,i)=>p(this,null,function*(){const{offer:s,reason:r}=n;if(m.info("producer::closing",{debuggingHint:r,producer:ee(H({},t),{status:"closing"})}),r!==gl){const a={producerId:t.id,description:{sdp:s.sdp,type:s.type,target:Pi.PUBLISHER}};try{const c=yield this.socketHandler.closeProducer(a),d={sdp:c==null?void 0:c.sdp,type:c==null?void 0:c.type};m.info("producer::closed",{producer:ee(H({},t),{status:"closed"})}),i({answer:d})}catch(c){m.error("producer close error",c)}}this.producers.delete(t.id),e()})),t.on("trackended",()=>{m.info("producer::trackended",{producer:ee(H({},t),{status:"UNKNOWN"})})}),o(this,ha).set(t.id,t)},op=new WeakSet,qg=function(t){return p(this,null,function*(){try{return yield this.recvTransport.canConsume(),yield o(this,Ti).create(t)}catch(e){throw m.error("Error in consume request",{error:e}),e}})},cp=new WeakSet,Gg=function(t){t.on("close",e=>p(this,null,function*(){m.debug("consumer closed",{consumer:{closureReason:e,id:t.id,kind:t.kind,appData:t.appData}}),o(this,lr).delete(t.id),L.emit(x.CONSUMER_CLOSED,{id:t.id})})),o(this,lr).set(t.id,t),this.producerIdToConsumerIdMap.set(t.producerId,t.id),L.emit(x.NEW_CONSUMER,{id:t.id,appData:t.appData,peerId:t.peerId})};var Dd,Nd,Ld,xo,tc,nc,yl,El,Vo,pn,ai,ti,zs,Ys,ms,Sl,dp,Y0,lp,Q0,up,X0,hp,Z0;const pp=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:n=3,hangoverFrames:i=5,noiseAdaptationRate:s=.95,voiceAdaptationRate:r=.99,minEnergyThreshold:a=.005,maxEnergyThreshold:c=.2,energyRatioThreshold:d=1.5,noiseHistorySize:h=50}={}){S(this,dp),S(this,lp),S(this,Dd,void 0),S(this,Nd,void 0),S(this,Ld,void 0),S(this,xo,void 0),S(this,tc,void 0),S(this,nc,void 0),S(this,yl,void 0),S(this,El,void 0),S(this,Vo,void 0),S(this,pn,void 0),S(this,ai,void 0),S(this,ti,!1),S(this,zs,0),S(this,Ys,0),S(this,ms,[]),S(this,Sl,void 0),T(this,xo,t),T(this,pn,t),T(this,Dd,e),T(this,Nd,n),T(this,Ld,i),T(this,tc,s),T(this,nc,r),T(this,yl,a),T(this,El,c),T(this,Vo,d),T(this,Sl,h),T(this,ai,t/2)}get voiceDetected(){return o(this,ti)}processAudioChunk(t){var e,n;const i=Q(e=pp,up,X0).call(e,t),s=Q(n=pp,hp,Z0).call(n,t);return Q(this,dp,Y0).call(this,i),i/o(this,ai)>o(this,Vo)&&i>o(this,pn)&&s>o(this,Dd)?(T(this,zs,o(this,zs)+1),T(this,Ys,o(this,Ld)),o(this,zs)>=o(this,Nd)&&T(this,ti,!0)):(T(this,zs,0),o(this,Ys)>0?T(this,Ys,o(this,Ys)-1):o(this,ti)&&T(this,ti,!1),o(this,ti)||Q(this,lp,Q0).call(this,i)),{energy:i,isVoice:o(this,ti)}}reset(){T(this,ti,!1),T(this,zs,0),T(this,Ys,0),T(this,pn,o(this,xo)),T(this,ai,o(this,xo)/2),T(this,ms,[])}getThresholdInfo(){return{currentEnergyThreshold:o(this,pn),backgroundNoiseEnergy:o(this,ai),energyRatioThreshold:o(this,Vo)}}};let mp=pp;Dd=new WeakMap,Nd=new WeakMap,Ld=new WeakMap,xo=new WeakMap,tc=new WeakMap,nc=new WeakMap,yl=new WeakMap,El=new WeakMap,Vo=new WeakMap,pn=new WeakMap,ai=new WeakMap,ti=new WeakMap,zs=new WeakMap,Ys=new WeakMap,ms=new WeakMap,Sl=new WeakMap,dp=new WeakSet,Y0=function(t){o(this,ti)?T(this,pn,o(this,nc)*o(this,pn)+(1-o(this,nc))*t):T(this,pn,o(this,tc)*o(this,pn)+(1-o(this,tc))*o(this,ai)),T(this,pn,Math.max(o(this,yl),Math.min(o(this,El),o(this,pn))))},lp=new WeakSet,Q0=function(t){if(t<o(this,pn)*1.2)if(o(this,ms).push(t),o(this,ms).length>o(this,Sl)&&o(this,ms).shift(),o(this,ms).length>=10){const e=[...o(this,ms)].sort((i,s)=>i-s),n=Math.floor(e.length/2);T(this,ai,e[n])}else T(this,ai,.95*o(this,ai)+.05*t)},up=new WeakSet,X0=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,n)=>e+n)/t.length)},hp=new WeakSet,Z0=function(t){let e=0;for(let n=1;n<t.length;n+=1)(t[n]>=0&&t[n-1]<0||t[n]<0&&t[n-1]>=0)&&(e+=1);return e},S(mp,up),S(mp,hp);const $2=60,J2=400;var ss,rs,oi,ur,hr,Uo,va,ic,as,Qs,sc,fp,eE,xd,gp,vp,tE,zu,$g;const Tl=class{constructor(t){S(this,fp),S(this,vp),S(this,ss,void 0),S(this,rs,void 0),S(this,oi,void 0),S(this,ur,void 0),S(this,hr,void 0),S(this,Uo,void 0),S(this,va,void 0),S(this,ic,void 0),S(this,as,void 0),S(this,Qs,void 0),S(this,sc,void 0),this.reportRequest=t,T(this,ur,new AudioContext),T(this,hr,o(this,ur).createAnalyser()),o(this,hr).fftSize=2048,T(this,ic,new mp)}set producerId(t){T(this,oi,t)}set audioTrack(t){T(this,Uo,t);const e=new MediaStream;e.addTrack(o(this,Uo)),o(this,ur).createMediaStreamSource(e).connect(o(this,hr))}start(){m.debug(`AudioActivityReporter: Starting audio activity reporter: ${o(this,oi)}`),o(this,ss)&&da(o(this,ss)),T(this,ss,Yd(()=>p(this,null,function*(){var t;if(!o(this,Uo)||!o(this,oi))return;const{energy:e}=Q(this,fp,eE).call(this),n=Q(t=Tl,xd,gp).call(t,e);let i=.9;o(this,sc)!==n&&o(this,sc)?i=.9:n?i=.3:i=.5,T(this,va,(o(this,va)||0)*(1-i)+e*i)}),$2)),o(this,rs)&&da(o(this,rs)),T(this,rs,Yd(Q(this,vp,tE).bind(this),J2))}stop(){try{m.debug(`AudioActivityReporter: Stopping audio activity reporter: ${o(this,oi)}`),o(this,ss)&&(da(o(this,ss)),T(this,ss,void 0)),o(this,rs)&&(da(o(this,rs)),T(this,rs,void 0))}catch(t){}o(this,ic).reset()}};let yp=Tl;ss=new WeakMap,rs=new WeakMap,oi=new WeakMap,ur=new WeakMap,hr=new WeakMap,Uo=new WeakMap,va=new WeakMap,ic=new WeakMap,as=new WeakMap,Qs=new WeakMap,sc=new WeakMap,fp=new WeakSet,eE=function(){var t;o(this,ur).state==="suspended"&&o(this,ur).resume().then(()=>{m.debug("AudioActivityReporter: AudioContext forced resumed")}).catch(r=>{m.error("AudioActivityReporter: Error resuming AudioContext",r)});const e=new Float32Array(o(this,hr).frequencyBinCount);o(this,hr).getFloatTimeDomainData(e);const{energy:n,isVoice:i}=o(this,ic).processAudioChunk(e),s=Q(t=Tl,zu,$g).call(t,n);return re.hasFeature(ue.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&m.debug(`AudioActivityReporter: producer: ${o(this,oi)}, energy: ${o(this,va)},
25
+ slogScale: ${s}, isVoice: ${i}, minEnergy: ${o(this,as)},
26
+ maxEnergy: ${o(this,Qs)}`),s===-1/0||n<1e-6?{energy:0,isVoice:!1}:((!o(this,as)||s<o(this,as))&&T(this,as,s),(!o(this,Qs)||s>o(this,Qs))&&T(this,Qs,s),{energy:(s-o(this,as))/(o(this,Qs)-o(this,as))*10||0,isVoice:i})},xd=new WeakSet,gp=function(t){return t<5},vp=new WeakSet,tE=function(t=o(this,va)){var e;if(!o(this,oi)||!t){re.hasFeature(ue.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&m.debug(`AudioActivityReporter: No producerId or energy to report: ${o(this,oi)}`);return}const n={producerId:o(this,oi),energy:Math.round(t),silent:Q(e=Tl,xd,gp).call(e,t)};T(this,sc,n.silent),this.reportRequest(n)},zu=new WeakSet,$g=function(t){const e=Math.log10(t);return Math.round(e)},S(yp,xd),S(yp,zu);const K2=(t=!1)=>{const e=new window.AudioContext,n=e.createOscillator();n.type="triangle",n.frequency.setValueAtTime(20,e.currentTime);const i=e.createGain();i.gain.setValueAtTime(0,e.currentTime),n.connect(i);const s=e.createMediaStreamDestination();i.connect(s),n.start();const r=s.stream.getAudioTracks()[0];return r.enabled=t,r},z2=(t=!1)=>{var e,n;const i=new MediaStream().getVideoTracks()[0],s=document.createElement("canvas");s.height=(e=i==null?void 0:i.getSettings().height)!=null?e:720,s.width=(n=i==null?void 0:i.getSettings().width)!=null?n:1280;const r=s.getContext("2d");r.fillStyle="black",r.fillRect(0,0,s.width,s.height),setInterval(()=>{r.fillStyle="black",r.fillRect(0,0,s.width,s.height)},1e3);const a=s.captureStream().getVideoTracks()[0];return a.enabled=t,a};var Y2=Object.defineProperty,Q2=Object.getOwnPropertyDescriptor,Te=(t,e,n,i)=>{for(var s=i>1?void 0:i?Q2(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&Y2(e,n,s),s};const Qn=["video/VP9","video/VP8"];var Vd,Ud,Ht,te,Bo,Xs,nn,ea,ta,Zs,Bd,os,Fo,na,ia,sn,un,er,sa,Ot,qt,ra,jo,Ep,nE,Sp,iE,Tp,sE;class Se{constructor(e,n,i){S(this,er),S(this,Ot),S(this,ra),S(this,Ep),S(this,Sp),S(this,Tp),y(this,"context"),y(this,"authToken"),y(this,"e2ee"),S(this,Vd,void 0),S(this,Ud,void 0),S(this,Ht,void 0),S(this,te,void 0),S(this,Bo,void 0),S(this,Xs,void 0),S(this,nn,void 0),S(this,ea,void 0),S(this,ta,void 0),S(this,Zs,void 0),S(this,Bd,void 0),S(this,os,void 0),S(this,Fo,void 0),S(this,na,void 0),S(this,ia,void 0),S(this,sn,void 0),S(this,un,void 0),y(this,"partialJoinRoomPromise");var s,r;this.context=e;const{socket:a}=i;this.mediaJoined=!1,T(this,na,new Map([["video/VP9",new Set],["video/VP8",new Set]])),T(this,ia,new Map([["video/VP9",new Set],["video/VP8",new Set]])),T(this,Xs,n),T(this,Ht,a),T(this,ea,!1),T(this,te,new G2(e,a,n)),T(this,nn,o(this,te).events),T(this,os,new Set),T(this,sn,new Map),T(this,ta,!1),T(this,Zs,new ml),n===bt.CF&&!navigator.isReactNative&&T(this,un,new yp(o(this,te).socketHandler.audioActivity.bind(o(this,te).socketHandler))),this.e2ee=(r=(s=e.getValue("modules").e2ee)==null?void 0:s.enabled)!=null?r:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),T(this,Bd,al(()=>p(this,null,function*(){if(!o(this,er,sa).mediaJoinAttempted)return;const{roomJoined:c}=yield this.joinRoom(o(this,Ud),o(this,Vd),{},!0,!0);c&&(L.emit(x.RESET_PRODUCER_STATE),L.emit(x.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get mediaJoined(){return o(this,er,sa).mediaJoined}set mediaJoined(e){o(this,er,sa).mediaJoined=e}reset(e=!0){o(this,te).closeAllProducers(),o(this,te).closeAllConsumers(),o(this,sn).clear(),o(this,os).clear(),e&&(this.partialJoinRoomPromise=void 0,o(this,Zs).stop(),o(this,te).stopAllTransports(),o(this,te).reset(),T(this,Zs,new ml))}joinRoom(e,n){return p(this,arguments,function*(i,s,r={},a=!1,c=!1){o(this,er,sa).mediaJoinAttempted=!0,T(this,ea,!0),this.reset(a);const d=Pt().ipInfo;if(d!=null&&d.loc&&!o(this,Fo)){const u=d.loc.split(",");T(this,Fo,{latitude:parseFloat(u[0]),longitude:parseFloat(u[1])})}let h;try{return h=yield o(this,Zs).push(()=>this._joinRoom(i,s,r,c,o(this,Fo)),"joinRoom"),h}catch(u){h={roomJoined:!1}}return h.roomJoined||L.emit(x.ROOM_NODE_FAILED),h})}_partialJoinRoom(e,n,i=!1,s=void 0){return p(this,null,function*(){var r;const{ipInfo:a}=Pt();let c=s;if(a!=null&&a.loc&&!s){const[u,g]=a.loc.split(",").map(parseFloat);c={latitude:u,longitude:g}}const d=(r=re.getValue(ue.FORCE_VIDEO_CODEC))==null?void 0:r.toString(),h=M2(d);T(this,Bo,h),yield um((u,g)=>p(this,null,function*(){if(!o(this,Ht).isConnected){g(new Error("socket is not connected"));return}u>0&&m.warn(`retrying sending join room request, count: ${u}`);try{yield o(this,te).socketHandler.joinRoom(n,e,h,i,c)}catch(E){throw m.error("failed to send join room request, error:",{error:E}),E}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:re.hasFeature(ue.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),yield o(this,te).setupTransports({send:!0,recv:!0}),o(this,Xs)!==bt.HIVE&&re.hasFeature(ue.PRECREATE_PRODUCERS)&&(this.shareWebcam(z2()),this.shareMic(K2()))})}partialJoinRoom(e,n,i=!1,s=void 0){return p(this,null,function*(){return this.partialJoinRoomPromise=o(this,Zs).push(()=>this._partialJoinRoom(e,n,i,s)),this.partialJoinRoomPromise})}_joinRoom(e,n){return p(this,arguments,function*(i,s,r={},a=!1,c=null){T(this,Ud,i);try{this.partialJoinRoomPromise?yield this.partialJoinRoomPromise:yield this._partialJoinRoom(i,s,a,c)}catch(d){m.error("error in partial join room",{error:d})}finally{this.partialJoinRoomPromise=void 0}try{return navigator.product!=="ReactNative"&&setTimeout(()=>p(this,null,function*(){const d={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:s,roomViewType:"groupCall",deviceInfo:ee(H({},Be.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};ne.roomJoined(d)})),{roomJoined:yield this.completeJoinRoom()}}catch(d){return m.error("error on sending join room request",{error:d}),{roomJoined:!1}}})}completeJoinRoom(){return p(this,null,function*(){try{this.mediaJoined=!0;const{roomState:e}=yield o(this,te).socketHandler.notifySelfJoinComplete();return T(this,Vd,e.roomUuid),T(this,ta,!0),T(this,ea,!1),!0}catch(e){return m.error("error on completing join room:",{error:e}),this.mediaJoined=!1,!1}})}leaveRoom(){return p(this,null,function*(){o(this,te).stopAllTransports(),T(this,ta,!1),o(this,er,sa).mediaJoinAttempted=!1;const e={closeRoom:!1};o(this,Ht).sendMessagePromise(o(this,nn).leaveRoom,GP.toBinary(e)).then(n=>{var i;(i=P1.fromBinary(n.payload))!=null&&i.closed||m.warn("weird state on peer closed and should not happen")}).catch(n=>{m.error("error on sending leave room request",{error:n})}),ne.callEnded(),k.destruct()})}getConsumers(){return o(this,te).consumers}activatePeers(e){return p(this,null,function*(){return this.createConsumers(e)})}deactivatePeers(e,n="default"){return p(this,null,function*(){const i=new Set;e.forEach(r=>{r.screenShare&&r.kind==="video"&&i.add(r.producingPeerId)});const s=n==="default"?e.filter(r=>!i.has(r.producingPeerId)).filter(r=>r.kind!=="audio"):e;yield Promise.all(s.map(r=>{const a=o(this,te).producerIdToConsumerIdMap.get(r.producerId);if(!a){m.warn(`consumer not found in deactivate producers: ${r.producerId}`);return}return o(this,te).closeConsumer(a)}))})}createConsumers(e){return p(this,null,function*(){return e.length===0?Promise.resolve():o(this,te).createConsumers(e)})}closeConsumers(e){return p(this,null,function*(){if(!e.length)return;const n=e.reduce((i,s)=>{const r=o(this,te).producerIdToConsumerIdMap.get(s.producerId);return r?(i.push(r),i):(m.warn(`consumer not found in deactivate producers: ${s.producerId}`),i)},[]);yield o(this,te).closeConsumers(n)})}_shareWebcam(e,n){return p(this,null,function*(){const i=n==="video/VP9"?De.WEBCAM:De.WEBCAM_BACKUP,s=Q(this,Ot,qt).call(this,i);if(s){const u=yield s;if(o(this,te).producers.has(u)){const g=o(this,te).producers.get(u);if(!g.closed&&!navigator.isReactNative)return yield g.replaceTrack({track:e}),yield this.resumeWebcam(i),e;yield this.disableWebcam(n)}return this._shareWebcam(e,n)}const r=Q(this,Tp,sE).call(this,e,n),a=cl(this.context,"disableSimulcast"),c=o(this,Xs)===bt.CF?ue.ENABLE_CF_SIMULCAST:ue.ENABLE_HIVE_SIMULCAST;!a&&re.hasFeature(c)?(m.info(`Simulcast enabled for SFU: ${o(this,Xs)}`),r.encodings=IL(e)):m.info(`Simulcast disabled for webcam producer, SFU: ${o(this,Xs)}`),re.hasFeature(ue.TRACK_HINT)&&(r.track.contentHint=re.getValue(ue.TRACK_HINT));const d=()=>{m.info("Disabling video due to the producer closure"),o(this,sn).delete(i)},h=o(this,te).createProducer(r,d);return Q(this,ra,jo).call(this,i,h.then(u=>u.id)),h.then(u=>u.track)})}shareWebcam(e){return p(this,null,function*(){if(e===void 0)return null;if(re.hasFeature(ue.FORCE_VIDEO_CODEC)){const n=re.getValue(ue.FORCE_VIDEO_CODEC).toString();if(n)return m.debug(`Calling _shareWebcam with forced video codec: ${n}`),this._shareWebcam(e,n)}return yield Promise.all(Qn.map(n=>{var i,s;return((s=(i=o(this,Bo).sender)==null?void 0:i.video)==null?void 0:s.codecs.findIndex(r=>r.mimeType===n))>=0&&o(this,ia).get(n).size>0?(m.debug(`Calling _shareWebcam with video codec: ${n}`),this._shareWebcam(e,n)):e})),e})}shareScreen(e){return p(this,null,function*(){const{video:n,audio:i}=e;if(n===void 0)return;const s={track:n,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Be.isElectron()},stopTracks:!1},r=()=>{m.info("Disabling screenShare due to the producer closure"),o(this,sn).delete(De.SCREENSHARE_VIDEO),o(this,sn).delete(De.SCREENSHARE_AUDIO)},a=o(this,te).createProducer(s,r);Q(this,ra,jo).call(this,De.SCREENSHARE_VIDEO,a.then(d=>d.id));let c;if(i){const d={track:i,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Be.isElectron()},stopTracks:!1,zeroRtpOnPause:!0},h=()=>{};c=o(this,te).createProducer(d,h),Q(this,ra,jo).call(this,De.SCREENSHARE_AUDIO,c.then(u=>u.id))}yield Promise.all([a,c||Promise.resolve()]),ne.screenShareStart()})}shareMic(e){return p(this,null,function*(){try{if(e===void 0)throw new rn("track undefined");const n=Q(this,Ot,qt).call(this,De.MIC);if(n){const a=yield n;if(o(this,te).producers.has(a)){const c=o(this,te).producers.get(a);if(!c.closed&&!navigator.isReactNative){yield c.replaceTrack({track:e}),yield this.resumeMic(),o(this,un)&&(o(this,un).audioTrack=e,o(this,un).producerId=a,o(this,un).start());return}yield o(this,te).closeProducer(a,{stopTrack:!1})}yield this.shareMic(e);return}const i=Q(this,Sp,iE).call(this,e),s=()=>{o(this,sn).delete(De.MIC)},r=o(this,te).createProducer(i,s);Q(this,ra,jo).call(this,De.MIC,r.then(a=>a.id)),yield r.then(a=>{o(this,un)&&(o(this,un).audioTrack=a.track,o(this,un).producerId=a.id,o(this,un).start())})}catch(n){throw new O(n)}})}pauseMic(){return p(this,null,function*(){var e;const n=yield Q(this,Ot,qt).call(this,De.MIC),i=o(this,te).producers.get(n);if(!i){m.error("pauseMic::could_not_find_mic_producer");return}if(i.paused){m.info("pauseMic::mic_producer_already_paused");return}i.pause(),(e=o(this,un))==null||e.stop();const s={producerId:i.id,pause:!0};o(this,Ht).sendMessage(o(this,nn).toggleProducer,xc.toBinary(s))})}pauseWebcam(){return p(this,null,function*(){const e=yield Q(this,Ot,qt).call(this,De.WEBCAM),n=yield Q(this,Ot,qt).call(this,De.WEBCAM_BACKUP),i=o(this,te).producers.get(e),s=o(this,te).producers.get(n);if(!i&&!s){m.error("pauseWebcam::could_not_find_webcam_producer");return}const r=a=>{const c={producerId:a.id,pause:!0};o(this,Ht).sendMessage(o(this,nn).toggleProducer,xc.toBinary(c))};i&&(i.pause(),r(i)),s&&(s.pause(),r(s))})}resumeMic(){return p(this,null,function*(){const e=yield Q(this,Ot,qt).call(this,De.MIC),n=o(this,te).producers.get(e);if(!n){m.error("resumeMic::could_not_find_mic_producer");return}if(!n.pause){m.info("resumeMic::mic_producer_already_resumed");return}n.resume(),n.appData.e2ee&&L.emit(x.E2EE_ACTIVE_PRODUCER,n);const i={producerId:n.id,pause:!1};o(this,Ht).sendMessage(o(this,nn).toggleProducer,xc.toBinary(i))})}resumeWebcam(){return p(this,arguments,function*(e=De.WEBCAM){const n=yield Q(this,Ot,qt).call(this,e),i=o(this,te).producers.get(n);if(!i){m.error("resumeWebcam::could_not_find_webcam_producer");return}if(!i.paused){m.info("resumeWebcam::webcam_producer_already_resumed");return}i.resume(),i.appData.e2ee&&L.emit(x.E2EE_ACTIVE_PRODUCER,i);const s={producerId:i.id,pause:!1};o(this,Ht).sendMessage(o(this,nn).toggleProducer,xc.toBinary(s))})}disableWebcam(e){return p(this,null,function*(){const n=e==="video/VP9"?De.WEBCAM:De.WEBCAM_BACKUP,i=yield Q(this,Ot,qt).call(this,n);Q(this,Ep,nE).call(this,n),i&&(yield o(this,te).closeProducer(i))})}disableMic(){return p(this,null,function*(){var e;const n=yield Q(this,Ot,qt).call(this,De.MIC);n&&(yield o(this,te).closeProducer(n)),(e=o(this,un))==null||e.stop(),o(this,sn).delete(De.MIC)})}disableScreenShare(){return p(this,null,function*(){m.info("screen_sharing_stopped"),ne.screenShareStop();const e=yield Q(this,Ot,qt).call(this,De.SCREENSHARE_VIDEO),n=yield Q(this,Ot,qt).call(this,De.SCREENSHARE_AUDIO);e&&(yield o(this,te).closeProducer(e)),n&&(yield o(this,te).closeProducer(n)),o(this,os).clear(),o(this,sn).delete(De.SCREENSHARE_VIDEO),o(this,sn).delete(De.SCREENSHARE_AUDIO)})}muteSelf(){return p(this,null,function*(){this.pauseMic()})}unmuteSelf(){return p(this,null,function*(){})}resetVideoProducers(e,n){return p(this,null,function*(){if(e){const i=yield Q(this,Ot,qt).call(this,De.WEBCAM),s=yield Q(this,Ot,qt).call(this,De.WEBCAM_BACKUP);yield o(this,te).closeProducer(i,{stopTrack:!1}),yield o(this,te).closeProducer(s,{stopTrack:!1}),this.shareWebcam(e)}if(n){const i=yield Q(this,Ot,qt).call(this,De.SCREENSHARE_VIDEO);yield o(this,te).closeProducer(i,{stopTrack:!1}),this.shareScreen({video:n})}})}changeDisplayName(e,n){return p(this,null,function*(){const i={displayName:e,participantId:n!=null?n:this.peerId};if(!(yield o(this,te).socketHandler.changeDisplayName(i)))throw new Error("failed to change display name!")})}kick(e){const n={peerIds:[e]};o(this,te).socketHandler.kickPeer(n)}kickAll(){o(this,te).socketHandler.kickAll()}muteAll(e){return p(this,null,function*(){if(!(yield o(this,te).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return p(this,null,function*(){if(!(yield o(this,te).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(e){return p(this,null,function*(){if(!(yield o(this,te).socketHandler.hostControlForPeer(e,"audio")))throw new Error("failed to mute given participant")})}disableVideo(e){return p(this,null,function*(){if(!(yield o(this,te).socketHandler.hostControlForPeer(e,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(e){return p(this,null,function*(){const n={participantId:e!=null?e:""};try{yield o(this,Ht).sendMessagePromise(o(this,nn).globalPinPeer,t1.toBinary(n))}catch(i){m.error("Error in pinning peer:",{error:i})}})}validateScreenShare(e){return this.peerId===e.peerId&&o(this,te).producers.get(e.producerId)&&o(this,os).add(e.consumerPeerId),o(this,os).size}switchConsumersToLayer(e,n){return p(this,null,function*(){o(this,te).switchConsumersToLayer(e,n)})}handleSocketEvents(){return p(this,null,function*(){o(this,Ht).on(o(this,nn).peerProducerCreateBroadcast,({payload:e})=>{var n,i;if(this.mediaJoined)try{const{participantId:s,producerState:r}=rA.fromBinary(e);if(s===this.peerId)return;if(r!=null&&r.mimeType||(r.mimeType=r.kind===ci.AUDIO?"audio/opus":"video/VP8"),r.kind===ci.VIDEO&&!r.screenShare&&((i=(n=o(this,Bo).receiver)==null?void 0:n.video)==null?void 0:i.codecs.findIndex(a=>a.mimeType===Qn[0]))>=0&&o(this,na).get(Qn[0]).has(s)&&r.mimeType!==Qn[0]){m.warn(`Ignoring producer: ${r.producerId}`);return}m.info(`producer created broadcast: ${s}, producer state: ${r}`),L.emit(x.NEW_PRODUCER,{peerId:s,producer:ee(H({},r),{kind:r.kind===ci.AUDIO?"audio":"video",producingPeerId:s})})}catch(s){m.error("error in peer-producer-create-broadcast",{error:s})}}),o(this,Ht).on(o(this,nn).peerProducerToggleBroadcast,({payload:e})=>{if(this.mediaJoined)try{const{participantId:n,initiatorParticipantId:i,producerState:{kind:s,pause:r,producerId:a}}=Xf.fromBinary(e),c=s===ci.AUDIO?"audio":"video";if(m.info(`producer toggle broadcast: ${n}, producerId: ${a}, kind:${c}, paused:${r} payload: ${JSON.stringify(Xf.fromBinary(e))}`),n===this.peerId&&i!==this.peerId&&r&&L.emit(c==="audio"?x.MUTE_SELF:x.MUTE_SELF_VIDEO),n===this.peerId)return;L.emit(x.PRODUCER_TOGGLE,{peerId:n,producerId:a,paused:r,kind:c}),Array.from(this.getConsumers().values()).filter(d=>d.producerId===a).forEach(d=>{d.paused!==r&&(m.debug(`consumer state mismatched for ${d.id}. updating consumer pause state ${d.paused} to ${r}`),r?(d.pause(),L.emit(x.CONSUMER_PAUSED,{id:d.id})):(d.resume(),L.emit(x.CONSUMER_RESUMED,{id:d.id})))})}catch(n){m.error("error in producer toggle broadcast handler",{error:n})}}),o(this,Ht).on(o(this,nn).peerLeaveBroadcast,({payload:e})=>{if(this.mediaJoined)try{const{participantId:n}=wh.fromBinary(e);if(n===this.peerId)return;m.info(`peer left broadcast:${n}`),o(this,os).delete(n),o(this,te).consumers.forEach(i=>{i.peerId===n&&i.close()}),L.emit(x.PEER_CLOSED,{id:n})}catch(n){m.error("error in peer left broadcast",{error:n})}}),o(this,Ht).on(o(this,nn).peerProducerCloseBroadcast,({payload:e})=>{if(this.mediaJoined)try{const{participantId:n,producerState:{producerId:i}}=cA.fromBinary(e);if(n===this.peerId)return;m.info(`producer closed broadcast:${n}`),L.emit(x.PRODUCER_CLOSED,{peerId:n,producerId:i});const s=o(this,te).producerIdToConsumerIdMap.get(i);if(!s){m.warn(`no consumer found for producer:${i}`);return}m.info(`closing consumer ${s}, producer id: ${i}`),o(this,te).closeConsumer(s).then(()=>{m.info(`closed consumer: ${s}`),o(this,te).producerIdToConsumerIdMap.delete(i),L.emit(x.CONSUMER_CLOSED,{id:s})}).catch(r=>{m.error("error closing consumer",{error:r})})}catch(n){m.error("error on producer close broadcast",{error:n})}}),o(this,Ht).on(o(this,nn).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!o(this,ea)&&!o(this,ta)||(m.warn("media hub termination broadcast received, rejoining room"),L.emit(x.ROOM_NODE_DISCONNECTED),o(this,Bd).call(this))})})}handleCallstatsEvents(){ne.onConsumerScore(e=>{e.forEach((n,i)=>{const s=o(this,te).consumers.get(i);s&&L.emit(x.CONSUMER_SCORE_UPDATE,{id:i,kind:s.kind,peerId:s.peerId,score:n.score,scoreStats:n})})}),ne.onProducerScore(e=>{e.forEach((n,i)=>{const s=Array.from(o(this,te).producers.values()).find(r=>r.id===i);s&&L.emit(x.PRODUCER_SCORE_UPDATE,{id:i,kind:s.kind,appData:s.appData,score:n.score,scoreStats:n})})})}handlePeerCapabilities(e,n){var i,s,r,a;for(let c=0;c<=Qn.length;c+=1){const d=Qn[c];if(((s=(i=n==null?void 0:n.receiver)==null?void 0:i.video)==null?void 0:s.codecs.findIndex(h=>h.mimeType===d))>=0||c===Qn.length-1){o(this,ia).get(d).add(e);break}}for(let c=0;c<=Qn.length;c+=1){const d=Qn[c];if(((a=(r=n==null?void 0:n.sender)==null?void 0:r.video)==null?void 0:a.codecs.findIndex(h=>h.mimeType===d))>=0||c===Qn.length-1){o(this,na).get(d).add(e);break}}}handlePeerLeaving(e){re.hasFeature(ue.FORCE_VIDEO_CODEC)||(o(this,na).forEach(n=>n.delete(e)),o(this,ia).forEach((n,i)=>{n.delete(e),n.size===0&&this.disableWebcam(i)}))}}Vd=new WeakMap,Ud=new WeakMap,Ht=new WeakMap,te=new WeakMap,Bo=new WeakMap,Xs=new WeakMap,nn=new WeakMap,ea=new WeakMap,ta=new WeakMap,Zs=new WeakMap,Bd=new WeakMap,os=new WeakMap,Fo=new WeakMap,na=new WeakMap,ia=new WeakMap,sn=new WeakMap,un=new WeakMap,er=new WeakSet,sa=function(){return this.context.getValue("connectionHandler")},Ot=new WeakSet,qt=function(t){return o(this,sn).get(t)},ra=new WeakSet,jo=function(t,e){return o(this,sn).set(t,e)},Ep=new WeakSet,nE=function(t){return o(this,sn).delete(t)},Sp=new WeakSet,iE=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!0}},Tp=new WeakSet,sE=function(t,e){return{track:t,codecOptions:[{name:e?e.split("/")[1]:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}};Te([k.trace("MediaNodeClient.reset",{country:k.location.country})],Se.prototype,"reset",1);Te([k.trace("MediaNodeClient.joinRoom")],Se.prototype,"joinRoom",1);Te([k.trace("MediaNodeClient.completeJoinRoom")],Se.prototype,"completeJoinRoom",1);Te([k.trace("MediaNodeClient.leaveRoom")],Se.prototype,"leaveRoom",1);Te([k.trace("MediaNodeClient.activatePeers")],Se.prototype,"activatePeers",1);Te([k.trace("MediaNodeClient.deactivatePeers")],Se.prototype,"deactivatePeers",1);Te([k.trace("MediaNodeClient.createConsumers")],Se.prototype,"createConsumers",1);Te([k.trace("MediaNodeClient.closeConsumers")],Se.prototype,"closeConsumers",1);Te([k.trace("MediaNodeClient._shareWebcam")],Se.prototype,"_shareWebcam",1);Te([k.trace("MediaNodeClient.shareWebcam")],Se.prototype,"shareWebcam",1);Te([k.trace("MediaNodeClient.shareScreen")],Se.prototype,"shareScreen",1);Te([k.trace("MediaNodeClient.shareMic")],Se.prototype,"shareMic",1);Te([k.trace("MediaNodeClient.pauseMic")],Se.prototype,"pauseMic",1);Te([k.trace("MediaNodeClient.pauseWebcam")],Se.prototype,"pauseWebcam",1);Te([k.trace("MediaNodeClient.resumeMic")],Se.prototype,"resumeMic",1);Te([k.trace("MediaNodeClient.resumeWebcam")],Se.prototype,"resumeWebcam",1);Te([k.trace("MediaNodeClient.disableWebcam")],Se.prototype,"disableWebcam",1);Te([k.trace("HiveClient.disableMic")],Se.prototype,"disableMic",1);Te([k.trace("HiveClient.disableScreenShare")],Se.prototype,"disableScreenShare",1);Te([k.trace("MediaNodeClient.muteSelf")],Se.prototype,"muteSelf",1);Te([k.trace("MediaNodeClient.resetVideoProducers")],Se.prototype,"resetVideoProducers",1);Te([k.trace("MediaNodeClient.changeDisplayName")],Se.prototype,"changeDisplayName",1);Te([k.trace("MediaNodeClient.kickPeer")],Se.prototype,"kick",1);Te([k.trace("MediaNodeClient.kickAllPeers")],Se.prototype,"kickAll",1);Te([k.trace("MediaNodeClient.muteAll")],Se.prototype,"muteAll",1);Te([k.trace("MediaNodeClient.muteAllVideo")],Se.prototype,"muteAllVideo",1);Te([k.trace("MediaNodeClient.disableAudio")],Se.prototype,"disableAudio",1);Te([k.trace("MediaNodeClient.disableVideo")],Se.prototype,"disableVideo",1);Te([k.trace("MediaNodeClient.pinPeer")],Se.prototype,"pinPeer",1);Te([k.trace("MediaNodeClient.validateScreenShare")],Se.prototype,"validateScreenShare",1);function rE(t,e,n){const i=t.getValue("roomNodeClient");if(i){if(i)return i;throw new Error("Room node client already set up.")}const s=new Se(t,e,n);return t.setValue("roomNodeClient",s),s}function aE(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch(n){m.error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var X2=Object.defineProperty,Z2=Object.getOwnPropertyDescriptor,Pr=(t,e,n,i)=>{for(var s=i>1?void 0:i?Z2(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&X2(e,n,s),s},Us,Xn,Bt,Tn,On,Jg;const oE=(Jg=class{constructor(t,e,n,i){S(this,Tn),y(this,"self"),y(this,"authToken"),S(this,Us,void 0),y(this,"viewType"),S(this,Xn,void 0),S(this,Bt,void 0);const{socket:s}=n,r=t.getValue("authToken");this.self=e,T(this,Bt,t),this.viewType=i,this.authToken=r,T(this,Us,s),T(this,Xn,n),e.config.viewType!==zt.Chat&&this.setupEvents()}get peerId(){return o(this,Bt).getValue("peerId")}get mediaJoined(){return o(this,Bt).getValue("connectionHandler").mediaJoined}static init(t,e,n,i,s){return p(this,null,function*(){const r=Pt(),a=t.getValue("peerId"),c=!!t.getValue("cachedUserDetails"),d=yield wt.__init__(t,n,i,s,s.name,c);if(navigator.product!=="ReactNative"){const h=!re.hasFeature(ue.PRECALL_BANDWIDTH_TEST);setTimeout(()=>p(this,null,function*(){const u=yield d.getAllDevices();m.info("populated_full_device_list",{devices:JSON.stringify(u)}),ne.devices("AUDIO",u==null?void 0:u.filter(g=>g.kind==="audioinput")),ne.devices("VIDEO",u==null?void 0:u.filter(g=>g.kind==="videoinput")),ne.devices("SPEAKER",u==null?void 0:u.filter(g=>g.kind==="audiooutput")),m.info("Callstats:: initializing");try{yield ne.initialize({peerId:a,engineName:Be.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield r.getICEServers(),apiBase:t.getValue("apiBase"),flags:re.getAllFlags(),logger:m,apiHostnames:Qy(t),skipConnectivityChecks:h}),m.info("Callstats:: initialized")}catch(g){m.error("Callstats:: initialization failed",{error:g})}}),0)}else m.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new oE(t,d,e,s.viewType)})}shareMediaTracks(){return p(this,null,function*(){var t;const{audioTrack:e,videoTrack:n,permissions:i,audioEnabled:s,videoEnabled:r,screenShareEnabled:a,screenShareTracks:c}=this.self;if(i.canProduceAudio&&s)try{yield o(this,Tn,On).shareMic(e)}catch(d){this.self.disableAudio()}if(i.canProduceVideo&&r)try{const d=yield o(this,Tn,On).shareWebcam(n);d&&d.id!==n.id&&re.hasFeature(ue.EXP_RESHARE)&&(yield o(this,Tn,On).shareWebcam(d))}catch(d){this.self.disableVideo()}if(i.canProduceScreenshare&&a)try{yield(t=o(this,Tn,On))==null?void 0:t.shareScreen({video:c.video,audio:c.audio})}catch(d){this.self.disableScreenShare()}})}kickHandler(t){return p(this,null,function*(){let e="kicked";(t==null?void 0:t.kickType)==="kickAll"&&(e="ended"),this.leaveRoom(e)})}waitlistedHandler(){m.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(m.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){m.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(m.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){m.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}resetSelf(t){return p(this,null,function*(){ne.callEnded(),o(this,Tn,On).reset(),t&&(yield this.joinRoom(t))})}setupEvents(){L.on(x.RESET_PRODUCER_STATE,()=>p(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),L.on(x.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),L.on(x.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),L.on(x.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),L.on(x.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{t===!1&&(this.self.roomState="init"),this.resetSelf(t)}),L.on(x.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;t&&re.hasFeature(ue.REFRESH_ID_ON_DISCONNECTION)&&(e=Ia()),o(this,Us).updateURL(e),k.resetPeerId(e),Pt().setHeader("dyte-tracing-id",e),pr.remapContext(e,o(this,Bt)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),L.on(x.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),o(this,Xn).on(z.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),o(this,Xn).on(fd.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&L.emit(x.UPDATE_PERMISSIONS,e.patch)})}),o(this,Xn).on(z.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),o(this,Xn).on(z.kick,()=>{this.kickHandler({kickType:"kick"})}),o(this,Xn).on(z.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),L.onAsync(x.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),L.on(x.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:n,scoreStats:i})=>{var s;const r=(s=n==null?void 0:n.screenShare)!=null?s:!1;this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:r,score:t,participantId:this.self.id,scoreStats:i})}),L.on(x.MUTE_SELF,()=>p(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),ne.audioOff())})),L.on(x.MUTE_SELF_VIDEO,()=>p(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),ne.videoOff())})),L.onAsync(x.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),L.on(x.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return p(this,null,function*(){try{const{peer:e}=yield o(this,Xn).joinRoom(this.self);o(this,Xn).socket.flush();const n=sm(e.stageType);if(o(this,Bt).setValue("stageStatus",n,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),o(this,Bt).notify("stageStatus")}catch(e){throw m.error("Error in joinRoom",{error:e}),e}})}leaveRoom(t="left"){return p(this,null,function*(){var e,n;if(t==="rejected"){try{(e=o(this,Us))==null||e.disconnect()}catch(i){m.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),o(this,Bt).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),o(this,Bt).notify("stageStatus");try{(n=o(this,Us))==null||n.disconnect()}catch(i){m.error("SelfController::leaveRoom::socketDisconnect")}aE(o(this,Bt)),pl.cleanup(),this.self.roomState=t,this.self.emit("roomLeft",{state:t})})}joinMediaRoom(t=!1){return p(this,null,function*(){var e,n;const{peerId:i,viewType:s,meetingId:r,stageStatus:a,roomNodeOptions:c}=o(this,Bt).getAllValues(),{sfu:d}=c;try{if(s===zt.Livestream){if(a!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}rE(o(this,Bt),d,{socket:o(this,Us),peerId:i})}const{roomJoined:h}=(n=yield(e=o(this,Tn,On))==null?void 0:e.joinRoom(this.self.name,r,{audio:this.self.audioEnabled,video:this.self.videoEnabled,screen:this.self.screenShareEnabled},t,t))!=null?n:{};if(!h)return;a==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(h){throw m.error("Error:SelfController.mediaRoomJoin",{error:h}),new O("Error: could not join media room","0002")}})}leaveMediaRoom(t){return p(this,null,function*(){const e=o(this,Bt).getValue("viewType");t!=="connected-meeting"&&(yield this.cleanupSelf()),!(t==="stageLeft"&&e===zt.Webinar)&&o(this,Tn,On)&&(o(this,Tn,On).mediaJoined&&t!=="disconnected"&&(yield o(this,Tn,On).leaveRoom()),!(t==="stageLeft"&&e===zt.Livestream)&&(o(this,Tn,On).mediaJoined=!1))})}cleanupSelf(){return p(this,null,function*(){yield this.self.disableAudio(),yield this.self.disableVideo(),yield this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()})}},Us=new WeakMap,Xn=new WeakMap,Bt=new WeakMap,Tn=new WeakSet,On=function(){return o(this,Bt).getValue("roomNodeClient")},Jg);let Rs=oE;Pr([k.trace("SelfController.resetSelf")],Rs.prototype,"resetSelf",1);Pr([k.trace("SelfController.setupEvents")],Rs.prototype,"setupEvents",1);Pr([k.trace("SelfController.joinRoom")],Rs.prototype,"joinRoom",1);Pr([k.trace("SelfController.leaveRoom")],Rs.prototype,"leaveRoom",1);Pr([k.trace("SelfController.joinMediaRoom")],Rs.prototype,"joinMediaRoom",1);Pr([k.trace("SelfController.leaveMediaRoom")],Rs.prototype,"leaveMediaRoom",1);Pr([k.trace("SelfController.init")],Rs,"init",1);var Fd;class ex{constructor(e){S(this,Fd,void 0),T(this,Fd,e)}on(e,n){let i;e===z.roomPeerCount?i=tg.fromBinary.bind(tg):i=hg.fromBinary.bind(hg),o(this,Fd).on(e,({payload:s})=>{const r=i(s);return n(r)})}}Fd=new WeakMap;var jd;class tx{constructor(e){S(this,jd,void 0),T(this,jd,e)}on(e,n){let i,s;switch(e){case z.transcript:{i=wu.fromBinary.bind(wu),s=wu.create();break}default:{m.debug("AISocketHandler switch case hit default, event not accounted for.");break}}o(this,jd).on(e,({payload:r})=>{let a=s;try{a=i(r)}catch(c){m.error("chatSocketHandler::on::binary_decode_error",{error:c})}return n(a)})}}jd=new WeakMap;var nx=Object.defineProperty,ix=Object.getOwnPropertyDescriptor,gm=(t,e,n,i)=>{for(var s=i>1?void 0:i?ix(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&nx(e,n,s),s},cs;class Ql{constructor(e){S(this,cs,void 0),T(this,cs,e)}getPolls(){return o(this,cs).sendMessagePromise(Ei.getPolls)}createPoll(e,n,i=!1,s=!1){const r={anonymous:i,hideVotes:s,question:e,options:n};return o(this,cs).sendMessage(Ei.createPoll,YD.toBinary(r))}votePoll(e,n){const i={index:n,pollId:e};return o(this,cs).sendMessage(Ei.votePoll,XD.toBinary(i))}on(e,n){let i,s;switch(e){case Ei.updatePoll:case Ei.createPoll:case Ei.votePoll:{i=Au.fromBinary.bind(Au),s=Au.create();break}}o(this,cs).on(e,({payload:r})=>{let a=s;try{a=i(r)}catch(c){m.error("pollSocketHandler::on::binary_decode_error",{error:c})}return n(a)})}removeListeners(e){o(this,cs).removeListeners(e)}}cs=new WeakMap;gm([k.trace("PollSocketHandler.getPolls")],Ql.prototype,"getPolls",1);gm([k.trace("PollSocketHandler.createPoll")],Ql.prototype,"createPoll",1);gm([k.trace("PollSocketHandler.votePoll")],Ql.prototype,"votePoll",1);var hn;class sx{constructor(e){S(this,hn,void 0),T(this,hn,e)}getStageRequests(){return p(this,null,function*(){const{payload:e}=yield o(this,hn).sendMessagePromise(z.getStageRequests);return e?Pu.fromBinary(e):{stageRequests:[]}})}requestAccess(){o(this,hn).sendMessage(z.requestStageAccess)}cancelRequestAccess(){o(this,hn).sendMessage(z.cancelStageRequest)}grantAccess(e){return p(this,null,function*(){const n={userIds:e};o(this,hn).sendMessage(z.grantStageAccess,FD.toBinary(n))})}denyAccess(e){return p(this,null,function*(){const n={userIds:e};o(this,hn).sendMessage(z.denyStageAccess,WD.toBinary(n))})}joinStage(){return o(this,hn).sendMessagePromise(z.joinStage,void 0,void 0,z.peerStageStatusUpdate)}leaveStage(e){const n={userIds:[e]};return o(this,hn).sendMessagePromise(z.leaveStage,mg.toBinary(n),void 0,z.peerStageStatusUpdate)}kick(e){const n={userIds:e};return o(this,hn).sendMessagePromise(z.leaveStage,mg.toBinary(n))}on(e,n){let i;switch(e){case z.grantStageAccess:case z.denyStageAccess:{i=void 0;break}case z.getStagePeers:{i=pg.fromBinary.bind(pg);break}case z.getStageRequests:case z.requestStageAccess:case z.cancelStageRequest:{i=Pu.fromBinary.bind(Pu);break}case z.peerStageStatusUpdate:{i=eg.fromBinary.bind(eg);break}}o(this,hn).on(e,({payload:s,id:r})=>{if(!s||!i)return n(void 0,r);const a=i(s);return n(a,r)})}getPeerInfo(e){return p(this,null,function*(){const n=yield o(this,hn).sendMessagePromise(z.getPeerInfo,o0.toBinary({peerId:e}));return qr.fromBinary(n.payload)})}}hn=new WeakMap;var St;class rx{constructor(e){S(this,St,void 0),T(this,St,e)}addPlugin(e,n){o(this,St).sendMessage(ie.addPlugin,iD.toBinary({pluginId:e,staggered:n}))}removePlugin(e){o(this,St).sendMessage(ie.removePlugin,rD.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return p(this,null,function*(){const{payload:e}=yield o(this,St).sendMessagePromise(ie.getPlugins);return e?RD.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,n,i){const s={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(n))};o(this,St).sendMessage(ie.customPluginEventToRoom,fD.toBinary(s),i)}customPluginEventToPeers(e,n,i,s){const r={pluginId:e,peerIds:n,pluginData:new TextEncoder().encode(JSON.stringify(i))};o(this,St).sendMessage(ie.customPluginEventToPeers,vD.toBinary(r),s)}enablePluginForRoom(e,n){o(this,St).sendMessage(ie.enablePluginForRoom,oD.toBinary({pluginId:e}),n)}enablePluginForPeers(e,n,i){o(this,St).sendMessage(ie.enablePluginForPeers,uD.toBinary({pluginId:e,peerIds:n}),i)}disablePluginForRoom(e,n){o(this,St).sendMessage(ie.disablePluginForRoom,dD.toBinary({pluginId:e}),n)}disablePluginForPeers(e,n,i){o(this,St).sendMessage(ie.disablePluginForPeers,pD.toBinary({pluginId:e,peerIds:n}),i)}storeInsertKeys(e,n,i,s){const r={pluginId:e,storeName:n,insertKeys:i.map(a=>({storeKey:a.key,payload:new TextEncoder().encode(JSON.stringify(a.payload))}))};o(this,St).sendMessage(ie.storeInsertKeys,cg.toBinary(r),s)}storeGetKeys(e,n,i,s){const r={pluginId:e,storeName:n,getKeys:i.map(a=>({storeKey:a.key}))};o(this,St).sendMessage(ie.storeGetKeys,TD.toBinary(r),s)}storeDeleteKeys(e,n,i,s){const r={pluginId:e,storeName:n,deleteKeys:i.map(a=>({storeKey:a.key}))};o(this,St).sendMessage(ie.storeDeleteKeys,kD.toBinary(r),s)}storeDelete(e,n,i){o(this,St).sendMessage(ie.storeDelete,_D.toBinary({pluginId:e,storeName:n}),i)}getPluginDataOld(e,n){m.info("getPluginDataOld",{plugin:{id:e,storeName:n}})}storePluginDataOld(e,n,i){const s={pluginId:e,storeName:n,insertKeys:[{storeKey:i.key,payload:new TextEncoder().encode(JSON.stringify(i))}]};o(this,St).sendMessage(ie.storeInsertKeys,cg.toBinary(s))}on(e,n){let i;switch(e){case ie.addPlugin:case ie.enablePluginForPeers:case ie.enablePluginForRoom:{i=Rh.fromBinary.bind(Rh);break}case ie.removePlugin:case ie.disablePluginForPeers:case ie.disablePluginForRoom:{i=dg.fromBinary.bind(dg);break}case ie.customPluginEventToPeers:case ie.customPluginEventToRoom:{i=ug.fromBinary.bind(ug);break}case ie.storeInsertKeys:case ie.storeGetKeys:case ie.storeDeleteKeys:case ie.storeDelete:{i=lg.fromBinary.bind(lg);break}}o(this,St).on(e,({payload:s,id:r})=>{const a=i(s);return n(a,r)})}}St=new WeakMap;var ax=Object.defineProperty,ox=(t,e,n)=>e in t?ax(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,cx=(t,e,n)=>(ox(t,typeof e!="symbol"?e+"":e,n),n),vm=(t,e,n)=>{if(!e.has(t))throw TypeError("Cannot "+n)},W=(t,e,n)=>(vm(t,e,"read from private field"),n?n.call(t):e.get(t)),Ve=(t,e,n)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,n)},ke=(t,e,n,i)=>(vm(t,e,"write to private field"),i?i.call(t,n):e.set(t,n),n),qe=(t,e,n)=>(vm(t,e,"access private method"),n),bl={},dx={get exports(){return bl},set exports(t){bl=t}},ya=typeof Reflect=="object"?Reflect:null,Kg=ya&&typeof ya.apply=="function"?ya.apply:function(t,e,n){return Function.prototype.apply.call(t,e,n)},Wd;ya&&typeof ya.ownKeys=="function"?Wd=ya.ownKeys:Object.getOwnPropertySymbols?Wd=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Wd=function(t){return Object.getOwnPropertyNames(t)};function lx(t){console&&console.warn&&console.warn(t)}var cE=Number.isNaN||function(t){return t!==t};function _e(){_e.init.call(this)}dx.exports=_e;bl.once=mx;_e.EventEmitter=_e;_e.prototype._events=void 0;_e.prototype._eventsCount=0;_e.prototype._maxListeners=void 0;var zg=10;function Xl(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(_e,"defaultMaxListeners",{enumerable:!0,get:function(){return zg},set:function(t){if(typeof t!="number"||t<0||cE(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");zg=t}});_e.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};_e.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||cE(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function dE(t){return t._maxListeners===void 0?_e.defaultMaxListeners:t._maxListeners}_e.prototype.getMaxListeners=function(){return dE(this)};_e.prototype.emit=function(t){for(var e=[],n=1;n<arguments.length;n++)e.push(arguments[n]);var i=t==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var r;if(e.length>0&&(r=e[0]),r instanceof Error)throw r;var a=new Error("Unhandled error."+(r?" ("+r.message+")":""));throw a.context=r,a}var c=s[t];if(c===void 0)return!1;if(typeof c=="function")Kg(c,this,e);else for(var d=c.length,h=mE(c,d),n=0;n<d;++n)Kg(h[n],this,e);return!0};function lE(t,e,n,i){var s,r,a;if(Xl(n),r=t._events,r===void 0?(r=t._events=Object.create(null),t._eventsCount=0):(r.newListener!==void 0&&(t.emit("newListener",e,n.listener?n.listener:n),r=t._events),a=r[e]),a===void 0)a=r[e]=n,++t._eventsCount;else if(typeof a=="function"?a=r[e]=i?[n,a]:[a,n]:i?a.unshift(n):a.push(n),s=dE(t),s>0&&a.length>s&&!a.warned){a.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=a.length,lx(c)}return t}_e.prototype.addListener=function(t,e){return lE(this,t,e,!1)};_e.prototype.on=_e.prototype.addListener;_e.prototype.prependListener=function(t,e){return lE(this,t,e,!0)};function ux(){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 uE(t,e,n){var i={fired:!1,wrapFn:void 0,target:t,type:e,listener:n},s=ux.bind(i);return s.listener=n,i.wrapFn=s,s}_e.prototype.once=function(t,e){return Xl(e),this.on(t,uE(this,t,e)),this};_e.prototype.prependOnceListener=function(t,e){return Xl(e),this.prependListener(t,uE(this,t,e)),this};_e.prototype.removeListener=function(t,e){var n,i,s,r,a;if(Xl(e),i=this._events,i===void 0)return this;if(n=i[t],n===void 0)return this;if(n===e||n.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete i[t],i.removeListener&&this.emit("removeListener",t,n.listener||e));else if(typeof n!="function"){for(s=-1,r=n.length-1;r>=0;r--)if(n[r]===e||n[r].listener===e){a=n[r].listener,s=r;break}if(s<0)return this;s===0?n.shift():hx(n,s),n.length===1&&(i[t]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",t,a||e)}return this};_e.prototype.off=_e.prototype.removeListener;_e.prototype.removeAllListeners=function(t){var e,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){var s=Object.keys(n),r;for(i=0;i<s.length;++i)r=s[i],r!=="removeListener"&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=n[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(i=e.length-1;i>=0;i--)this.removeListener(t,e[i]);return this};function hE(t,e,n){var i=t._events;if(i===void 0)return[];var s=i[e];return s===void 0?[]:typeof s=="function"?n?[s.listener||s]:[s]:n?px(s):mE(s,s.length)}_e.prototype.listeners=function(t){return hE(this,t,!0)};_e.prototype.rawListeners=function(t){return hE(this,t,!1)};_e.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):pE.call(t,e)};_e.prototype.listenerCount=pE;function pE(t){var e=this._events;if(e!==void 0){var n=e[t];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}_e.prototype.eventNames=function(){return this._eventsCount>0?Wd(this._events):[]};function mE(t,e){for(var n=new Array(e),i=0;i<e;++i)n[i]=t[i];return n}function hx(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function px(t){for(var e=new Array(t.length),n=0;n<e.length;++n)e[n]=t[n].listener||t[n];return e}function mx(t,e){return new Promise(function(n,i){function s(a){t.removeListener(e,r),i(a)}function r(){typeof t.removeListener=="function"&&t.removeListener("error",s),n([].slice.call(arguments))}fE(t,e,r,{once:!0}),e!=="error"&&fx(t,s,{once:!0})})}function fx(t,e,n){typeof t.on=="function"&&fE(t,"error",e,n)}function fE(t,e,n,i){if(typeof t.on=="function")i.once?t.once(e,n):t.on(e,n);else if(typeof t.addEventListener=="function")t.addEventListener(e,function s(r){i.once&&t.removeEventListener(e,s),n(r)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}class gx extends _{constructor(){super("message.v1.SocketMessage",[{no:1,name:"event",kind:"scalar",T:13},{no:2,name:"id",kind:"scalar",opt:!0,T:9},{no:3,name:"payload",kind:"scalar",opt:!0,T:12},{no:4,name:"metadata",kind:"scalar",opt:!0,T:12}])}}const Yg=new gx;class gE{static encode(e){return Yg.toBinary(e)}static decode(e){return Yg.fromBinary(new Uint8Array(e))}}function vx(t,e){return Math.floor(Math.random()*(e-t+1)+t)}var ds;class yx{constructor(e={}){cx(this,"opts"),Ve(this,ds,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},ke(this,ds,0)}wait(){return p(this,null,function*(){ke(this,ds,W(this,ds)+1);const e=vx(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*Oe(2,W(this,ds))));yield new Promise(n=>{setTimeout(n,e)})})}getAttempts(){return W(this,ds)}reset(){ke(this,ds,0)}}ds=new WeakMap;const Ji={debug:0,info:1,warn:2,error:3};var tr,nr;class Ex{constructor(e){Ve(this,tr,void 0),Ve(this,nr,void 0),ke(this,tr,console),ke(this,nr,e)}debug(...e){Ji[W(this,nr)]>Ji.debug||W(this,tr).debug("[Sockrates]:",...e)}info(...e){Ji[W(this,nr)]>Ji.info||W(this,tr).info("[Sockrates]:",...e)}warn(...e){Ji[W(this,nr)]>Ji.warn||W(this,tr).warn("[Sockrates]:",...e)}error(...e){Ji[W(this,nr)]>Ji.error||W(this,tr).error("[Sockrates]:",...e)}}tr=new WeakMap,nr=new WeakMap;var vE=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(vE||{});const Sx="2",Tx="3";var Qe,aa,He,st,ls,Tt,wi,ys,jn,oa,yi,bp,yE,Wo,Hd,kp,EE,wp,Qg,kl,_p,Ip,SE,rc,qd,ac,wl,_l,Cp,Ea,oc,cc,Il;class bx{constructor(e,n){var i;Ve(this,bp),Ve(this,Wo),Ve(this,kp),Ve(this,wp),Ve(this,kl),Ve(this,Ip),Ve(this,rc),Ve(this,ac),Ve(this,_l),Ve(this,Ea),Ve(this,cc),Ve(this,Qe,void 0),Ve(this,aa,void 0),Ve(this,He,void 0),Ve(this,st,void 0),Ve(this,ls,void 0),Ve(this,Tt,void 0),Ve(this,wi,void 0),Ve(this,ys,void 0),Ve(this,jn,void 0),Ve(this,oa,void 0),Ve(this,yi,void 0);var s,r,a,c,d,h,u,g,E;ke(this,aa,e),ke(this,ls,[]),ke(this,Tt,new bl),ke(this,wi,!0),ke(this,jn,!1),ke(this,He,n!=null?n:{}),(s=W(this,He)).autoReconnect!=null||(s.autoReconnect=!0),(r=W(this,He)).retryConnectionInterval!=null||(r.retryConnectionInterval=1e3),(a=W(this,He)).pingTimeout!=null||(a.pingTimeout=3e4),(c=W(this,He)).connectionTimeout!=null||(c.connectionTimeout=5e3),(d=W(this,He)).debug!=null||(d.debug=!0),(h=W(this,He)).maxReconnectionAttempts!=null||(h.maxReconnectionAttempts=10),(u=W(this,He)).disconnectOnPingTimeout!=null||(u.disconnectOnPingTimeout=!0),(g=W(this,He)).queueOnDisconnect!=null||(g.queueOnDisconnect=!1),(E=W(this,He)).flushOnReconnect!=null||(E.flushOnReconnect=!1),ke(this,ys,{code:void 0,reason:void 0}),ke(this,st,(i=W(this,He).logger)!=null?i:new Ex(W(this,He).debug?"debug":"info")),ke(this,yi,new yx)}get readyState(){var e;return(e=W(this,Qe))==null?void 0:e.readyState}get url(){return W(this,aa)}updateURL(e){ke(this,aa,e),qe(this,Ip,SE).call(this)}get config(){return W(this,He)}get sendQueue(){return W(this,ls)}flush(){if(!W(this,He).queueOnDisconnect)return!1;const e=[];return W(this,ls).forEach(n=>{this.send(n.event,n.id,n.payload,n.metadata)||e.push(n)}),ke(this,ls,e),W(this,ls)}connect(e=!1){return p(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){W(this,st).debug("Websocket was already connecting or connected.");return}if(W(this,wi)!==!1)return new Promise((n,i)=>{qe(this,Ea,oc).call(this),qe(this,cc,Il).call(this);try{ke(this,Qe,new WebSocket(qe(this,bp,yE).call(this,W(this,aa)))),W(this,Qe).binaryType="arraybuffer",W(this,st).debug("Connecting");const s=setTimeout(()=>{W(this,st).debug("Connection timeout. Closing socket"),ke(this,wi,!0),qe(this,cc,Il).call(this),W(this,Qe).close(3001,"Connection Timeout"),W(this,He).autoReconnect&&!W(this,jn)&&(W(this,Tt).emit("reconnecting"),qe(this,rc,qd).call(this)),i(new Error("Connection timed out!"))},W(this,He).connectionTimeout);W(this,Qe).onopen=()=>{W(this,st).debug(`Ready State: ${vE[W(this,Qe).readyState]}`),s&&clearTimeout(s),qe(this,_l,Cp).call(this),ke(this,ys,{code:void 0,reason:void 0}),W(this,Tt).emit("connected"),W(this,He).flushOnReconnect&&this.flush(),n()},W(this,Qe).onclose=r=>{try{s&&clearTimeout(s);const{code:a,reason:c}=r;i(c),W(this,st).debug("Socket closed. Close event:",{event:r}),W(this,st).debug(`Connection closed code: ${a}`),W(this,st).debug(`Connection closed reason: ${c}`),W(this,jn)||qe(this,kl,_p).call(this,a,c)}catch(a){qe(this,Wo,Hd).call(this,a)}},W(this,Qe).onerror=r=>{qe(this,Wo,Hd).call(this,r)},W(this,Qe).onmessage=r=>qe(this,kp,EE).call(this,r)}catch(s){qe(this,Wo,Hd).call(this,s,i)}})})}send(e,n,i,s){const r={event:e,id:n,payload:i,metadata:s};if(W(this,He).queueOnDisconnect&&(!W(this,Qe)||W(this,Qe).readyState!==1))return W(this,st).debug("Queuing message since socket is not connected!",r),W(this,ls).push(r),!1;const a=gE.encode(r);return qe(this,ac,wl).call(this,a)}emit(e,n,i,s){return this.send(e,n,i,s)}sendRaw(e){return qe(this,ac,wl).call(this,e)}receive(e,n){return W(this,Tt).on(e.toString(),n)}on(e,n){if(typeof e=="string"&&(e==="connected"||e==="disconnected"||e==="errored"||e==="reconnected"||e==="reconnecting"||e==="reconnectAttempt"||e==="reconnectFailure"||e==="failed")){W(this,Tt).on(e,n);return}this.receive(e,n)}removeAllListeners(){W(this,Tt).removeAllListeners()}removeReceiver(e,n){this.removeListener(e,n)}removeListener(e,n){W(this,Tt).removeListener(e.toString(),n)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){W(this,Tt).listeners(e.toString()).map(n=>this.removeListener(e,n))}disconnect(){ke(this,wi,!1),qe(this,Ea,oc).call(this),this.removeAllListeners(),ke(this,ys,{code:1e3,reason:"Sockrates disconnect method called"}),W(this,Qe).close(1e3,"Sockrates disconnect method called.")}}Qe=new WeakMap,aa=new WeakMap,He=new WeakMap,st=new WeakMap,ls=new WeakMap,Tt=new WeakMap,wi=new WeakMap,ys=new WeakMap,jn=new WeakMap,oa=new WeakMap,yi=new WeakMap,bp=new WeakSet,yE=function(t){if(t.startsWith("ws://")||t.startsWith("wss://"))return t;if(t.startsWith("https://"))return`wss://${t.substring(8)}`;if(t.startsWith("http://"))return`ws://${t.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},Wo=new WeakSet,Hd=function(t,e){W(this,st).error("Error:",{error:t}),W(this,Tt).emit("errored",{error:t}),e==null||e(t)},kp=new WeakSet,EE=function(t){if(qe(this,_l,Cp).call(this),t.data===Sx){W(this,st).debug("Received ping from server"),qe(this,ac,wl).call(this,Tx);return}const e=gE.decode(t.data),{id:n,payload:i}=e;W(this,st).debug("Received message",{event:e.event,messageID:n}),W(this,Tt).emit(e.event.toString(),{id:n,payload:i})},wp=new WeakSet,Qg=function(){return W(this,Qe).readyState===1},kl=new WeakSet,_p=function(t,e){ke(this,ys,{reason:e,code:t}),W(this,Tt).emit("disconnected",{code:t,reason:e})},Ip=new WeakSet,SE=function(){const{reason:t,code:e}=W(this,ys);e&&e!==1e3&&W(this,wi)&&W(this,He).autoReconnect&&!W(this,jn)&&(W(this,st).debug(`Triggering reconnection due to ${t}.`),W(this,Tt).emit("reconnecting"),qe(this,rc,qd).call(this))},rc=new WeakSet,qd=function(t=!0){return p(this,null,function*(){if(t&&W(this,jn)){W(this,st).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(W(this,jn)||W(this,yi).reset(),W(this,He).maxReconnectionAttempts!==null&&W(this,yi).getAttempts()>=W(this,He).maxReconnectionAttempts){W(this,Tt).emit("failed"),ke(this,jn,!1);return}ke(this,jn,!0),qe(this,cc,Il).call(this),qe(this,Ea,oc).call(this);try{if(yield W(this,yi).wait(),W(this,wi)===!1)return;if(W(this,st).debug(`Reconnection attempt ${W(this,yi).getAttempts()}`),W(this,Tt).emit("reconnectAttempt",{attempt:W(this,yi).getAttempts()}),yield this.connect(),!qe(this,wp,Qg).call(this))throw Error("Reconnect Failed");ke(this,jn,!1),ke(this,ys,{code:void 0,reason:void 0}),W(this,Tt).emit("reconnected")}catch(e){W(this,st).debug("Failed to reconnect."),W(this,Tt).emit("reconnectFailure",{attempt:W(this,yi).getAttempts()}),qe(this,rc,qd).call(this,!1)}})},ac=new WeakSet,wl=function(t){try{return W(this,Qe).send(t),!0}catch(e){return W(this,st).error(e.message),!1}},_l=new WeakSet,Cp=function(){this.config.disconnectOnPingTimeout&&(W(this,st).debug("Resetting ping timeout"),qe(this,Ea,oc).call(this),ke(this,oa,setTimeout(()=>{var t;W(this,st).debug("Disconnecting the socket due to ping timeout"),ke(this,wi,!0);const e=3002,n="Ping timeout";(t=W(this,Qe))==null||t.close(e,n),qe(this,kl,_p).call(this,e,n)},W(this,He).pingTimeout)))},Ea=new WeakSet,oc=function(){W(this,oa)&&(clearTimeout(W(this,oa)),ke(this,oa,void 0))},cc=new WeakSet,Il=function(){W(this,Qe)&&(W(this,Qe).onopen=void 0,W(this,Qe).onerror=void 0,W(this,Qe).onmessage=void 0,W(this,Qe).onclose=void 0)};var kx=Object.defineProperty,wx=Object.getOwnPropertyDescriptor,Zl=(t,e,n,i)=>{for(var s=i>1?void 0:i?wx(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&kx(e,n,s),s};const Xg=65535,_x=3e3;var Bs,Ke,ze,et,Dn,Ki,id,Yu,sd,Qu,Zg;const TE=(Zg=class{constructor(t,{peerId:e,meetingId:n,authToken:i,capabilities:s}){S(this,ze),S(this,id),S(this,sd),S(this,Bs,void 0),S(this,Ke,void 0),y(this,"roomName"),y(this,"authToken"),y(this,"capabilities"),S(this,Dn,void 0),S(this,Ki,void 0);var r;if(!e||!n||!i)throw new O("peerId, meetingId, or authToken can not be empty","0404");T(this,Dn,void 0),T(this,Ki,t),this.capabilities=s,this.roomName=n,this.authToken=i,T(this,Bs,Q(this,id,Yu).call(this,e)),T(this,Ke,new bx(o(this,Bs),{autoReconnect:!0,disconnectOnPingTimeout:(r=s.includes("PING"))!=null?r:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:m})),this.handleSocketConnectionEvents()}get joinAttempted(){return o(this,ze,et).socketJoinAttempted}set joinAttempted(t){o(this,ze,et).socketJoinAttempted=t}get peerId(){return o(this,Ki).getValue("peerId")}updateURL(t){t!==this.peerId&&(T(this,Bs,Q(this,id,Yu).call(this,t)),m.debug("SocketService:: Connection URL updated.")),o(this,Ke).updateURL(o(this,Bs))}static getSocketEdgeDomain(t){return fa({servicePrefix:"socket-edge",baseURI:t})}get url(){return o(this,Bs)}connect(){return p(this,null,function*(){o(this,ze,et).socketJoinAttempted=!0,yield o(this,Ke).connect(),o(this,ze,et).socketJoinAttempted=!0,o(this,ze,et).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){return p(this,null,function*(){o(this,ze,et).socketJoinAttempted=!1,o(this,Ke).disconnect(),o(this,ze,et).socketJoinAttempted=!0,o(this,ze,et).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}})}get isConnected(){try{return o(this,Ke).readyState===1}catch(t){return!1}}sendMessage(t,e,n){const i={};return k.injectContext(i),o(this,Ke).send(t,n!=null?n:Q(this,sd,Qu).call(this),e,new TextEncoder().encode(JSON.stringify(i)))}sendMessagePromise(t,e,n,i){const s=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:s,protobuf:e,messageId:n,resp:i})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:n,messageId:i,resp:s}){const r=s!=null?s:t;return new Promise((a,c)=>{const d=(b,w)=>{o(this,Ke).removeListener(r,b),o(this,Ke).removeListener(Xg,w),o(this,Ke).removeListener(_n.errorResponse,w),o(this,Ke).removeListener(Wn.errorResponse,w)},h=i!=null?i:Q(this,sd,Qu).call(this),u={};k.injectContext(u);const g=({id:b,payload:w})=>{if(h===b){let M;try{const D=E1.fromBinary(w);M=new Error(D.errorMessage)}catch(D){M=new Error("failed to parse error message",{cause:D});try{const F=SA.fromBinary(w);M=new Error(F.message)}catch(F){M=new Error("failed to parse error message",{cause:F})}}c(M),d(E,g)}},E=({id:b,payload:w})=>{h===b&&(a({id:b,payload:w}),d(E,g))};o(this,Ke).on(r,E),o(this,Ke).on(Xg,g),o(this,Ke).on(_n.errorResponse,g),o(this,Ke).on(Wn.errorResponse,g),setTimeout(()=>{d(E,g),c(new Error(`request timeout for callback eventId:${t}`))},e),o(this,Ke).send(t,h,n,new TextEncoder().encode(JSON.stringify(u)))})}on(t,e){o(this,Ke).on(t,e)}onStateEvent(t,e){o(this,Ke).on(t,e)}removeListener(t,e){o(this,Ke).removeListener(t,e)}removeListeners(t){o(this,Ke).removeListeners(t)}flush(){return o(this,Ke).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>p(this,null,function*(){m.info("SocketService::Connected to socket-edge"),o(this,Dn)&&(clearTimeout(o(this,Dn)),T(this,Dn,void 0)),o(this,ze,et).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:t,reason:e})=>{var n;m.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e},country:k.location.country});const{recv:i,send:s}=(n=o(this,ze,et).mediaState)!=null?n:{};i!=null&&i.state&&(i==null?void 0:i.state)!==ks.CONNECTED||s!=null&&s.state&&(s==null?void 0:s.state)!==ks.CONNECTED?L.emit(x.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:o(this,ze,et).joinAttempted}):T(this,Dn,setTimeout(()=>{L.emit(x.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:o(this,ze,et).joinAttempted}),T(this,Dn,void 0)},_x)),o(this,ze,et).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>p(this,null,function*(){m.info("SocketService::Reconnecting to socket-edge",{country:k.location.country}),o(this,ze,et).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>p(this,[t],function*({attempt:e}){m.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),o(this,ze,et).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{m.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),o(this,ze,et).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>p(this,null,function*(){m.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:o(this,ze,et).mediaJoinAttempted}}),o(this,Dn)&&(clearTimeout(o(this,Dn)),T(this,Dn,void 0)),L.emit(x.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:o(this,ze,et).mediaJoinAttempted}),o(this,ze,et).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>p(this,null,function*(){m.info("SocketService::Failed to connect to socket-edge",{country:k.location.country}),L.emit(x.SOCKET_SERVICE_FAILED),o(this,ze,et).updateSocketConnectionState("failed")}))}},Bs=new WeakMap,Ke=new WeakMap,ze=new WeakSet,et=function(){return o(this,Ki).getValue("connectionHandler")},Dn=new WeakMap,Ki=new WeakMap,id=new WeakSet,Yu=function(t){let e=TE.getSocketEdgeDomain(o(this,Ki).getValue("baseURI"));typeof cl(o(this,Ki),"socket_server_base")=="string"&&(e=cl(o(this,Ki),"socket_server_base"));const n=`wss://${e}`,i=new URL(`${n}/ws`),s=this.peerId,r=ee(H({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},s!==t&&{oldPeerID:s}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(a=>dl[a]).join(" "),joinWithDetails:!0,useCfWorker:!0});return Object.entries(r).forEach(([a,c])=>{i.searchParams.append(a,c.toString())}),i.href},sd=new WeakSet,Qu=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Zg);let _c=TE;Zl([k.trace("SocketService.connect")],_c.prototype,"connect",1);Zl([k.trace("SocketService.disconnect")],_c.prototype,"disconnect",1);Zl([k.trace("SocketService.sendMessagePromise")],_c.prototype,"sendMessagePromise",1);Zl([k.trace("SocketService.sendMessagePromiseWithTimeout")],_c.prototype,"sendMessagePromiseWithTimeout",1);const ir=class{static handleConnectedRoomsDumpRaw({payload:t}){var e;const n=JA.fromBinary(t),i=n.meetings.map(s=>{var r;return{id:s.id,title:s.title,participants:(r=s.participants)!=null?r:[]}});return{parentMeeting:{id:n.parentMeeting.id,title:n.parentMeeting.title,participants:(e=n.parentMeeting.participants)!=null?e:[]},meetings:i}}static handleTransferPeerRaw({payload:t}){const e=EM.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}static handleMovedPeerRaw({payload:t}){const e=c0.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}static handleConnectedRoomsUpdatedRaw({payload:t}){return sg.fromBinary(t).payloads.map(e=>({id:e.id,title:e.title}))}static handleConnectedRoomsDeletedRaw({payload:t}){return dM.fromBinary(t).payloads}static getConnectedRoomsDump(){return p(this,null,function*(){const t=yield ir.socketService.sendMessagePromise(z.getConnectedRoomsDump);return ir.handleConnectedRoomsDumpRaw(t)})}static createConnectedRooms(t){return p(this,null,function*(){const{payload:e}=yield ir.socketService.sendMessagePromise(z.createConnectedRooms,QA.toBinary({payloads:t}));return sg.fromBinary(e).payloads.map(n=>({id:n.id,title:n.title}))})}static updateConnectedRooms(t){return p(this,null,function*(){})}static disableConnectedRooms(t){return p(this,null,function*(){const e=t.map(i=>({id:i})),n=yield ir.socketService.sendMessagePromise(z.deleteConnectedRooms,oM.toBinary({payloads:e}));return ir.handleConnectedRoomsDeletedRaw(n)})}static movePeersBetweenRooms(t){return p(this,null,function*(){try{const e=yield ir.socketService.sendMessagePromise(z.movePeers,fM.toBinary({sourceMeetingId:t.sourceMeetingId,destinationMeetingId:t.destinationMeetingId,participants:t.participants}));return new TextDecoder().decode(e.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(e){return{success:!1,error:e}}})}};let $e=ir;y($e,"socketService"),y($e,"currentMeetingId");var Ix=Object.defineProperty,Cx=Object.getOwnPropertyDescriptor,eu=(t,e,n,i)=>{for(var s=i>1?void 0:i?Cx(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&Ix(e,n,s),s};const ca=class{constructor(t,e){y(this,"apiBase"),y(this,"selfController"),y(this,"pollController"),y(this,"chatController"),y(this,"metaController"),y(this,"storesManager"),y(this,"stageController"),y(this,"pluginController"),y(this,"internalsController"),y(this,"recordingController"),y(this,"livestreamController"),y(this,"participantController"),this.apiBase=t,this.storesManager=e.storesManager,this.metaController=e.metaController,this.selfController=e.selfController,this.chatController=e.chatController,this.pollController=e.pollController,this.stageController=e.stageController,this.pluginController=e.pluginController,this.recordingController=e.recordingController,this.internalsController=e.internalsController,this.participantController=e.participantController,this.livestreamController=e.livestreamController}static init(t){return p(this,null,function*(){var e,n;const{peerId:i,apiBase:s,authToken:r,meetingId:a,organizationId:c,cachedUserDetails:d}=t.getAllValues();if(L.reset(),pl.cleanup(),aE(t),Be.isSupported()===!1)throw new O("Browser not supported","0010",!0);const h=MN(t,{authToken:r,baseURL:s,cachedUserDetails:d});h.setRoomName(a),h.setRoomUUID(a),h.setOrganizationId(c),h.setHeader("dyte-tracing-id",i),t.setValue("apiClient",h);const u=new pL;t.setValue("connectionHandler",u);const g=ca.createSocketService(t),E=g.connect(),b=h.getUserDetails(),w=h.getPlugins();let M=bt.HIVE,D,F="";try{yield ca.setupFlagsmith(t)}catch($){m.error("Failed to setup flagsmith",{error:$})}try{yield E}catch($){m.error("[Controller]: Failed to connect to socket server:",{error:$})}try{({sfu:M,meetingTitle:F}=yield h.getRoomNodeData()),D=yield b,m.info(`SFU ${M} is being used.`),t.setValue("presetName",D.preset.name),t.setValue("roomNodeOptions",{sfu:M})}catch($){m.error("Failed to get room metadata",{error:$})}const Y=QL.init(D.preset,!t.getValue("modules").theme),X=ca.setupControllers(g,t,D,w,F,Y);nL(Y)&&((e=ca.createRoomNodeClient(t,g).partialJoinRoom(D.participant.name,a,void 0))==null||e.catch($=>{m.error("[Controller]: Failed to queue partial media room promise:",{error:$})})),k.location.country=(n=h.ipInfo)==null?void 0:n.country;const{controllers:A}=yield X;return sP(),new ca(s,A)})}static setupFlagsmith(t){return p(this,null,function*(){var e;const{peerId:n,baseURI:i,overrides:s,meetingId:r,organizationId:a}=t.getAllValues(),c=nP(r),d=ee(H({entity:Th.PEER,clientId:a,isAnonUser:!a,sdkVersion:t.getValue("sdkVersion"),presetName:t.getValue("presetName"),meetingHash:c,roomName:r},Be.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const h=(e=s==null?void 0:s.whitelabelled_flags_endpoint)==null||e?fa({servicePrefix:"flags",baseURI:i}):"edge.api.flagsmith.com";yield re.identify(`${Th.PEER}_${n}`,JSON.parse(JSON.stringify(d)),!1,5e3,h,m),m.info("flagsmith::allFlags",{flags:JSON.stringify(re.getAllFlags())},!0)}catch(h){m.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,n,i,s,r){return p(this,null,function*(){var a,c,d;const h=e.getValue("modules"),{preset:u,participant:g}=n,E=e.getValue("defaults"),{sfu:b}=e.getValue("roomNodeOptions"),{viewType:w,mediaConstraints:{audio:M}}=r;e.setValue("viewType",w),e.setValue("defaults",H({mediaConfiguration:{audio:{enableHighBitrate:(a=M.enableHighBitrate)!=null?a:!1,enableStereo:(c=M.enableStereo)!=null?c:!1}}},E));const D=y2.init(e,w,u.permissions);e.setValue("maxPreferredStreams",Be.isMobile()?r.maxVideoStreams.mobile:r.maxVideoStreams.desktop);let F,Y,X,A,$,me,Ie,fe;const Je=new tx(t);$e.socketService=t;const ht=new Ql(t),V=new In(t),I=new sx(t),P=pl.create(t,e),K=new rx(t),ye=new ex(t),Xe=new yr(t),q=yield Rs.init(e,P,g,D,r),N=yield S0.init(e,q.self,P,Je,s);if(h.participant&&(fe=new Di(e,q.self,P,b)),(d=h.e2ee)!=null&&d.enabled&&h.e2ee.manager.init(m,L),h.chat&&(Y=yield Ii.init(e,V,Xe,q.self,fe.participants)),h.internals&&($=yield am.init()),h.livestream&&r.viewType===zt.Livestream&&re.hasFeature(ue.LIVESTREAM)&&(Ie=new P0(q.self,ye)),r.viewType!==zt.Chat){if(h.poll&&(F=yield g0.init(e,q.self,ht)),h.recording&&(me=new w0(e,q.self,P)),h.stage&&(X=new T0(e,I,P,q.self,fe.participants)),h.plugin){if(!fe)throw new O("The plugin module cannot be initialized without the `participant` module","0102");const Rn=yield i;A=yield Tc.init(e,Rn,K,V,Y==null?void 0:Y.chat,q.self,fe.participants,s)}if(h.pip){const Rn=yield oP._init(e,q.self);e.setValue("pip",Rn)}}const Ze={storesManager:new r2(e,K),pollController:F,selfController:q,metaController:N,chatController:Y,stageController:X,pluginController:A,recordingController:me,internalsController:$,livestreamController:Ie,participantController:fe};return{theme:r,permissions:D,controllers:Ze}})}static createRoomNodeClient(t,e){const{peerId:n,roomNodeOptions:i}=t.getAllValues(),{sfu:s}=i;return rE(t,s,{socket:e,peerId:n})}static createSocketService(t){const{peerId:e,meetingId:n,authToken:i}=t.getAllValues(),s=["PING"];return new _c(t,{peerId:e,meetingId:n,authToken:i,capabilities:s})}};let Ic=ca;eu([k.trace("Controller.init")],Ic,"init",1);eu([k.trace("setupFlagsmith")],Ic,"setupFlagsmith",1);eu([k.trace("Controller.createRoomNodeClient")],Ic,"createRoomNodeClient",1);eu([k.trace("Controller.createSocketService")],Ic,"createSocketService",1);var Rx=Object.defineProperty,Px=Object.getOwnPropertyDescriptor,Ax=(t,e,n,i)=>{for(var s=i>1?void 0:i?Px(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&Rx(e,n,s),s},Gd,Rp;class bE extends fn{constructor(e,n){super(),S(this,Gd,void 0),y(this,"meetings",[]),y(this,"parentMeeting",null),S(this,Rp,void 0),T(this,Rp,e),T(this,Gd,n.self)}get supportsConnectedMeetings(){return o(this,Gd).id!==""}get isActive(){return this.meetings.length!==0}get currentMeetingId(){return $e.currentMeetingId}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
27
+ Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`)}getConnectedMeetings(){return p(this,null,function*(){return this.validateConnectedMeetingsAction(),yield $e.getConnectedRoomsDump()})}createMeetings(e){return p(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield $e.createConnectedRooms(e)).map(n=>({id:n.id,title:n.title}))})}updateMeetings(e){return p(this,null,function*(){this.validateConnectedMeetingsAction(),yield $e.updateConnectedRooms(e.map(n=>({meetingId:n.id,title:n.title})))})}deleteMeetings(e){return p(this,null,function*(){this.validateConnectedMeetingsAction();const n=this.meetings.map(i=>e.includes(i.id)&&i.participants.length!==0?this.moveParticipants(i.id,this.parentMeeting.id,i.participants.map(s=>s.id)):Promise.resolve());return yield Promise.all(n),yield $e.disableConnectedRooms(e)})}moveParticipants(e,n,i){return p(this,null,function*(){this.validateConnectedMeetingsAction();const s=yield $e.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:n,participants:i.map(r=>({id:r}))});return s.success&&this.moveSuccessHandler(e,n,i),s})}moveParticipantsWithCustomPreset(e,n,i){return p(this,null,function*(){this.validateConnectedMeetingsAction();const s=yield $e.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:n,participants:i});return s.success&&this.moveSuccessHandler(e,n,i.map(r=>r.id)),s})}moveSuccessHandler(e,n,i){const s=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(r=>r.participants)].forEach(r=>s.set(r.id,r)),n===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(r=>s.get(r)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(r=>!i.includes(r.id))),this.meetings=this.meetings.map(r=>{if(n===r.id){const a=r.participants.concat(i.map(c=>s.get(c)));return ee(H({},r),{participants:a})}if(e===r.id){const a=r.participants.filter(c=>!i.includes(c.id));return ee(H({},r),{participants:a})}return r})}}Gd=new WeakMap,Rp=new WeakMap;Ax([an({maxInvocations:60,period:60})],bE.prototype,"getConnectedMeetings",1);var Mx=Object.defineProperty,Ox=Object.getOwnPropertyDescriptor,ym=(t,e,n,i)=>{for(var s=i>1?void 0:i?Ox(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&Mx(e,n,s),s},uo,Nn,Xu,Zu;const us=(Xu=class{constructor(t,e,n){y(this,"connectedMeetings"),S(this,uo,void 0),S(this,Nn,void 0),S(this,Zu,void 0),T(this,Zu,t),T(this,uo,n),this.connectedMeetings=new bE(t,e),this.setCurrentMeeting(e)}static init(t,e,n){return us.instance||(us.instance=new us(t,e,n)),us.instance.connectedMeetings.supportsConnectedMeetings&&(us.instance.setupEvents(),e.self.once("roomJoined",()=>us.instance.getConnectedMeetings())),us.instance}setCurrentMeeting(t){T(this,Nn,t),$e.currentMeetingId=t.meta.meetingId}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){$e.socketService&&($e.socketService.on(z.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),$e.socketService.on(z.transferPeer,this.handleTransferPeer.bind(this)),$e.socketService.on(z.movedPeer,this.handleMovedPeer.bind(this)),$e.socketService.on(z.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),$e.socketService.on(z.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this)))}handleTransferPeer(t){const e=$e.handleTransferPeerRaw(t);return this.switchMeeting(e)}switchMeeting(t){return p(this,arguments,function*({authToken:e,meetingId:n}){var i,s,r,a;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
28
+ Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`);m.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",n);const c={video:o(this,Nn).self.videoEnabled,audio:o(this,Nn).self.audioEnabled};try{o(this,Nn).self.cleanupEvents(),yield o(this,Nn).leave("connected-meeting")}catch(h){m.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(s=(i=o(this,Nn))==null?void 0:i.meta)==null?void 0:s.meetingId}`,{error:h})}$e.socketService=void 0,m.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${n}`);const d=yield kE.init(ee(H({},o(this,uo)),{cachedUserDetails:null,defaults:ee(H(H({},o(this,uo).defaults),c),{mediaHandler:o(this,Nn).self}),authToken:e}));m.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(r=d==null?void 0:d.meta)==null?void 0:r.meetingId}`);try{const{hidden:h}=o(this,Nn).self;d.self.setName(o(this,Nn).self.name),yield d.join(),h&&d.self.hide()}catch(h){m.error("ConnectedMeetingsController.joinRoom",{error:h})}return m.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(a=d==null?void 0:d.meta)==null?void 0:a.meetingId}`),this.connectedMeetings.emit("meetingChanged",d),this.setCurrentMeeting(d),d})}handleConnectedRoomsDump(t){const e=$e.handleConnectedRoomsDumpRaw(t);this.connectedMeetings.meetings=e.meetings.map(n=>({id:n.id,title:n.title,participants:n.participants||[]})),this.connectedMeetings.parentMeeting={id:e.parentMeeting.id,title:e.parentMeeting.title,participants:e.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(t){return $e.handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=$e.handleConnectedRoomsUpdatedRaw(t),n=new Map;this.connectedMeetings.meetings.forEach(i=>{n.set(i.id,i)}),e.forEach(i=>{n.has(i.id)?n.get(i.id).title=i.title:n.set(i.id,ee(H({},i),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(n.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=$e.handleConnectedRoomsDeletedRaw(t).map(n=>n.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(n=>!e.includes(n.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},uo=new WeakMap,Nn=new WeakMap,Zu=new WeakMap,y(Xu,"instance"),Xu);let tu=us;ym([k.trace("ConnectedMeetingsController.getConnectedMeetings")],tu.prototype,"getConnectedMeetings",1);ym([k.trace("ConnectedMeetingsController.setupEvents")],tu.prototype,"setupEvents",1);ym([k.trace("ConnectedMeetingsController.switchMeeting")],tu.prototype,"switchMeeting",1);class Dx{constructor(){y(this,"battery"),y(this,"init",()=>p(this,null,function*(){try{"getBattery"in navigator&&(this.battery=yield navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){m.error("Error getting battery",e)}})),y(this,"updateChargeInfo",()=>{var e;m.log(`Battery charging? ${(e=this.battery)!=null&&e.charging?"Yes":"No"}`)}),y(this,"updateLevelInfo",()=>{if(!this.battery){m.log("Battery level: Not known");return}m.log(`Battery level: ${this.battery.level*100}%`)}),y(this,"cleanup",()=>{var e,n;"getBattery"in navigator&&((e=this.battery)==null||e.removeEventListener("chargingchange",this.updateChargeInfo),(n=this.battery)==null||n.removeEventListener("levelchange",this.updateLevelInfo))})}}const ev=new Dx;function Nx(t,e){t.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c \u2014 not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.dyte.io/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:n,orgId:i,participantId:s}=JSON.parse(atob(t.split(".")[1]));if(!n)throw Error(`Received V1 auth token ${t}`);let r="dyte.io";e&&(r=e);const a=`https://api.${r}`;return{meetingId:n,orgId:i,participantId:s,baseURI:r,apiBase:a}}catch(n){throw m.error("constants::decodeAuthToken",{error:n,debuggingHint:`Unable to decode auth token: ${t}`},!0),new O("Invalid auth token","0004")}}var Lx=Object.defineProperty,xx=Object.getOwnPropertyDescriptor,nu=(t,e,n,i)=>{for(var s=i>1?void 0:i?xx(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&Lx(e,n,s),s},Ct,rd,ad,eh,tv,nv;let ws=(nv=class{constructor(t,e){S(this,eh),S(this,Ct,void 0),S(this,rd,void 0),S(this,ad,void 0),T(this,ad,t),T(this,Ct,e)}static init(t){return p(this,null,function*(){var e,n,i,s,r,a,c;ZR(),Be.init();const d=(n=(e=t==null?void 0:t.cachedUserDetails)==null?void 0:e.peerId)!=null?n:Ia();ev.init();const{authToken:h,baseURI:u}=t,g=Nx(h,u),{meetingId:E}=g,b=Pl(g,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const w=ws.setupContext(d,t,E,b);k.meetingMetadata.roomName=E,k.meetingMetadata.userId=b.participantId,k.meetingMetadata.organizationId=b.orgId,k.init(w,(s=(i=t.modules)==null?void 0:i.tracing)!=null?s:!0),m.info("DyteClient::init::options",{dyteClientInitOptions:ee(H({},t),{authToken:`${(r=t.authToken)==null?void 0:r.slice(0,10)}...
29
+ ${(a=t.authToken)==null?void 0:a.slice(-10)}`})});const M=yield Ic.init(w),D=new ws(w,M);return Q(c=D,eh,tv).call(c,t),D})}static setupContext(t,e,n,i){var s;const r=pr.createContext(t,e),a=H(H({},JR),e==null?void 0:e.modules);return r.setValue("peerId",t),r.setValue("modules",a),r.setValue("sdkName","web-core"),r.setValue("meetingId",n),r.setValue("apiBase",i.apiBase),r.setValue("baseURI",i.baseURI),r.setValue("userId",i.participantId),r.setValue("organizationId",i.orgId),r.setValue("authToken",e.authToken),r.setValue("overrides",(s=e.overrides)!=null?s:{}),r.setValue("env",KR({baseURI:i.baseURI})),r.setValue("defaults",e.defaults||{audio:!0,video:!0}),r.setValue("onError",e.onError||(()=>{})),r.setValue("cachedUserDetails",qn(e.cachedUserDetails)),r.setValue("sdkVersion","VERSION_PLACEHOLDER"),r}join(){return p(this,null,function*(){const{selfController:t}=o(this,Ct);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return p(this,null,function*(){ev.cleanup();const{selfController:e}=o(this,Ct);return e.leaveRoom(t)})}get participants(){var t;return(t=o(this,Ct).participantController)==null?void 0:t.participants}get self(){var t;return(t=o(this,Ct).selfController)==null?void 0:t.self}get meta(){var t;return(t=o(this,Ct).metaController)==null?void 0:t.meta}get ai(){var t;return(t=o(this,Ct).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=o(this,Ct).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=o(this,Ct).chatController)==null?void 0:t.chat}get polls(){var t;return(t=o(this,Ct).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=o(this,rd))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=o(this,Ct).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=o(this,Ct).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=o(this,Ct).stageController)==null?void 0:t.stage}get stores(){return o(this,Ct).storesManager}get __internals__(){var t;return(t=o(this,Ct).internalsController)==null?void 0:t.internals}joinRoom(){return p(this,null,function*(){return this.join()})}leaveRoom(t){return p(this,null,function*(){return this.leave(t)})}},Ct=new WeakMap,rd=new WeakMap,ad=new WeakMap,eh=new WeakSet,tv=function(t){T(this,rd,tu.init(o(this,ad),this,t))},nv);nu([Lt("0002"),Cs.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],ws.prototype,"join",1);nu([Lt("0003")],ws.prototype,"leave",1);nu([Lt("0001"),Cs.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],ws,"init",1);ws=nu([Lt("0000")],ws);const kE=ws;module.exports=kE;