@cloudflare/realtimekit 0.5.0-staging.49 → 0.5.0-staging.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.js CHANGED
@@ -1,23 +1,23 @@
1
- var RealtimeKitClient=function(){"use strict";var go,cv=new Uint8Array(16);function dv(){if(!go&&(go=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!go))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return go(cv)}var lv=/^(?:[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 Uc(t){return typeof t=="string"&&lv.test(t)}for(var nt=[],Vc=0;Vc<256;++Vc)nt.push((Vc+256).toString(16).substr(1));function uv(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=(nt[t[e+0]]+nt[t[e+1]]+nt[t[e+2]]+nt[t[e+3]]+"-"+nt[t[e+4]]+nt[t[e+5]]+"-"+nt[t[e+6]]+nt[t[e+7]]+"-"+nt[t[e+8]]+nt[t[e+9]]+"-"+nt[t[e+10]]+nt[t[e+11]]+nt[t[e+12]]+nt[t[e+13]]+nt[t[e+14]]+nt[t[e+15]]).toLowerCase();if(!Uc(r))throw TypeError("Stringified UUID is invalid");return r}function gn(t,e,r){t=t||{};var n=t.random||(t.rng||dv)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){r=r||0;for(var i=0;i<16;++i)e[r+i]=n[i];return e}return uv(n)}const hv={"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"},cu={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"},Ve={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},pt={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"},Ur={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};class D{static getFirstMatch(e,r){const n=r.match(e);return n&&n.length>0&&n[1]||""}static getSecondMatch(e,r){const n=r.match(e);return n&&n.length>1&&n[2]||""}static matchAndReturnConst(e,r,n){if(e.test(r))return n}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 r=e.split(".").splice(0,2).map(n=>parseInt(n,10)||0);if(r.push(0),r[0]===10)switch(r[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 r=e.split(".").splice(0,2).map(n=>parseInt(n,10)||0);if(r.push(0),!(r[0]===1&&r[1]<5)){if(r[0]===1&&r[1]<6)return"Cupcake";if(r[0]===1&&r[1]>=6)return"Donut";if(r[0]===2&&r[1]<2)return"Eclair";if(r[0]===2&&r[1]===2)return"Froyo";if(r[0]===2&&r[1]>2)return"Gingerbread";if(r[0]===3)return"Honeycomb";if(r[0]===4&&r[1]<1)return"Ice Cream Sandwich";if(r[0]===4&&r[1]<4)return"Jelly Bean";if(r[0]===4&&r[1]>=4)return"KitKat";if(r[0]===5)return"Lollipop";if(r[0]===6)return"Marshmallow";if(r[0]===7)return"Nougat";if(r[0]===8)return"Oreo";if(r[0]===9)return"Pie"}}static getVersionPrecision(e){return e.split(".").length}static compareVersions(e,r,n=!1){const i=D.getVersionPrecision(e),s=D.getVersionPrecision(r);let o=Math.max(i,s),a=0;const d=D.map([e,r],h=>{const p=o-D.getVersionPrecision(h),f=h+new Array(p+1).join(".0");return D.map(f.split("."),g=>new Array(20-g.length).join("0")+g).reverse()});for(n&&(a=o-Math.min(i,s)),o-=1;o>=a;){if(d[0][o]>d[1][o])return 1;if(d[0][o]===d[1][o]){if(o===a)return 0;o-=1}else if(d[0][o]<d[1][o])return-1}}static map(e,r){const n=[];let i;if(Array.prototype.map)return Array.prototype.map.call(e,r);for(i=0;i<e.length;i+=1)n.push(r(e[i]));return n}static find(e,r){let n,i;if(Array.prototype.find)return Array.prototype.find.call(e,r);for(n=0,i=e.length;n<i;n+=1){const s=e[n];if(r(s,n))return s}}static assign(e,...r){const n=e;let i,s;if(Object.assign)return Object.assign(e,...r);for(i=0,s=r.length;i<s;i+=1){const o=r[i];typeof o=="object"&&o!==null&&Object.keys(o).forEach(d=>{n[d]=o[d]})}return e}static getBrowserAlias(e){return hv[e]}static getBrowserTypeByAlias(e){return cu[e]||""}}const Te=/version\/(\d+(\.?_?\d+)+)/i,pv=[{test:[/googlebot/i],describe(t){const e={name:"Googlebot"},r=D.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,t)||D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/opera/i],describe(t){const e={name:"Opera"},r=D.getFirstMatch(Te,t)||D.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/opr\/|opios/i],describe(t){const e={name:"Opera"},r=D.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,t)||D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/SamsungBrowser/i],describe(t){const e={name:"Samsung Internet for Android"},r=D.getFirstMatch(Te,t)||D.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/Whale/i],describe(t){const e={name:"NAVER Whale Browser"},r=D.getFirstMatch(Te,t)||D.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/MZBrowser/i],describe(t){const e={name:"MZ Browser"},r=D.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,t)||D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/focus/i],describe(t){const e={name:"Focus"},r=D.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,t)||D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/swing/i],describe(t){const e={name:"Swing"},r=D.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,t)||D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/coast/i],describe(t){const e={name:"Opera Coast"},r=D.getFirstMatch(Te,t)||D.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(t){const e={name:"Opera Touch"},r=D.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,t)||D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/yabrowser/i],describe(t){const e={name:"Yandex Browser"},r=D.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,t)||D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/ucbrowser/i],describe(t){const e={name:"UC Browser"},r=D.getFirstMatch(Te,t)||D.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/Maxthon|mxios/i],describe(t){const e={name:"Maxthon"},r=D.getFirstMatch(Te,t)||D.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/epiphany/i],describe(t){const e={name:"Epiphany"},r=D.getFirstMatch(Te,t)||D.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/puffin/i],describe(t){const e={name:"Puffin"},r=D.getFirstMatch(Te,t)||D.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/sleipnir/i],describe(t){const e={name:"Sleipnir"},r=D.getFirstMatch(Te,t)||D.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/k-meleon/i],describe(t){const e={name:"K-Meleon"},r=D.getFirstMatch(Te,t)||D.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/micromessenger/i],describe(t){const e={name:"WeChat"},r=D.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,t)||D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/qqbrowser/i],describe(t){const e={name:/qqbrowserlite/i.test(t)?"QQ Browser Lite":"QQ Browser"},r=D.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,t)||D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/msie|trident/i],describe(t){const e={name:"Internet Explorer"},r=D.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/\sedg\//i],describe(t){const e={name:"Microsoft Edge"},r=D.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/edg([ea]|ios)/i],describe(t){const e={name:"Microsoft Edge"},r=D.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/vivaldi/i],describe(t){const e={name:"Vivaldi"},r=D.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/seamonkey/i],describe(t){const e={name:"SeaMonkey"},r=D.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/sailfish/i],describe(t){const e={name:"Sailfish"},r=D.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,t);return r&&(e.version=r),e}},{test:[/silk/i],describe(t){const e={name:"Amazon Silk"},r=D.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/phantom/i],describe(t){const e={name:"PhantomJS"},r=D.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/slimerjs/i],describe(t){const e={name:"SlimerJS"},r=D.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(t){const e={name:"BlackBerry"},r=D.getFirstMatch(Te,t)||D.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/(web|hpw)[o0]s/i],describe(t){const e={name:"WebOS Browser"},r=D.getFirstMatch(Te,t)||D.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/bada/i],describe(t){const e={name:"Bada"},r=D.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/tizen/i],describe(t){const e={name:"Tizen"},r=D.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,t)||D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/qupzilla/i],describe(t){const e={name:"QupZilla"},r=D.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,t)||D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/firefox|iceweasel|fxios/i],describe(t){const e={name:"Firefox"},r=D.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/electron/i],describe(t){const e={name:"Electron"},r=D.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/MiuiBrowser/i],describe(t){const e={name:"Miui"},r=D.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/chromium/i],describe(t){const e={name:"Chromium"},r=D.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,t)||D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/chrome|crios|crmo/i],describe(t){const e={name:"Chrome"},r=D.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/GSA/i],describe(t){const e={name:"Google Search"},r=D.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test(t){const e=!t.test(/like android/i),r=t.test(/android/i);return e&&r},describe(t){const e={name:"Android Browser"},r=D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/playstation 4/i],describe(t){const e={name:"PlayStation 4"},r=D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/safari|applewebkit/i],describe(t){const e={name:"Safari"},r=D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/.*/i],describe(t){const e=/^(.*)\/(.*) /,r=/^(.*)\/(.*)[ \t]\((.*)/,i=t.search("\\(")!==-1?r:e;return{name:D.getFirstMatch(i,t),version:D.getSecondMatch(i,t)}}}];var mv=[{test:[/Roku\/DVP/],describe(t){const e=D.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,t);return{name:pt.Roku,version:e}}},{test:[/windows phone/i],describe(t){const e=D.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,t);return{name:pt.WindowsPhone,version:e}}},{test:[/windows /i],describe(t){const e=D.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,t),r=D.getWindowsVersionName(e);return{name:pt.Windows,version:e,versionName:r}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(t){const e={name:pt.iOS},r=D.getSecondMatch(/(Version\/)(\d[\d.]+)/,t);return r&&(e.version=r),e}},{test:[/macintosh/i],describe(t){const e=D.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,t).replace(/[_\s]/g,"."),r=D.getMacOSVersionName(e),n={name:pt.MacOS,version:e};return r&&(n.versionName=r),n}},{test:[/(ipod|iphone|ipad)/i],describe(t){const e=D.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,t).replace(/[_\s]/g,".");return{name:pt.iOS,version:e}}},{test(t){const e=!t.test(/like android/i),r=t.test(/android/i);return e&&r},describe(t){const e=D.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,t),r=D.getAndroidVersionName(e),n={name:pt.Android,version:e};return r&&(n.versionName=r),n}},{test:[/(web|hpw)[o0]s/i],describe(t){const e=D.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,t),r={name:pt.WebOS};return e&&e.length&&(r.version=e),r}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(t){const e=D.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,t)||D.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,t)||D.getFirstMatch(/\bbb(\d+)/i,t);return{name:pt.BlackBerry,version:e}}},{test:[/bada/i],describe(t){const e=D.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,t);return{name:pt.Bada,version:e}}},{test:[/tizen/i],describe(t){const e=D.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,t);return{name:pt.Tizen,version:e}}},{test:[/linux/i],describe(){return{name:pt.Linux}}},{test:[/CrOS/],describe(){return{name:pt.ChromeOS}}},{test:[/PlayStation 4/],describe(t){const e=D.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,t);return{name:pt.PlayStation4,version:e}}}],fv=[{test:[/googlebot/i],describe(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe(t){const e=D.getFirstMatch(/(can-l01)/i,t)&&"Nova",r={type:Ve.mobile,vendor:"Huawei"};return e&&(r.model=e),r}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe(){return{type:Ve.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe(){return{type:Ve.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(){return{type:Ve.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe(){return{type:Ve.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe(){return{type:Ve.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe(){return{type:Ve.tablet}}},{test(t){const e=t.test(/ipod|iphone/i),r=t.test(/like (ipod|iphone)/i);return e&&!r},describe(t){const e=D.getFirstMatch(/(ipod|iphone)/i,t);return{type:Ve.mobile,vendor:"Apple",model:e}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe(){return{type:Ve.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe(){return{type:Ve.mobile}}},{test(t){return t.getBrowserName(!0)==="blackberry"},describe(){return{type:Ve.mobile,vendor:"BlackBerry"}}},{test(t){return t.getBrowserName(!0)==="bada"},describe(){return{type:Ve.mobile}}},{test(t){return t.getBrowserName()==="windows phone"},describe(){return{type:Ve.mobile,vendor:"Microsoft"}}},{test(t){const e=Number(String(t.getOSVersion()).split(".")[0]);return t.getOSName(!0)==="android"&&e>=3},describe(){return{type:Ve.tablet}}},{test(t){return t.getOSName(!0)==="android"},describe(){return{type:Ve.mobile}}},{test(t){return t.getOSName(!0)==="macos"},describe(){return{type:Ve.desktop,vendor:"Apple"}}},{test(t){return t.getOSName(!0)==="windows"},describe(){return{type:Ve.desktop}}},{test(t){return t.getOSName(!0)==="linux"},describe(){return{type:Ve.desktop}}},{test(t){return t.getOSName(!0)==="playstation 4"},describe(){return{type:Ve.tv}}},{test(t){return t.getOSName(!0)==="roku"},describe(){return{type:Ve.tv}}}],gv=[{test(t){return t.getBrowserName(!0)==="microsoft edge"},describe(t){if(/\sedg\//i.test(t))return{name:Ur.Blink};const r=D.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,t);return{name:Ur.EdgeHTML,version:r}}},{test:[/trident/i],describe(t){const e={name:Ur.Trident},r=D.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test(t){return t.test(/presto/i)},describe(t){const e={name:Ur.Presto},r=D.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test(t){const e=t.test(/gecko/i),r=t.test(/like gecko/i);return e&&!r},describe(t){const e={name:Ur.Gecko},r=D.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:Ur.Blink}}},{test:[/(apple)?webkit/i],describe(t){const e={name:Ur.WebKit},r=D.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}}];class du{constructor(e,r=!1){if(e==null||e==="")throw new Error("UserAgent parameter can't be empty");this._ua=e,this.parsedResult={},r!==!0&&this.parse()}getUA(){return this._ua}test(e){return e.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const e=D.find(pv,r=>{if(typeof r.test=="function")return r.test(this);if(r.test instanceof Array)return r.test.some(n=>this.test(n));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=D.find(mv,r=>{if(typeof r.test=="function")return r.test(this);if(r.test instanceof Array)return r.test.some(n=>this.test(n));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:r}=this.getOS();return e?String(r).toLowerCase()||"":r||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(e=!1){const{type:r}=this.getPlatform();return e?String(r).toLowerCase()||"":r||""}parsePlatform(){this.parsedResult.platform={};const e=D.find(fv,r=>{if(typeof r.test=="function")return r.test(this);if(r.test instanceof Array)return r.test.some(n=>this.test(n));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=D.find(gv,r=>{if(typeof r.test=="function")return r.test(this);if(r.test instanceof Array)return r.test.some(n=>this.test(n));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 D.assign({},this.parsedResult)}satisfies(e){const r={};let n=0;const i={};let s=0;if(Object.keys(e).forEach(a=>{const d=e[a];typeof d=="string"?(i[a]=d,s+=1):typeof d=="object"&&(r[a]=d,n+=1)}),n>0){const a=Object.keys(r),d=D.find(a,p=>this.isOS(p));if(d){const p=this.satisfies(r[d]);if(p!==void 0)return p}const h=D.find(a,p=>this.isPlatform(p));if(h){const p=this.satisfies(r[h]);if(p!==void 0)return p}}if(s>0){const a=Object.keys(i),d=D.find(a,h=>this.isBrowser(h,!0));if(d!==void 0)return this.compareVersion(i[d])}}isBrowser(e,r=!1){const n=this.getBrowserName().toLowerCase();let i=e.toLowerCase();const s=D.getBrowserTypeByAlias(i);return r&&s&&(i=s.toLowerCase()),i===n}compareVersion(e){let r=[0],n=e,i=!1;const s=this.getBrowserVersion();if(typeof s=="string")return e[0]===">"||e[0]==="<"?(n=e.substr(1),e[1]==="="?(i=!0,n=e.substr(2)):r=[],e[0]===">"?r.push(1):r.push(-1)):e[0]==="="?n=e.substr(1):e[0]==="~"&&(i=!0,n=e.substr(1)),r.indexOf(D.compareVersions(s,n,i))>-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,r=!1){return this.isBrowser(e,r)||this.isOS(e)||this.isPlatform(e)}some(e=[]){return e.some(r=>this.is(r))}}/*!
1
+ var RealtimeKitClient=function(){"use strict";var eo,ty=new Uint8Array(16);function ry(){if(!eo&&(eo=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!eo))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return eo(ty)}var ny=/^(?:[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 Td(t){return typeof t=="string"&&ny.test(t)}for(var ut=[],kd=0;kd<256;++kd)ut.push((kd+256).toString(16).substr(1));function iy(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=(ut[t[e+0]]+ut[t[e+1]]+ut[t[e+2]]+ut[t[e+3]]+"-"+ut[t[e+4]]+ut[t[e+5]]+"-"+ut[t[e+6]]+ut[t[e+7]]+"-"+ut[t[e+8]]+ut[t[e+9]]+"-"+ut[t[e+10]]+ut[t[e+11]]+ut[t[e+12]]+ut[t[e+13]]+ut[t[e+14]]+ut[t[e+15]]).toLowerCase();if(!Td(r))throw TypeError("Stringified UUID is invalid");return r}function Un(t,e,r){t=t||{};var n=t.random||(t.rng||ry)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){r=r||0;for(var i=0;i<16;++i)e[r+i]=n[i];return e}return iy(n)}const sy={"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"},Yu={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"},We={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},Et={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"},rn={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};class x{static getFirstMatch(e,r){const n=r.match(e);return n&&n.length>0&&n[1]||""}static getSecondMatch(e,r){const n=r.match(e);return n&&n.length>1&&n[2]||""}static matchAndReturnConst(e,r,n){if(e.test(r))return n}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 r=e.split(".").splice(0,2).map(n=>parseInt(n,10)||0);if(r.push(0),r[0]===10)switch(r[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 r=e.split(".").splice(0,2).map(n=>parseInt(n,10)||0);if(r.push(0),!(r[0]===1&&r[1]<5)){if(r[0]===1&&r[1]<6)return"Cupcake";if(r[0]===1&&r[1]>=6)return"Donut";if(r[0]===2&&r[1]<2)return"Eclair";if(r[0]===2&&r[1]===2)return"Froyo";if(r[0]===2&&r[1]>2)return"Gingerbread";if(r[0]===3)return"Honeycomb";if(r[0]===4&&r[1]<1)return"Ice Cream Sandwich";if(r[0]===4&&r[1]<4)return"Jelly Bean";if(r[0]===4&&r[1]>=4)return"KitKat";if(r[0]===5)return"Lollipop";if(r[0]===6)return"Marshmallow";if(r[0]===7)return"Nougat";if(r[0]===8)return"Oreo";if(r[0]===9)return"Pie"}}static getVersionPrecision(e){return e.split(".").length}static compareVersions(e,r,n=!1){const i=x.getVersionPrecision(e),s=x.getVersionPrecision(r);let a=Math.max(i,s),o=0;const d=x.map([e,r],h=>{const p=a-x.getVersionPrecision(h),m=h+new Array(p+1).join(".0");return x.map(m.split("."),g=>new Array(20-g.length).join("0")+g).reverse()});for(n&&(o=a-Math.min(i,s)),a-=1;a>=o;){if(d[0][a]>d[1][a])return 1;if(d[0][a]===d[1][a]){if(a===o)return 0;a-=1}else if(d[0][a]<d[1][a])return-1}}static map(e,r){const n=[];let i;if(Array.prototype.map)return Array.prototype.map.call(e,r);for(i=0;i<e.length;i+=1)n.push(r(e[i]));return n}static find(e,r){let n,i;if(Array.prototype.find)return Array.prototype.find.call(e,r);for(n=0,i=e.length;n<i;n+=1){const s=e[n];if(r(s,n))return s}}static assign(e,...r){const n=e;let i,s;if(Object.assign)return Object.assign(e,...r);for(i=0,s=r.length;i<s;i+=1){const a=r[i];typeof a=="object"&&a!==null&&Object.keys(a).forEach(d=>{n[d]=a[d]})}return e}static getBrowserAlias(e){return sy[e]}static getBrowserTypeByAlias(e){return Yu[e]||""}}const _e=/version\/(\d+(\.?_?\d+)+)/i,ay=[{test:[/googlebot/i],describe(t){const e={name:"Googlebot"},r=x.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,t)||x.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/opera/i],describe(t){const e={name:"Opera"},r=x.getFirstMatch(_e,t)||x.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/opr\/|opios/i],describe(t){const e={name:"Opera"},r=x.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,t)||x.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/SamsungBrowser/i],describe(t){const e={name:"Samsung Internet for Android"},r=x.getFirstMatch(_e,t)||x.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/Whale/i],describe(t){const e={name:"NAVER Whale Browser"},r=x.getFirstMatch(_e,t)||x.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/MZBrowser/i],describe(t){const e={name:"MZ Browser"},r=x.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,t)||x.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/focus/i],describe(t){const e={name:"Focus"},r=x.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,t)||x.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/swing/i],describe(t){const e={name:"Swing"},r=x.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,t)||x.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/coast/i],describe(t){const e={name:"Opera Coast"},r=x.getFirstMatch(_e,t)||x.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(t){const e={name:"Opera Touch"},r=x.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,t)||x.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/yabrowser/i],describe(t){const e={name:"Yandex Browser"},r=x.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,t)||x.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/ucbrowser/i],describe(t){const e={name:"UC Browser"},r=x.getFirstMatch(_e,t)||x.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/Maxthon|mxios/i],describe(t){const e={name:"Maxthon"},r=x.getFirstMatch(_e,t)||x.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/epiphany/i],describe(t){const e={name:"Epiphany"},r=x.getFirstMatch(_e,t)||x.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/puffin/i],describe(t){const e={name:"Puffin"},r=x.getFirstMatch(_e,t)||x.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/sleipnir/i],describe(t){const e={name:"Sleipnir"},r=x.getFirstMatch(_e,t)||x.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/k-meleon/i],describe(t){const e={name:"K-Meleon"},r=x.getFirstMatch(_e,t)||x.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/micromessenger/i],describe(t){const e={name:"WeChat"},r=x.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,t)||x.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/qqbrowser/i],describe(t){const e={name:/qqbrowserlite/i.test(t)?"QQ Browser Lite":"QQ Browser"},r=x.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,t)||x.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/msie|trident/i],describe(t){const e={name:"Internet Explorer"},r=x.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/\sedg\//i],describe(t){const e={name:"Microsoft Edge"},r=x.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/edg([ea]|ios)/i],describe(t){const e={name:"Microsoft Edge"},r=x.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/vivaldi/i],describe(t){const e={name:"Vivaldi"},r=x.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/seamonkey/i],describe(t){const e={name:"SeaMonkey"},r=x.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/sailfish/i],describe(t){const e={name:"Sailfish"},r=x.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,t);return r&&(e.version=r),e}},{test:[/silk/i],describe(t){const e={name:"Amazon Silk"},r=x.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/phantom/i],describe(t){const e={name:"PhantomJS"},r=x.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/slimerjs/i],describe(t){const e={name:"SlimerJS"},r=x.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(t){const e={name:"BlackBerry"},r=x.getFirstMatch(_e,t)||x.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/(web|hpw)[o0]s/i],describe(t){const e={name:"WebOS Browser"},r=x.getFirstMatch(_e,t)||x.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/bada/i],describe(t){const e={name:"Bada"},r=x.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/tizen/i],describe(t){const e={name:"Tizen"},r=x.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,t)||x.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/qupzilla/i],describe(t){const e={name:"QupZilla"},r=x.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,t)||x.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/firefox|iceweasel|fxios/i],describe(t){const e={name:"Firefox"},r=x.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/electron/i],describe(t){const e={name:"Electron"},r=x.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/MiuiBrowser/i],describe(t){const e={name:"Miui"},r=x.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/chromium/i],describe(t){const e={name:"Chromium"},r=x.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,t)||x.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/chrome|crios|crmo/i],describe(t){const e={name:"Chrome"},r=x.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/GSA/i],describe(t){const e={name:"Google Search"},r=x.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test(t){const e=!t.test(/like android/i),r=t.test(/android/i);return e&&r},describe(t){const e={name:"Android Browser"},r=x.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/playstation 4/i],describe(t){const e={name:"PlayStation 4"},r=x.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/safari|applewebkit/i],describe(t){const e={name:"Safari"},r=x.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/.*/i],describe(t){const e=/^(.*)\/(.*) /,r=/^(.*)\/(.*)[ \t]\((.*)/,i=t.search("\\(")!==-1?r:e;return{name:x.getFirstMatch(i,t),version:x.getSecondMatch(i,t)}}}];var oy=[{test:[/Roku\/DVP/],describe(t){const e=x.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,t);return{name:Et.Roku,version:e}}},{test:[/windows phone/i],describe(t){const e=x.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,t);return{name:Et.WindowsPhone,version:e}}},{test:[/windows /i],describe(t){const e=x.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,t),r=x.getWindowsVersionName(e);return{name:Et.Windows,version:e,versionName:r}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(t){const e={name:Et.iOS},r=x.getSecondMatch(/(Version\/)(\d[\d.]+)/,t);return r&&(e.version=r),e}},{test:[/macintosh/i],describe(t){const e=x.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,t).replace(/[_\s]/g,"."),r=x.getMacOSVersionName(e),n={name:Et.MacOS,version:e};return r&&(n.versionName=r),n}},{test:[/(ipod|iphone|ipad)/i],describe(t){const e=x.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,t).replace(/[_\s]/g,".");return{name:Et.iOS,version:e}}},{test(t){const e=!t.test(/like android/i),r=t.test(/android/i);return e&&r},describe(t){const e=x.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,t),r=x.getAndroidVersionName(e),n={name:Et.Android,version:e};return r&&(n.versionName=r),n}},{test:[/(web|hpw)[o0]s/i],describe(t){const e=x.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,t),r={name:Et.WebOS};return e&&e.length&&(r.version=e),r}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(t){const e=x.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,t)||x.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,t)||x.getFirstMatch(/\bbb(\d+)/i,t);return{name:Et.BlackBerry,version:e}}},{test:[/bada/i],describe(t){const e=x.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,t);return{name:Et.Bada,version:e}}},{test:[/tizen/i],describe(t){const e=x.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,t);return{name:Et.Tizen,version:e}}},{test:[/linux/i],describe(){return{name:Et.Linux}}},{test:[/CrOS/],describe(){return{name:Et.ChromeOS}}},{test:[/PlayStation 4/],describe(t){const e=x.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,t);return{name:Et.PlayStation4,version:e}}}],cy=[{test:[/googlebot/i],describe(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe(t){const e=x.getFirstMatch(/(can-l01)/i,t)&&"Nova",r={type:We.mobile,vendor:"Huawei"};return e&&(r.model=e),r}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe(){return{type:We.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe(){return{type:We.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(){return{type:We.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe(){return{type:We.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe(){return{type:We.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe(){return{type:We.tablet}}},{test(t){const e=t.test(/ipod|iphone/i),r=t.test(/like (ipod|iphone)/i);return e&&!r},describe(t){const e=x.getFirstMatch(/(ipod|iphone)/i,t);return{type:We.mobile,vendor:"Apple",model:e}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe(){return{type:We.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe(){return{type:We.mobile}}},{test(t){return t.getBrowserName(!0)==="blackberry"},describe(){return{type:We.mobile,vendor:"BlackBerry"}}},{test(t){return t.getBrowserName(!0)==="bada"},describe(){return{type:We.mobile}}},{test(t){return t.getBrowserName()==="windows phone"},describe(){return{type:We.mobile,vendor:"Microsoft"}}},{test(t){const e=Number(String(t.getOSVersion()).split(".")[0]);return t.getOSName(!0)==="android"&&e>=3},describe(){return{type:We.tablet}}},{test(t){return t.getOSName(!0)==="android"},describe(){return{type:We.mobile}}},{test(t){return t.getOSName(!0)==="macos"},describe(){return{type:We.desktop,vendor:"Apple"}}},{test(t){return t.getOSName(!0)==="windows"},describe(){return{type:We.desktop}}},{test(t){return t.getOSName(!0)==="linux"},describe(){return{type:We.desktop}}},{test(t){return t.getOSName(!0)==="playstation 4"},describe(){return{type:We.tv}}},{test(t){return t.getOSName(!0)==="roku"},describe(){return{type:We.tv}}}],dy=[{test(t){return t.getBrowserName(!0)==="microsoft edge"},describe(t){if(/\sedg\//i.test(t))return{name:rn.Blink};const r=x.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,t);return{name:rn.EdgeHTML,version:r}}},{test:[/trident/i],describe(t){const e={name:rn.Trident},r=x.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test(t){return t.test(/presto/i)},describe(t){const e={name:rn.Presto},r=x.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test(t){const e=t.test(/gecko/i),r=t.test(/like gecko/i);return e&&!r},describe(t){const e={name:rn.Gecko},r=x.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:rn.Blink}}},{test:[/(apple)?webkit/i],describe(t){const e={name:rn.WebKit},r=x.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}}];class Qu{constructor(e,r=!1){if(e==null||e==="")throw new Error("UserAgent parameter can't be empty");this._ua=e,this.parsedResult={},r!==!0&&this.parse()}getUA(){return this._ua}test(e){return e.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const e=x.find(ay,r=>{if(typeof r.test=="function")return r.test(this);if(r.test instanceof Array)return r.test.some(n=>this.test(n));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=x.find(oy,r=>{if(typeof r.test=="function")return r.test(this);if(r.test instanceof Array)return r.test.some(n=>this.test(n));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:r}=this.getOS();return e?String(r).toLowerCase()||"":r||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(e=!1){const{type:r}=this.getPlatform();return e?String(r).toLowerCase()||"":r||""}parsePlatform(){this.parsedResult.platform={};const e=x.find(cy,r=>{if(typeof r.test=="function")return r.test(this);if(r.test instanceof Array)return r.test.some(n=>this.test(n));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=x.find(dy,r=>{if(typeof r.test=="function")return r.test(this);if(r.test instanceof Array)return r.test.some(n=>this.test(n));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 x.assign({},this.parsedResult)}satisfies(e){const r={};let n=0;const i={};let s=0;if(Object.keys(e).forEach(o=>{const d=e[o];typeof d=="string"?(i[o]=d,s+=1):typeof d=="object"&&(r[o]=d,n+=1)}),n>0){const o=Object.keys(r),d=x.find(o,p=>this.isOS(p));if(d){const p=this.satisfies(r[d]);if(p!==void 0)return p}const h=x.find(o,p=>this.isPlatform(p));if(h){const p=this.satisfies(r[h]);if(p!==void 0)return p}}if(s>0){const o=Object.keys(i),d=x.find(o,h=>this.isBrowser(h,!0));if(d!==void 0)return this.compareVersion(i[d])}}isBrowser(e,r=!1){const n=this.getBrowserName().toLowerCase();let i=e.toLowerCase();const s=x.getBrowserTypeByAlias(i);return r&&s&&(i=s.toLowerCase()),i===n}compareVersion(e){let r=[0],n=e,i=!1;const s=this.getBrowserVersion();if(typeof s=="string")return e[0]===">"||e[0]==="<"?(n=e.substr(1),e[1]==="="?(i=!0,n=e.substr(2)):r=[],e[0]===">"?r.push(1):r.push(-1)):e[0]==="="?n=e.substr(1):e[0]==="~"&&(i=!0,n=e.substr(1)),r.indexOf(x.compareVersions(s,n,i))>-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,r=!1){return this.isBrowser(e,r)||this.isOS(e)||this.isPlatform(e)}some(e=[]){return e.some(r=>this.is(r))}}/*!
2
2
  * Bowser - a browser detector
3
3
  * https://github.com/lancedikson/bowser
4
4
  * MIT License | (c) Dustin Diaz 2012-2015
5
5
  * MIT License | (c) Denis Demchenko 2015-2019
6
- */class lu{static getParser(e,r=!1){if(typeof e!="string")throw new Error("UserAgent should be a string");return new du(e,r)}static parse(e){return new du(e).getResult()}static get BROWSER_MAP(){return cu}static get ENGINE_MAP(){return Ur}static get OS_MAP(){return pt}static get PLATFORMS_MAP(){return Ve}}function Bc(t){let e=typeof t;if(e=="object"){if(Array.isArray(t))return"array";if(t===null)return"null"}return e}function vv(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}let vr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),vo=[];for(let t=0;t<vr.length;t++)vo[vr[t].charCodeAt(0)]=t;vo["-".charCodeAt(0)]=vr.indexOf("+"),vo["_".charCodeAt(0)]=vr.indexOf("/");function yv(t){let e=t.length*3/4;t[t.length-2]=="="?e-=2:t[t.length-1]=="="&&(e-=1);let r=new Uint8Array(e),n=0,i=0,s,o=0;for(let a=0;a<t.length;a++){if(s=vo[t.charCodeAt(a)],s===void 0)switch(t[a]){case"=":i=0;case`
7
- `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(i){case 0:o=s,i=1;break;case 1:r[n++]=o<<2|(s&48)>>4,o=s,i=2;break;case 2:r[n++]=(o&15)<<4|(s&60)>>2,o=s,i=3;break;case 3:r[n++]=(o&3)<<6|s,i=0;break}}if(i==1)throw Error("invalid base64 string.");return r.subarray(0,n)}function Ev(t){let e="",r=0,n,i=0;for(let s=0;s<t.length;s++)switch(n=t[s],r){case 0:e+=vr[n>>2],i=(n&3)<<4,r=1;break;case 1:e+=vr[i|n>>4],i=(n&15)<<2,r=2;break;case 2:e+=vr[i|n>>6],e+=vr[n&63],r=0;break}return r&&(e+=vr[i],e+="=",r==1&&(e+="=")),e}var yo;(function(t){t.symbol=Symbol.for("protobuf-ts/unknown"),t.onRead=(r,n,i,s,o)=>{(e(n)?n[t.symbol]:n[t.symbol]=[]).push({no:i,wireType:s,data:o})},t.onWrite=(r,n,i)=>{for(let{no:s,wireType:o,data:a}of t.list(n))i.tag(s,o).raw(a)},t.list=(r,n)=>{if(e(r)){let i=r[t.symbol];return n?i.filter(s=>s.no==n):i}return[]},t.last=(r,n)=>t.list(r,n).slice(-1)[0];const e=r=>r&&Array.isArray(r[t.symbol])})(yo||(yo={}));var Be;(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"})(Be||(Be={}));function Sv(){let t=0,e=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(t|=(i&127)<<n,(i&128)==0)return this.assertBounds(),[t,e]}let r=this.buf[this.pos++];if(t|=(r&15)<<28,e=(r&112)>>4,(r&128)==0)return this.assertBounds(),[t,e];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(e|=(i&127)<<n,(i&128)==0)return this.assertBounds(),[t,e]}throw new Error("invalid varint")}function jc(t,e,r){for(let s=0;s<28;s=s+7){const o=t>>>s,a=!(o>>>7==0&&e==0),d=(a?o|128:o)&255;if(r.push(d),!a)return}const n=t>>>28&15|(e&7)<<4,i=e>>3!=0;if(r.push((i?n|128:n)&255),!!i){for(let s=3;s<31;s=s+7){const o=e>>>s,a=o>>>7!=0,d=(a?o|128:o)&255;if(r.push(d),!a)return}r.push(e>>>31&1)}}const Eo=(1<<16)*(1<<16);function uu(t){let e=t[0]=="-";e&&(t=t.slice(1));const r=1e6;let n=0,i=0;function s(o,a){const d=Number(t.slice(o,a));i*=r,n=n*r+d,n>=Eo&&(i=i+(n/Eo|0),n=n%Eo)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),[e,n,i]}function Hc(t,e){if(e>>>0<=2097151)return""+(Eo*e+(t>>>0));let r=t&16777215,n=(t>>>24|e<<8)>>>0&16777215,i=e>>16&65535,s=r+n*6777216+i*6710656,o=n+i*8147497,a=i*2,d=1e7;s>=d&&(o+=Math.floor(s/d),s%=d),o>=d&&(a+=Math.floor(o/d),o%=d);function h(p,f){let g=p?String(p):"";return f?"0000000".slice(g.length)+g:g}return h(a,0)+h(o,a)+h(s,1)}function hu(t,e){if(t>=0){for(;t>127;)e.push(t&127|128),t=t>>>7;e.push(t)}else{for(let r=0;r<9;r++)e.push(t&127|128),t=t>>7;e.push(1)}}function Tv(){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 r=5;(t&128)!==0&&r<10;r++)t=this.buf[this.pos++];if((t&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}let ke;function kv(){const t=new DataView(new ArrayBuffer(8));ke=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}kv();function pu(t){if(!t)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const mu=/^-?[0-9]+$/,So=4294967296,To=2147483648;class fu{constructor(e,r){this.lo=e|0,this.hi=r|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let e=this.hi*So+(this.lo>>>0);if(!Number.isSafeInteger(e))throw new Error("cannot convert to safe number");return e}}class ct extends fu{static from(e){if(ke)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=ke.C(e);case"number":if(e===0)return this.ZERO;e=ke.C(e);case"bigint":if(!e)return this.ZERO;if(e<ke.UMIN)throw new Error("signed value for ulong");if(e>ke.UMAX)throw new Error("ulong too large");return ke.V.setBigUint64(0,e,!0),new ct(ke.V.getInt32(0,!0),ke.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!mu.test(e))throw new Error("string is no integer");let[r,n,i]=uu(e);if(r)throw new Error("signed value for ulong");return new ct(n,i);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 ct(e,e/So)}throw new Error("unknown value "+typeof e)}toString(){return ke?this.toBigInt().toString():Hc(this.lo,this.hi)}toBigInt(){return pu(ke),ke.V.setInt32(0,this.lo,!0),ke.V.setInt32(4,this.hi,!0),ke.V.getBigUint64(0,!0)}}ct.ZERO=new ct(0,0);class _e extends fu{static from(e){if(ke)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=ke.C(e);case"number":if(e===0)return this.ZERO;e=ke.C(e);case"bigint":if(!e)return this.ZERO;if(e<ke.MIN)throw new Error("signed long too small");if(e>ke.MAX)throw new Error("signed long too large");return ke.V.setBigInt64(0,e,!0),new _e(ke.V.getInt32(0,!0),ke.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!mu.test(e))throw new Error("string is no integer");let[r,n,i]=uu(e);if(r){if(i>To||i==To&&n!=0)throw new Error("signed long too small")}else if(i>=To)throw new Error("signed long too large");let s=new _e(n,i);return r?s.negate():s;case"number":if(e==0)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");return e>0?new _e(e,e/So):new _e(-e,-e/So).negate()}throw new Error("unknown value "+typeof e)}isNegative(){return(this.hi&To)!==0}negate(){let e=~this.hi,r=this.lo;return r?r=~r+1:e+=1,new _e(r,e)}toString(){if(ke)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return"-"+Hc(e.lo,e.hi)}return Hc(this.lo,this.hi)}toBigInt(){return pu(ke),ke.V.setInt32(0,this.lo,!0),ke.V.setInt32(4,this.hi,!0),ke.V.getBigInt64(0,!0)}}_e.ZERO=new _e(0,0);const gu={readUnknownField:!0,readerFactory:t=>new bv(t)};function _v(t){return t?Object.assign(Object.assign({},gu),t):gu}class bv{constructor(e,r){this.varint64=Sv,this.uint32=Tv,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=r!=null?r:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let e=this.uint32(),r=e>>>3,n=e&7;if(r<=0||n<0||n>5)throw new Error("illegal tag: field no "+r+" wire type "+n);return[r,n]}skip(e){let r=this.pos;switch(e){case Be.Varint:for(;this.buf[this.pos++]&128;);break;case Be.Bit64:this.pos+=4;case Be.Bit32:this.pos+=4;break;case Be.LengthDelimited:let n=this.uint32();this.pos+=n;break;case Be.StartGroup:let i;for(;(i=this.tag()[1])!==Be.EndGroup;)this.skip(i);break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(r,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 _e(...this.varint64())}uint64(){return new ct(...this.varint64())}sint64(){let[e,r]=this.varint64(),n=-(e&1);return e=(e>>>1|(r&1)<<31)^n,r=r>>>1^n,new _e(e,r)}bool(){let[e,r]=this.varint64();return e!==0||r!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new ct(this.sfixed32(),this.sfixed32())}sfixed64(){return new _e(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(),r=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(r,r+e)}string(){return this.textDecoder.decode(this.bytes())}}function fe(t,e){if(!t)throw new Error(e)}const wv=34028234663852886e22,Cv=-34028234663852886e22,Iv=4294967295,Rv=2147483647,Pv=-2147483648;function cs(t){if(typeof t!="number")throw new Error("invalid int 32: "+typeof t);if(!Number.isInteger(t)||t>Rv||t<Pv)throw new Error("invalid int 32: "+t)}function ko(t){if(typeof t!="number")throw new Error("invalid uint 32: "+typeof t);if(!Number.isInteger(t)||t>Iv||t<0)throw new Error("invalid uint 32: "+t)}function Wc(t){if(typeof t!="number")throw new Error("invalid float 32: "+typeof t);if(!!Number.isFinite(t)&&(t>wv||t<Cv))throw new Error("invalid float 32: "+t)}const vu={writeUnknownFields:!0,writerFactory:()=>new Mv};function Av(t){return t?Object.assign(Object.assign({},vu),t):vu}class Mv{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 i=0;i<this.chunks.length;i++)e+=this.chunks[i].length;let r=new Uint8Array(e),n=0;for(let i=0;i<this.chunks.length;i++)r.set(this.chunks[i],n),n+=this.chunks[i].length;return this.chunks=[],r}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),r=this.stack.pop();if(!r)throw new Error("invalid state, fork stack empty");return this.chunks=r.chunks,this.buf=r.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,r){return this.uint32((e<<3|r)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(ko(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return cs(e),hu(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 r=this.textEncoder.encode(e);return this.uint32(r.byteLength),this.raw(r)}float(e){Wc(e);let r=new Uint8Array(4);return new DataView(r.buffer).setFloat32(0,e,!0),this.raw(r)}double(e){let r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,e,!0),this.raw(r)}fixed32(e){ko(e);let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,e,!0),this.raw(r)}sfixed32(e){cs(e);let r=new Uint8Array(4);return new DataView(r.buffer).setInt32(0,e,!0),this.raw(r)}sint32(e){return cs(e),e=(e<<1^e>>31)>>>0,hu(e,this.buf),this}sfixed64(e){let r=new Uint8Array(8),n=new DataView(r.buffer),i=_e.from(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(r)}fixed64(e){let r=new Uint8Array(8),n=new DataView(r.buffer),i=ct.from(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(r)}int64(e){let r=_e.from(e);return jc(r.lo,r.hi,this.buf),this}sint64(e){let r=_e.from(e),n=r.hi>>31,i=r.lo<<1^n,s=(r.hi<<1|r.lo>>>31)^n;return jc(i,s,this.buf),this}uint64(e){let r=ct.from(e);return jc(r.lo,r.hi,this.buf),this}}const yu={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},Eu={ignoreUnknownFields:!1};function Dv(t){return t?Object.assign(Object.assign({},Eu),t):Eu}function Ov(t){return t?Object.assign(Object.assign({},yu),t):yu}const Su=Symbol.for("protobuf-ts/message-type");function Tu(t){let e=!1;const r=[];for(let n=0;n<t.length;n++){let i=t.charAt(n);i=="_"?e=!0:/\d/.test(i)?(r.push(i),e=!0):e?(r.push(i.toUpperCase()),e=!1):n==0?r.push(i.toLowerCase()):r.push(i)}return r.join("")}var M;(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"})(M||(M={}));var sr;(function(t){t[t.BIGINT=0]="BIGINT",t[t.STRING=1]="STRING",t[t.NUMBER=2]="NUMBER"})(sr||(sr={}));var _o;(function(t){t[t.NO=0]="NO",t[t.PACKED=1]="PACKED",t[t.UNPACKED=2]="UNPACKED"})(_o||(_o={}));function Nv(t){var e,r,n,i;return t.localName=(e=t.localName)!==null&&e!==void 0?e:Tu(t.name),t.jsonName=(r=t.jsonName)!==null&&r!==void 0?r:Tu(t.name),t.repeat=(n=t.repeat)!==null&&n!==void 0?n:_o.NO,t.opt=(i=t.opt)!==null&&i!==void 0?i:t.repeat||t.oneof?!1:t.kind=="message",t}function Lv(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 xv{constructor(e){var r;this.fields=(r=e.fields)!==null&&r!==void 0?r:[]}prepare(){if(this.data)return;const e=[],r=[],n=[];for(let i of this.fields)if(i.oneof)n.includes(i.oneof)||(n.push(i.oneof),e.push(i.oneof),r.push(i.oneof));else switch(r.push(i.localName),i.kind){case"scalar":case"enum":(!i.opt||i.repeat)&&e.push(i.localName);break;case"message":i.repeat&&e.push(i.localName);break;case"map":e.push(i.localName);break}this.data={req:e,known:r,oneofs:Object.values(n)}}is(e,r,n=!1){if(r<0)return!0;if(e==null||typeof e!="object")return!1;this.prepare();let i=Object.keys(e),s=this.data;if(i.length<s.req.length||s.req.some(o=>!i.includes(o))||!n&&i.some(o=>!s.known.includes(o)))return!1;if(r<1)return!0;for(const o of s.oneofs){const a=e[o];if(!Lv(a))return!1;if(a.oneofKind===void 0)continue;const d=this.fields.find(h=>h.localName===a.oneofKind);if(!d||!this.field(a[a.oneofKind],d,n,r))return!1}for(const o of this.fields)if(o.oneof===void 0&&!this.field(e[o.localName],o,n,r))return!1;return!0}field(e,r,n,i){let s=r.repeat;switch(r.kind){case"scalar":return e===void 0?r.opt:s?this.scalars(e,r.T,i,r.L):this.scalar(e,r.T,r.L);case"enum":return e===void 0?r.opt:s?this.scalars(e,M.INT32,i):this.scalar(e,M.INT32);case"message":return e===void 0?!0:s?this.messages(e,r.T(),n,i):this.message(e,r.T(),n,i);case"map":if(typeof e!="object"||e===null)return!1;if(i<2)return!0;if(!this.mapKeys(e,r.K,i))return!1;switch(r.V.kind){case"scalar":return this.scalars(Object.values(e),r.V.T,i,r.V.L);case"enum":return this.scalars(Object.values(e),M.INT32,i);case"message":return this.messages(Object.values(e),r.V.T(),n,i)}break}return!0}message(e,r,n,i){return n?r.isAssignable(e,i):r.is(e,i)}messages(e,r,n,i){if(!Array.isArray(e))return!1;if(i<2)return!0;if(n){for(let s=0;s<e.length&&s<i;s++)if(!r.isAssignable(e[s],i-1))return!1}else for(let s=0;s<e.length&&s<i;s++)if(!r.is(e[s],i-1))return!1;return!0}scalar(e,r,n){let i=typeof e;switch(r){case M.UINT64:case M.FIXED64:case M.INT64:case M.SFIXED64:case M.SINT64:switch(n){case sr.BIGINT:return i=="bigint";case sr.NUMBER:return i=="number"&&!isNaN(e);default:return i=="string"}case M.BOOL:return i=="boolean";case M.STRING:return i=="string";case M.BYTES:return e instanceof Uint8Array;case M.DOUBLE:case M.FLOAT:return i=="number"&&!isNaN(e);default:return i=="number"&&Number.isInteger(e)}}scalars(e,r,n,i){if(!Array.isArray(e))return!1;if(n<2)return!0;if(Array.isArray(e)){for(let s=0;s<e.length&&s<n;s++)if(!this.scalar(e[s],r,i))return!1}return!0}mapKeys(e,r,n){let i=Object.keys(e);switch(r){case M.INT32:case M.FIXED32:case M.SFIXED32:case M.SINT32:case M.UINT32:return this.scalars(i.slice(0,n).map(s=>parseInt(s)),r,n);case M.BOOL:return this.scalars(i.slice(0,n).map(s=>s=="true"?!0:s=="false"?!1:s),r,n);default:return this.scalars(i,r,n,sr.STRING)}}}function Gt(t,e){switch(e){case sr.BIGINT:return t.toBigInt();case sr.NUMBER:return t.toNumber();default:return t.toString()}}class Fv{constructor(e){this.info=e}prepare(){var e;if(this.fMap===void 0){this.fMap={};const r=(e=this.info.fields)!==null&&e!==void 0?e:[];for(const n of r)this.fMap[n.name]=n,this.fMap[n.jsonName]=n,this.fMap[n.localName]=n}}assert(e,r,n){if(!e){let i=Bc(n);throw(i=="number"||i=="boolean")&&(i=n.toString()),new Error(`Cannot parse JSON ${i} for ${this.info.typeName}#${r}`)}}read(e,r,n){this.prepare();const i=[];for(const[s,o]of Object.entries(e)){const a=this.fMap[s];if(!a){if(!n.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${s}`);continue}const d=a.localName;let h;if(a.oneof){if(o===null&&(a.kind!=="enum"||a.T()[0]!=="google.protobuf.NullValue"))continue;if(i.includes(a.oneof))throw new Error(`Multiple members of the oneof group "${a.oneof}" of ${this.info.typeName} are present in JSON.`);i.push(a.oneof),h=r[a.oneof]={oneofKind:d}}else h=r;if(a.kind=="map"){if(o===null)continue;this.assert(vv(o),a.name,o);const p=h[d];for(const[f,g]of Object.entries(o)){this.assert(g!==null,a.name+" map value",null);let E;switch(a.V.kind){case"message":E=a.V.T().internalJsonRead(g,n);break;case"enum":if(E=this.enum(a.V.T(),g,a.name,n.ignoreUnknownFields),E===!1)continue;break;case"scalar":E=this.scalar(g,a.V.T,a.V.L,a.name);break}this.assert(E!==void 0,a.name+" map value",g);let v=f;a.K==M.BOOL&&(v=v=="true"?!0:v=="false"?!1:v),v=this.scalar(v,a.K,sr.STRING,a.name).toString(),p[v]=E}}else if(a.repeat){if(o===null)continue;this.assert(Array.isArray(o),a.name,o);const p=h[d];for(const f of o){this.assert(f!==null,a.name,null);let g;switch(a.kind){case"message":g=a.T().internalJsonRead(f,n);break;case"enum":if(g=this.enum(a.T(),f,a.name,n.ignoreUnknownFields),g===!1)continue;break;case"scalar":g=this.scalar(f,a.T,a.L,a.name);break}this.assert(g!==void 0,a.name,o),p.push(g)}}else switch(a.kind){case"message":if(o===null&&a.T().typeName!="google.protobuf.Value"){this.assert(a.oneof===void 0,a.name+" (oneof member)",null);continue}h[d]=a.T().internalJsonRead(o,n,h[d]);break;case"enum":let p=this.enum(a.T(),o,a.name,n.ignoreUnknownFields);if(p===!1)continue;h[d]=p;break;case"scalar":h[d]=this.scalar(o,a.T,a.L,a.name);break}}}enum(e,r,n,i){if(e[0]=="google.protobuf.NullValue"&&fe(r===null||r==="NULL_VALUE",`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} only accepts null.`),r===null)return 0;switch(typeof r){case"number":return fe(Number.isInteger(r),`Unable to parse field ${this.info.typeName}#${n}, enum can only be integral number, got ${r}.`),r;case"string":let s=r;e[2]&&r.substring(0,e[2].length)===e[2]&&(s=r.substring(e[2].length));let o=e[1][s];return typeof o=="undefined"&&i?!1:(fe(typeof o=="number",`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} has no value for "${r}".`),o)}fe(!1,`Unable to parse field ${this.info.typeName}#${n}, cannot parse enum value from ${typeof r}".`)}scalar(e,r,n,i){let s;try{switch(r){case M.DOUBLE:case M.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===""){s="empty string";break}if(typeof e=="string"&&e.trim().length!==e.length){s="extra whitespace";break}if(typeof e!="string"&&typeof e!="number")break;let o=Number(e);if(Number.isNaN(o)){s="not a number";break}if(!Number.isFinite(o)){s="too large or small";break}return r==M.FLOAT&&Wc(o),o;case M.INT32:case M.FIXED32:case M.SFIXED32:case M.SINT32:case M.UINT32:if(e===null)return 0;let a;if(typeof e=="number"?a=e:e===""?s="empty string":typeof e=="string"&&(e.trim().length!==e.length?s="extra whitespace":a=Number(e)),a===void 0)break;return r==M.UINT32?ko(a):cs(a),a;case M.INT64:case M.SFIXED64:case M.SINT64:if(e===null)return Gt(_e.ZERO,n);if(typeof e!="number"&&typeof e!="string")break;return Gt(_e.from(e),n);case M.FIXED64:case M.UINT64:if(e===null)return Gt(ct.ZERO,n);if(typeof e!="number"&&typeof e!="string")break;return Gt(ct.from(e),n);case M.BOOL:if(e===null)return!1;if(typeof e!="boolean")break;return e;case M.STRING:if(e===null)return"";if(typeof e!="string"){s="extra whitespace";break}try{encodeURIComponent(e)}catch(d){d="invalid UTF8";break}return e;case M.BYTES:if(e===null||e==="")return new Uint8Array(0);if(typeof e!="string")break;return yv(e)}}catch(o){s=o.message}this.assert(!1,i+(s?" - "+s:""),e)}}class Uv{constructor(e){var r;this.fields=(r=e.fields)!==null&&r!==void 0?r:[]}write(e,r){const n={},i=e;for(const s of this.fields){if(!s.oneof){let h=this.field(s,i[s.localName],r);h!==void 0&&(n[r.useProtoFieldName?s.name:s.jsonName]=h);continue}const o=i[s.oneof];if(o.oneofKind!==s.localName)continue;const a=s.kind=="scalar"||s.kind=="enum"?Object.assign(Object.assign({},r),{emitDefaultValues:!0}):r;let d=this.field(s,o[s.localName],a);fe(d!==void 0),n[r.useProtoFieldName?s.name:s.jsonName]=d}return n}field(e,r,n){let i;if(e.kind=="map"){fe(typeof r=="object"&&r!==null);const s={};switch(e.V.kind){case"scalar":for(const[d,h]of Object.entries(r)){const p=this.scalar(e.V.T,h,e.name,!1,!0);fe(p!==void 0),s[d.toString()]=p}break;case"message":const o=e.V.T();for(const[d,h]of Object.entries(r)){const p=this.message(o,h,e.name,n);fe(p!==void 0),s[d.toString()]=p}break;case"enum":const a=e.V.T();for(const[d,h]of Object.entries(r)){fe(h===void 0||typeof h=="number");const p=this.enum(a,h,e.name,!1,!0,n.enumAsInteger);fe(p!==void 0),s[d.toString()]=p}break}(n.emitDefaultValues||Object.keys(s).length>0)&&(i=s)}else if(e.repeat){fe(Array.isArray(r));const s=[];switch(e.kind){case"scalar":for(let d=0;d<r.length;d++){const h=this.scalar(e.T,r[d],e.name,e.opt,!0);fe(h!==void 0),s.push(h)}break;case"enum":const o=e.T();for(let d=0;d<r.length;d++){fe(r[d]===void 0||typeof r[d]=="number");const h=this.enum(o,r[d],e.name,e.opt,!0,n.enumAsInteger);fe(h!==void 0),s.push(h)}break;case"message":const a=e.T();for(let d=0;d<r.length;d++){const h=this.message(a,r[d],e.name,n);fe(h!==void 0),s.push(h)}break}(n.emitDefaultValues||s.length>0||n.emitDefaultValues)&&(i=s)}else switch(e.kind){case"scalar":i=this.scalar(e.T,r,e.name,e.opt,n.emitDefaultValues);break;case"enum":i=this.enum(e.T(),r,e.name,e.opt,n.emitDefaultValues,n.enumAsInteger);break;case"message":i=this.message(e.T(),r,e.name,n);break}return i}enum(e,r,n,i,s,o){if(e[0]=="google.protobuf.NullValue")return!s&&!i?void 0:null;if(r===void 0){fe(i);return}if(!(r===0&&!s&&!i))return fe(typeof r=="number"),fe(Number.isInteger(r)),o||!e[1].hasOwnProperty(r)?r:e[2]?e[2]+e[1][r]:e[1][r]}message(e,r,n,i){return r===void 0?i.emitDefaultValues?null:void 0:e.internalJsonWrite(r,i)}scalar(e,r,n,i,s){if(r===void 0){fe(i);return}const o=s||i;switch(e){case M.INT32:case M.SFIXED32:case M.SINT32:return r===0?o?0:void 0:(cs(r),r);case M.FIXED32:case M.UINT32:return r===0?o?0:void 0:(ko(r),r);case M.FLOAT:Wc(r);case M.DOUBLE:return r===0?o?0:void 0:(fe(typeof r=="number"),Number.isNaN(r)?"NaN":r===Number.POSITIVE_INFINITY?"Infinity":r===Number.NEGATIVE_INFINITY?"-Infinity":r);case M.STRING:return r===""?o?"":void 0:(fe(typeof r=="string"),r);case M.BOOL:return r===!1?o?!1:void 0:(fe(typeof r=="boolean"),r);case M.UINT64:case M.FIXED64:fe(typeof r=="number"||typeof r=="string"||typeof r=="bigint");let a=ct.from(r);return a.isZero()&&!o?void 0:a.toString();case M.INT64:case M.SFIXED64:case M.SINT64:fe(typeof r=="number"||typeof r=="string"||typeof r=="bigint");let d=_e.from(r);return d.isZero()&&!o?void 0:d.toString();case M.BYTES:return fe(r instanceof Uint8Array),r.byteLength?Ev(r):o?"":void 0}}}function $c(t,e=sr.STRING){switch(t){case M.BOOL:return!1;case M.UINT64:case M.FIXED64:return Gt(ct.ZERO,e);case M.INT64:case M.SFIXED64:case M.SINT64:return Gt(_e.ZERO,e);case M.DOUBLE:case M.FLOAT:return 0;case M.BYTES:return new Uint8Array(0);case M.STRING:return"";default:return 0}}class Vv{constructor(e){this.info=e}prepare(){var e;if(!this.fieldNoToField){const r=(e=this.info.fields)!==null&&e!==void 0?e:[];this.fieldNoToField=new Map(r.map(n=>[n.no,n]))}}read(e,r,n,i){this.prepare();const s=i===void 0?e.len:e.pos+i;for(;e.pos<s;){const[o,a]=e.tag(),d=this.fieldNoToField.get(o);if(!d){let g=n.readUnknownField;if(g=="throw")throw new Error(`Unknown field ${o} (wire type ${a}) for ${this.info.typeName}`);let E=e.skip(a);g!==!1&&(g===!0?yo.onRead:g)(this.info.typeName,r,o,a,E);continue}let h=r,p=d.repeat,f=d.localName;switch(d.oneof&&(h=h[d.oneof],h.oneofKind!==f&&(h=r[d.oneof]={oneofKind:f})),d.kind){case"scalar":case"enum":let g=d.kind=="enum"?M.INT32:d.T,E=d.kind=="scalar"?d.L:void 0;if(p){let A=h[f];if(a==Be.LengthDelimited&&g!=M.STRING&&g!=M.BYTES){let L=e.uint32()+e.pos;for(;e.pos<L;)A.push(this.scalar(e,g,E))}else A.push(this.scalar(e,g,E))}else h[f]=this.scalar(e,g,E);break;case"message":if(p){let A=h[f],L=d.T().internalBinaryRead(e,e.uint32(),n);A.push(L)}else h[f]=d.T().internalBinaryRead(e,e.uint32(),n,h[f]);break;case"map":let[v,R]=this.mapEntry(d,e,n);h[f][v]=R;break}}}mapEntry(e,r,n){let i=r.uint32(),s=r.pos+i,o,a;for(;r.pos<s;){let[d,h]=r.tag();switch(d){case 1:e.K==M.BOOL?o=r.bool().toString():o=this.scalar(r,e.K,sr.STRING);break;case 2:switch(e.V.kind){case"scalar":a=this.scalar(r,e.V.T,e.V.L);break;case"enum":a=r.int32();break;case"message":a=e.V.T().internalBinaryRead(r,r.uint32(),n);break}break;default:throw new Error(`Unknown field ${d} (wire type ${h}) in map entry for ${this.info.typeName}#${e.name}`)}}if(o===void 0){let d=$c(e.K);o=e.K==M.BOOL?d.toString():d}if(a===void 0)switch(e.V.kind){case"scalar":a=$c(e.V.T,e.V.L);break;case"enum":a=0;break;case"message":a=e.V.T().create();break}return[o,a]}scalar(e,r,n){switch(r){case M.INT32:return e.int32();case M.STRING:return e.string();case M.BOOL:return e.bool();case M.DOUBLE:return e.double();case M.FLOAT:return e.float();case M.INT64:return Gt(e.int64(),n);case M.UINT64:return Gt(e.uint64(),n);case M.FIXED64:return Gt(e.fixed64(),n);case M.FIXED32:return e.fixed32();case M.BYTES:return e.bytes();case M.UINT32:return e.uint32();case M.SFIXED32:return e.sfixed32();case M.SFIXED64:return Gt(e.sfixed64(),n);case M.SINT32:return e.sint32();case M.SINT64:return Gt(e.sint64(),n)}}}class Bv{constructor(e){this.info=e}prepare(){if(!this.fields){const e=this.info.fields?this.info.fields.concat():[];this.fields=e.sort((r,n)=>r.no-n.no)}}write(e,r,n){this.prepare();for(const s of this.fields){let o,a,d=s.repeat,h=s.localName;if(s.oneof){const p=e[s.oneof];if(p.oneofKind!==h)continue;o=p[h],a=!0}else o=e[h],a=!1;switch(s.kind){case"scalar":case"enum":let p=s.kind=="enum"?M.INT32:s.T;if(d)if(fe(Array.isArray(o)),d==_o.PACKED)this.packed(r,p,s.no,o);else for(const f of o)this.scalar(r,p,s.no,f,!0);else o===void 0?fe(s.opt):this.scalar(r,p,s.no,o,a||s.opt);break;case"message":if(d){fe(Array.isArray(o));for(const f of o)this.message(r,n,s.T(),s.no,f)}else this.message(r,n,s.T(),s.no,o);break;case"map":fe(typeof o=="object"&&o!==null);for(const[f,g]of Object.entries(o))this.mapEntry(r,n,s,f,g);break}}let i=n.writeUnknownFields;i!==!1&&(i===!0?yo.onWrite:i)(this.info.typeName,e,r)}mapEntry(e,r,n,i,s){e.tag(n.no,Be.LengthDelimited),e.fork();let o=i;switch(n.K){case M.INT32:case M.FIXED32:case M.UINT32:case M.SFIXED32:case M.SINT32:o=Number.parseInt(i);break;case M.BOOL:fe(i=="true"||i=="false"),o=i=="true";break}switch(this.scalar(e,n.K,1,o,!0),n.V.kind){case"scalar":this.scalar(e,n.V.T,2,s,!0);break;case"enum":this.scalar(e,M.INT32,2,s,!0);break;case"message":this.message(e,r,n.V.T(),2,s);break}e.join()}message(e,r,n,i,s){s!==void 0&&(n.internalBinaryWrite(s,e.tag(i,Be.LengthDelimited).fork(),r),e.join())}scalar(e,r,n,i,s){let[o,a,d]=this.scalarInfo(r,i);(!d||s)&&(e.tag(n,o),e[a](i))}packed(e,r,n,i){if(!i.length)return;fe(r!==M.BYTES&&r!==M.STRING),e.tag(n,Be.LengthDelimited),e.fork();let[,s]=this.scalarInfo(r);for(let o=0;o<i.length;o++)e[s](i[o]);e.join()}scalarInfo(e,r){let n=Be.Varint,i,s=r===void 0,o=r===0;switch(e){case M.INT32:i="int32";break;case M.STRING:o=s||!r.length,n=Be.LengthDelimited,i="string";break;case M.BOOL:o=r===!1,i="bool";break;case M.UINT32:i="uint32";break;case M.DOUBLE:n=Be.Bit64,i="double";break;case M.FLOAT:n=Be.Bit32,i="float";break;case M.INT64:o=s||_e.from(r).isZero(),i="int64";break;case M.UINT64:o=s||ct.from(r).isZero(),i="uint64";break;case M.FIXED64:o=s||ct.from(r).isZero(),n=Be.Bit64,i="fixed64";break;case M.BYTES:o=s||!r.byteLength,n=Be.LengthDelimited,i="bytes";break;case M.FIXED32:n=Be.Bit32,i="fixed32";break;case M.SFIXED32:n=Be.Bit32,i="sfixed32";break;case M.SFIXED64:o=s||_e.from(r).isZero(),n=Be.Bit64,i="sfixed64";break;case M.SINT32:i="sint32";break;case M.SINT64:o=s||_e.from(r).isZero(),i="sint64";break}return[n,i,s||o]}}function jv(t){const e=t.messagePrototype?Object.create(t.messagePrototype):Object.defineProperty({},Su,{value:t});for(let r of t.fields){let n=r.localName;if(!r.opt)if(r.oneof)e[r.oneof]={oneofKind:void 0};else if(r.repeat)e[n]=[];else switch(r.kind){case"scalar":e[n]=$c(r.T,r.L);break;case"enum":e[n]=0;break;case"map":e[n]={};break}}return e}function Gc(t,e,r){let n,i=r,s;for(let o of t.fields){let a=o.localName;if(o.oneof){const d=i[o.oneof];if((d==null?void 0:d.oneofKind)==null)continue;if(n=d[a],s=e[o.oneof],s.oneofKind=d.oneofKind,n==null){delete s[a];continue}}else if(n=i[a],s=e,n==null)continue;switch(o.repeat&&(s[a].length=n.length),o.kind){case"scalar":case"enum":if(o.repeat)for(let h=0;h<n.length;h++)s[a][h]=n[h];else s[a]=n;break;case"message":let d=o.T();if(o.repeat)for(let h=0;h<n.length;h++)s[a][h]=d.create(n[h]);else s[a]===void 0?s[a]=d.create(n):d.mergePartial(s[a],n);break;case"map":switch(o.V.kind){case"scalar":case"enum":Object.assign(s[a],n);break;case"message":let h=o.V.T();for(let p of Object.keys(n))s[a][p]=h.create(n[p]);break}break}}}function Hv(t,e,r){if(e===r)return!0;if(!e||!r)return!1;for(let n of t.fields){let i=n.localName,s=n.oneof?e[n.oneof][i]:e[i],o=n.oneof?r[n.oneof][i]:r[i];switch(n.kind){case"enum":case"scalar":let a=n.kind=="enum"?M.INT32:n.T;if(!(n.repeat?_u(a,s,o):ku(a,s,o)))return!1;break;case"map":if(!(n.V.kind=="message"?bu(n.V.T(),bo(s),bo(o)):_u(n.V.kind=="enum"?M.INT32:n.V.T,bo(s),bo(o))))return!1;break;case"message":let d=n.T();if(!(n.repeat?bu(d,s,o):d.equals(s,o)))return!1;break}}return!0}const bo=Object.values;function ku(t,e,r){if(e===r)return!0;if(t!==M.BYTES)return!1;let n=e,i=r;if(n.length!==i.length)return!1;for(let s=0;s<n.length;s++)if(n[s]!=i[s])return!1;return!0}function _u(t,e,r){if(e.length!==r.length)return!1;for(let n=0;n<e.length;n++)if(!ku(t,e[n],r[n]))return!1;return!0}function bu(t,e,r){if(e.length!==r.length)return!1;for(let n=0;n<e.length;n++)if(!t.equals(e[n],r[n]))return!1;return!0}const Wv=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({}));class k{constructor(e,r,n){this.defaultCheckDepth=16,this.typeName=e,this.fields=r.map(Nv),this.options=n!=null?n:{},this.messagePrototype=Object.create(null,Object.assign(Object.assign({},Wv),{[Su]:{value:this}})),this.refTypeCheck=new xv(this),this.refJsonReader=new Fv(this),this.refJsonWriter=new Uv(this),this.refBinReader=new Vv(this),this.refBinWriter=new Bv(this)}create(e){let r=jv(this);return e!==void 0&&Gc(this,r,e),r}clone(e){let r=this.create();return Gc(this,r,e),r}equals(e,r){return Hv(this,e,r)}is(e,r=this.defaultCheckDepth){return this.refTypeCheck.is(e,r,!1)}isAssignable(e,r=this.defaultCheckDepth){return this.refTypeCheck.is(e,r,!0)}mergePartial(e,r){Gc(this,e,r)}fromBinary(e,r){let n=_v(r);return this.internalBinaryRead(n.readerFactory(e),e.byteLength,n)}fromJson(e,r){return this.internalJsonRead(e,Dv(r))}fromJsonString(e,r){let n=JSON.parse(e);return this.fromJson(n,r)}toJson(e,r){return this.internalJsonWrite(e,Ov(r))}toJsonString(e,r){var n;let i=this.toJson(e,r);return JSON.stringify(i,null,(n=r==null?void 0:r.prettySpaces)!==null&&n!==void 0?n:0)}toBinary(e,r){let n=Av(r);return this.internalBinaryWrite(e,n.writerFactory(),n).finish()}internalJsonRead(e,r,n){if(e!==null&&typeof e=="object"&&!Array.isArray(e)){let i=n!=null?n:this.create();return this.refJsonReader.read(e,i,r),i}throw new Error(`Unable to parse message ${this.typeName} from JSON ${Bc(e)}.`)}internalJsonWrite(e,r){return this.refJsonWriter.write(e,r)}internalBinaryWrite(e,r,n){return this.refBinWriter.write(e,r,n),r}internalBinaryRead(e,r,n,i){let s=i!=null?i:this.create();return this.refBinReader.read(e,s,n,r),s}}const $v=t=>(e,r)=>(t.set(e,r),r),wu=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,Cu=536870912,Iu=Cu*2,Gv=(t,e)=>r=>{const n=e.get(r);let i=n===void 0?r.size:n<Iu?n+1:0;if(!r.has(i))return t(r,i);if(r.size<Cu){for(;r.has(i);)i=Math.floor(Math.random()*Iu);return t(r,i)}if(r.size>wu)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*wu);return t(r,i)},Ru=new WeakMap,Jv=$v(Ru),wo=Gv(Jv,Ru),qv=t=>t.method!==void 0&&t.method==="call",Kv=t=>t.error===null&&typeof t.id=="number",Co=((t,e)=>{let r=null;return()=>{if(r!==null)return r;const n=new Blob([e],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(n);return r=t(i),setTimeout(()=>URL.revokeObjectURL(i)),r}})(t=>{const e=new Map([[0,()=>{}]]),r=new Map([[0,()=>{}]]),n=new Map,i=new Worker(t);return i.addEventListener("message",({data:h})=>{if(qv(h)){const{params:{timerId:p,timerType:f}}=h;if(f==="interval"){const g=e.get(p);if(typeof g=="number"){const E=n.get(g);if(E===void 0||E.timerId!==p||E.timerType!==f)throw new Error("The timer is in an undefined state.")}else if(typeof g!="undefined")g();else throw new Error("The timer is in an undefined state.")}else if(f==="timeout"){const g=r.get(p);if(typeof g=="number"){const E=n.get(g);if(E===void 0||E.timerId!==p||E.timerType!==f)throw new Error("The timer is in an undefined state.")}else if(typeof g!="undefined")g(),r.delete(p);else throw new Error("The timer is in an undefined state.")}}else if(Kv(h)){const{id:p}=h,f=n.get(p);if(f===void 0)throw new Error("The timer is in an undefined state.");const{timerId:g,timerType:E}=f;n.delete(p),E==="interval"?e.delete(g):r.delete(g)}else{const{error:{message:p}}=h;throw new Error(p)}}),{clearInterval:h=>{const p=wo(n);n.set(p,{timerId:h,timerType:"interval"}),e.set(h,p),i.postMessage({id:p,method:"clear",params:{timerId:h,timerType:"interval"}})},clearTimeout:h=>{const p=wo(n);n.set(p,{timerId:h,timerType:"timeout"}),r.set(h,p),i.postMessage({id:p,method:"clear",params:{timerId:h,timerType:"timeout"}})},setInterval:(h,p=0)=>{const f=wo(e);return e.set(f,()=>{h(),typeof e.get(f)=="function"&&i.postMessage({id:null,method:"set",params:{delay:p,now:performance.now(),timerId:f,timerType:"interval"}})}),i.postMessage({id:null,method:"set",params:{delay:p,now:performance.now(),timerId:f,timerType:"interval"}}),f},setTimeout:(h,p=0)=>{const f=wo(r);return r.set(f,h),i.postMessage({id:null,method:"set",params:{delay:p,now:performance.now(),timerId:f,timerType:"timeout"}}),f}}},`(()=>{"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})}}))})();`),Pu=t=>Co().clearInterval(t),zv=t=>Co().clearTimeout(t),Au=(t,e)=>Co().setInterval(t,e);var Yv=Object.freeze(Object.defineProperty({__proto__:null,clearInterval:Pu,clearTimeout:zv,setInterval:Au,setTimeout:(t,e)=>Co().setTimeout(t,e)},Symbol.toStringTag,{value:"Module"})),Mu={},Jc={exports:{}},Du=Jc.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(Du).forEach(function(t){var e=Du[t];e.forEach(function(r){r.reg||(r.reg=/(.*)/),r.format||(r.format="%s")})}),function(t){var e=function(a){return String(Number(a))===a?Number(a):a},r=function(a,d,h,p){if(p&&!h)d[p]=e(a[1]);else for(var f=0;f<h.length;f+=1)a[f+1]!=null&&(d[h[f]]=e(a[f+1]))},n=function(a,d,h){var p=a.name&&a.names;a.push&&!d[a.push]?d[a.push]=[]:p&&!d[a.name]&&(d[a.name]={});var f=a.push?{}:p?d[a.name]:d;r(h.match(a.reg),f,a.names,a.name),a.push&&d[a.push].push(f)},i=Jc.exports,s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(a){var d={},h=[],p=d;return a.split(/(\r\n|\r|\n)/).filter(s).forEach(function(f){var g=f[0],E=f.slice(2);g==="m"&&(h.push({rtp:[],fmtp:[]}),p=h[h.length-1]);for(var v=0;v<(i[g]||[]).length;v+=1){var R=i[g][v];if(R.reg.test(E))return n(R,p,E)}}),d.media=h,d};var o=function(a,d){var h=d.split(/=(.+)/,2);return h.length===2?a[h[0]]=e(h[1]):h.length===1&&d.length>1&&(a[h[0]]=void 0),a};t.parseParams=function(a){return a.split(/;\s?/).reduce(o,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(a){return a.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(a){for(var d=[],h=a.split(" ").map(e),p=0;p<h.length;p+=3)d.push({component:h[p],ip:h[p+1],port:h[p+2]});return d},t.parseImageAttributes=function(a){return a.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(o,{})})},t.parseSimulcastStreamList=function(a){return a.split(";").map(function(d){return d.split(",").map(function(h){var p,f=!1;return h[0]!=="~"?p=e(h):(p=e(h.substring(1,h.length)),f=!0),{scid:p,paused:f}})})}}(Mu);var qc=Jc.exports,Qv=/%[sdv%]/g,Xv=function(t){var e=1,r=arguments,n=r.length;return t.replace(Qv,function(i){if(e>=n)return i;var s=r[e];switch(e+=1,i){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},ds=function(t,e,r){var n=e.format instanceof Function?e.format(e.push?r:r[e.name]):e.format,i=[t+"="+n];if(e.names)for(var s=0;s<e.names.length;s+=1){var o=e.names[s];e.name?i.push(r[e.name][o]):i.push(r[e.names[s]])}else i.push(r[e.name]);return Xv.apply(null,i)},Zv=["v","o","s","i","u","e","p","c","b","t","r","z","a"],ey=["i","c","b","a"],ty=function(t,e){e=e||{},t.version==null&&(t.version=0),t.name==null&&(t.name=" "),t.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var r=e.outerOrder||Zv,n=e.innerOrder||ey,i=[];return r.forEach(function(s){qc[s].forEach(function(o){o.name in t&&t[o.name]!=null?i.push(ds(s,o,t)):o.push in t&&t[o.push]!=null&&t[o.push].forEach(function(a){i.push(ds(s,o,a))})})}),t.media.forEach(function(s){i.push(ds("m",qc.m[0],s)),n.forEach(function(o){qc[o].forEach(function(a){a.name in s&&s[a.name]!=null?i.push(ds(o,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(d){i.push(ds(o,a,d))})})})}),i.join(`\r
6
+ */class Xu{static getParser(e,r=!1){if(typeof e!="string")throw new Error("UserAgent should be a string");return new Qu(e,r)}static parse(e){return new Qu(e).getResult()}static get BROWSER_MAP(){return Yu}static get ENGINE_MAP(){return rn}static get OS_MAP(){return Et}static get PLATFORMS_MAP(){return We}}function _d(t){let e=typeof t;if(e=="object"){if(Array.isArray(t))return"array";if(t===null)return"null"}return e}function ly(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}let Cr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),to=[];for(let t=0;t<Cr.length;t++)to[Cr[t].charCodeAt(0)]=t;to["-".charCodeAt(0)]=Cr.indexOf("+"),to["_".charCodeAt(0)]=Cr.indexOf("/");function uy(t){let e=t.length*3/4;t[t.length-2]=="="?e-=2:t[t.length-1]=="="&&(e-=1);let r=new Uint8Array(e),n=0,i=0,s,a=0;for(let o=0;o<t.length;o++){if(s=to[t.charCodeAt(o)],s===void 0)switch(t[o]){case"=":i=0;case`
7
+ `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(i){case 0:a=s,i=1;break;case 1:r[n++]=a<<2|(s&48)>>4,a=s,i=2;break;case 2:r[n++]=(a&15)<<4|(s&60)>>2,a=s,i=3;break;case 3:r[n++]=(a&3)<<6|s,i=0;break}}if(i==1)throw Error("invalid base64 string.");return r.subarray(0,n)}function hy(t){let e="",r=0,n,i=0;for(let s=0;s<t.length;s++)switch(n=t[s],r){case 0:e+=Cr[n>>2],i=(n&3)<<4,r=1;break;case 1:e+=Cr[i|n>>4],i=(n&15)<<2,r=2;break;case 2:e+=Cr[i|n>>6],e+=Cr[n&63],r=0;break}return r&&(e+=Cr[i],e+="=",r==1&&(e+="=")),e}var ro;(function(t){t.symbol=Symbol.for("protobuf-ts/unknown"),t.onRead=(r,n,i,s,a)=>{(e(n)?n[t.symbol]:n[t.symbol]=[]).push({no:i,wireType:s,data:a})},t.onWrite=(r,n,i)=>{for(let{no:s,wireType:a,data:o}of t.list(n))i.tag(s,a).raw(o)},t.list=(r,n)=>{if(e(r)){let i=r[t.symbol];return n?i.filter(s=>s.no==n):i}return[]},t.last=(r,n)=>t.list(r,n).slice(-1)[0];const e=r=>r&&Array.isArray(r[t.symbol])})(ro||(ro={}));var $e;(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"})($e||($e={}));function py(){let t=0,e=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(t|=(i&127)<<n,(i&128)==0)return this.assertBounds(),[t,e]}let r=this.buf[this.pos++];if(t|=(r&15)<<28,e=(r&112)>>4,(r&128)==0)return this.assertBounds(),[t,e];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(e|=(i&127)<<n,(i&128)==0)return this.assertBounds(),[t,e]}throw new Error("invalid varint")}function bd(t,e,r){for(let s=0;s<28;s=s+7){const a=t>>>s,o=!(a>>>7==0&&e==0),d=(o?a|128:a)&255;if(r.push(d),!o)return}const n=t>>>28&15|(e&7)<<4,i=e>>3!=0;if(r.push((i?n|128:n)&255),!!i){for(let s=3;s<31;s=s+7){const a=e>>>s,o=a>>>7!=0,d=(o?a|128:a)&255;if(r.push(d),!o)return}r.push(e>>>31&1)}}const no=(1<<16)*(1<<16);function Zu(t){let e=t[0]=="-";e&&(t=t.slice(1));const r=1e6;let n=0,i=0;function s(a,o){const d=Number(t.slice(a,o));i*=r,n=n*r+d,n>=no&&(i=i+(n/no|0),n=n%no)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),[e,n,i]}function wd(t,e){if(e>>>0<=2097151)return""+(no*e+(t>>>0));let r=t&16777215,n=(t>>>24|e<<8)>>>0&16777215,i=e>>16&65535,s=r+n*6777216+i*6710656,a=n+i*8147497,o=i*2,d=1e7;s>=d&&(a+=Math.floor(s/d),s%=d),a>=d&&(o+=Math.floor(a/d),a%=d);function h(p,m){let g=p?String(p):"";return m?"0000000".slice(g.length)+g:g}return h(o,0)+h(a,o)+h(s,1)}function eh(t,e){if(t>=0){for(;t>127;)e.push(t&127|128),t=t>>>7;e.push(t)}else{for(let r=0;r<9;r++)e.push(t&127|128),t=t>>7;e.push(1)}}function my(){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 r=5;(t&128)!==0&&r<10;r++)t=this.buf[this.pos++];if((t&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}let be;function fy(){const t=new DataView(new ArrayBuffer(8));be=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}fy();function th(t){if(!t)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const rh=/^-?[0-9]+$/,io=4294967296,so=2147483648;class nh{constructor(e,r){this.lo=e|0,this.hi=r|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let e=this.hi*io+(this.lo>>>0);if(!Number.isSafeInteger(e))throw new Error("cannot convert to safe number");return e}}class ft extends nh{static from(e){if(be)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=be.C(e);case"number":if(e===0)return this.ZERO;e=be.C(e);case"bigint":if(!e)return this.ZERO;if(e<be.UMIN)throw new Error("signed value for ulong");if(e>be.UMAX)throw new Error("ulong too large");return be.V.setBigUint64(0,e,!0),new ft(be.V.getInt32(0,!0),be.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!rh.test(e))throw new Error("string is no integer");let[r,n,i]=Zu(e);if(r)throw new Error("signed value for ulong");return new ft(n,i);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 ft(e,e/io)}throw new Error("unknown value "+typeof e)}toString(){return be?this.toBigInt().toString():wd(this.lo,this.hi)}toBigInt(){return th(be),be.V.setInt32(0,this.lo,!0),be.V.setInt32(4,this.hi,!0),be.V.getBigUint64(0,!0)}}ft.ZERO=new ft(0,0);class Ie extends nh{static from(e){if(be)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=be.C(e);case"number":if(e===0)return this.ZERO;e=be.C(e);case"bigint":if(!e)return this.ZERO;if(e<be.MIN)throw new Error("signed long too small");if(e>be.MAX)throw new Error("signed long too large");return be.V.setBigInt64(0,e,!0),new Ie(be.V.getInt32(0,!0),be.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!rh.test(e))throw new Error("string is no integer");let[r,n,i]=Zu(e);if(r){if(i>so||i==so&&n!=0)throw new Error("signed long too small")}else if(i>=so)throw new Error("signed long too large");let s=new Ie(n,i);return r?s.negate():s;case"number":if(e==0)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");return e>0?new Ie(e,e/io):new Ie(-e,-e/io).negate()}throw new Error("unknown value "+typeof e)}isNegative(){return(this.hi&so)!==0}negate(){let e=~this.hi,r=this.lo;return r?r=~r+1:e+=1,new Ie(r,e)}toString(){if(be)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return"-"+wd(e.lo,e.hi)}return wd(this.lo,this.hi)}toBigInt(){return th(be),be.V.setInt32(0,this.lo,!0),be.V.setInt32(4,this.hi,!0),be.V.getBigInt64(0,!0)}}Ie.ZERO=new Ie(0,0);const ih={readUnknownField:!0,readerFactory:t=>new vy(t)};function gy(t){return t?Object.assign(Object.assign({},ih),t):ih}class vy{constructor(e,r){this.varint64=py,this.uint32=my,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=r!=null?r:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let e=this.uint32(),r=e>>>3,n=e&7;if(r<=0||n<0||n>5)throw new Error("illegal tag: field no "+r+" wire type "+n);return[r,n]}skip(e){let r=this.pos;switch(e){case $e.Varint:for(;this.buf[this.pos++]&128;);break;case $e.Bit64:this.pos+=4;case $e.Bit32:this.pos+=4;break;case $e.LengthDelimited:let n=this.uint32();this.pos+=n;break;case $e.StartGroup:let i;for(;(i=this.tag()[1])!==$e.EndGroup;)this.skip(i);break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(r,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 Ie(...this.varint64())}uint64(){return new ft(...this.varint64())}sint64(){let[e,r]=this.varint64(),n=-(e&1);return e=(e>>>1|(r&1)<<31)^n,r=r>>>1^n,new Ie(e,r)}bool(){let[e,r]=this.varint64();return e!==0||r!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new ft(this.sfixed32(),this.sfixed32())}sfixed64(){return new Ie(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(),r=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(r,r+e)}string(){return this.textDecoder.decode(this.bytes())}}function ye(t,e){if(!t)throw new Error(e)}const yy=34028234663852886e22,Sy=-34028234663852886e22,Ey=4294967295,Ty=2147483647,ky=-2147483648;function Ss(t){if(typeof t!="number")throw new Error("invalid int 32: "+typeof t);if(!Number.isInteger(t)||t>Ty||t<ky)throw new Error("invalid int 32: "+t)}function ao(t){if(typeof t!="number")throw new Error("invalid uint 32: "+typeof t);if(!Number.isInteger(t)||t>Ey||t<0)throw new Error("invalid uint 32: "+t)}function Id(t){if(typeof t!="number")throw new Error("invalid float 32: "+typeof t);if(!!Number.isFinite(t)&&(t>yy||t<Sy))throw new Error("invalid float 32: "+t)}const sh={writeUnknownFields:!0,writerFactory:()=>new by};function _y(t){return t?Object.assign(Object.assign({},sh),t):sh}class by{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 i=0;i<this.chunks.length;i++)e+=this.chunks[i].length;let r=new Uint8Array(e),n=0;for(let i=0;i<this.chunks.length;i++)r.set(this.chunks[i],n),n+=this.chunks[i].length;return this.chunks=[],r}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),r=this.stack.pop();if(!r)throw new Error("invalid state, fork stack empty");return this.chunks=r.chunks,this.buf=r.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,r){return this.uint32((e<<3|r)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(ao(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Ss(e),eh(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 r=this.textEncoder.encode(e);return this.uint32(r.byteLength),this.raw(r)}float(e){Id(e);let r=new Uint8Array(4);return new DataView(r.buffer).setFloat32(0,e,!0),this.raw(r)}double(e){let r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,e,!0),this.raw(r)}fixed32(e){ao(e);let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,e,!0),this.raw(r)}sfixed32(e){Ss(e);let r=new Uint8Array(4);return new DataView(r.buffer).setInt32(0,e,!0),this.raw(r)}sint32(e){return Ss(e),e=(e<<1^e>>31)>>>0,eh(e,this.buf),this}sfixed64(e){let r=new Uint8Array(8),n=new DataView(r.buffer),i=Ie.from(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(r)}fixed64(e){let r=new Uint8Array(8),n=new DataView(r.buffer),i=ft.from(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(r)}int64(e){let r=Ie.from(e);return bd(r.lo,r.hi,this.buf),this}sint64(e){let r=Ie.from(e),n=r.hi>>31,i=r.lo<<1^n,s=(r.hi<<1|r.lo>>>31)^n;return bd(i,s,this.buf),this}uint64(e){let r=ft.from(e);return bd(r.lo,r.hi,this.buf),this}}const ah={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},oh={ignoreUnknownFields:!1};function wy(t){return t?Object.assign(Object.assign({},oh),t):oh}function Iy(t){return t?Object.assign(Object.assign({},ah),t):ah}const ch=Symbol.for("protobuf-ts/message-type");function dh(t){let e=!1;const r=[];for(let n=0;n<t.length;n++){let i=t.charAt(n);i=="_"?e=!0:/\d/.test(i)?(r.push(i),e=!0):e?(r.push(i.toUpperCase()),e=!1):n==0?r.push(i.toLowerCase()):r.push(i)}return r.join("")}var L;(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"})(L||(L={}));var yr;(function(t){t[t.BIGINT=0]="BIGINT",t[t.STRING=1]="STRING",t[t.NUMBER=2]="NUMBER"})(yr||(yr={}));var oo;(function(t){t[t.NO=0]="NO",t[t.PACKED=1]="PACKED",t[t.UNPACKED=2]="UNPACKED"})(oo||(oo={}));function Cy(t){var e,r,n,i;return t.localName=(e=t.localName)!==null&&e!==void 0?e:dh(t.name),t.jsonName=(r=t.jsonName)!==null&&r!==void 0?r:dh(t.name),t.repeat=(n=t.repeat)!==null&&n!==void 0?n:oo.NO,t.opt=(i=t.opt)!==null&&i!==void 0?i:t.repeat||t.oneof?!1:t.kind=="message",t}function Py(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 Ry{constructor(e){var r;this.fields=(r=e.fields)!==null&&r!==void 0?r:[]}prepare(){if(this.data)return;const e=[],r=[],n=[];for(let i of this.fields)if(i.oneof)n.includes(i.oneof)||(n.push(i.oneof),e.push(i.oneof),r.push(i.oneof));else switch(r.push(i.localName),i.kind){case"scalar":case"enum":(!i.opt||i.repeat)&&e.push(i.localName);break;case"message":i.repeat&&e.push(i.localName);break;case"map":e.push(i.localName);break}this.data={req:e,known:r,oneofs:Object.values(n)}}is(e,r,n=!1){if(r<0)return!0;if(e==null||typeof e!="object")return!1;this.prepare();let i=Object.keys(e),s=this.data;if(i.length<s.req.length||s.req.some(a=>!i.includes(a))||!n&&i.some(a=>!s.known.includes(a)))return!1;if(r<1)return!0;for(const a of s.oneofs){const o=e[a];if(!Py(o))return!1;if(o.oneofKind===void 0)continue;const d=this.fields.find(h=>h.localName===o.oneofKind);if(!d||!this.field(o[o.oneofKind],d,n,r))return!1}for(const a of this.fields)if(a.oneof===void 0&&!this.field(e[a.localName],a,n,r))return!1;return!0}field(e,r,n,i){let s=r.repeat;switch(r.kind){case"scalar":return e===void 0?r.opt:s?this.scalars(e,r.T,i,r.L):this.scalar(e,r.T,r.L);case"enum":return e===void 0?r.opt:s?this.scalars(e,L.INT32,i):this.scalar(e,L.INT32);case"message":return e===void 0?!0:s?this.messages(e,r.T(),n,i):this.message(e,r.T(),n,i);case"map":if(typeof e!="object"||e===null)return!1;if(i<2)return!0;if(!this.mapKeys(e,r.K,i))return!1;switch(r.V.kind){case"scalar":return this.scalars(Object.values(e),r.V.T,i,r.V.L);case"enum":return this.scalars(Object.values(e),L.INT32,i);case"message":return this.messages(Object.values(e),r.V.T(),n,i)}break}return!0}message(e,r,n,i){return n?r.isAssignable(e,i):r.is(e,i)}messages(e,r,n,i){if(!Array.isArray(e))return!1;if(i<2)return!0;if(n){for(let s=0;s<e.length&&s<i;s++)if(!r.isAssignable(e[s],i-1))return!1}else for(let s=0;s<e.length&&s<i;s++)if(!r.is(e[s],i-1))return!1;return!0}scalar(e,r,n){let i=typeof e;switch(r){case L.UINT64:case L.FIXED64:case L.INT64:case L.SFIXED64:case L.SINT64:switch(n){case yr.BIGINT:return i=="bigint";case yr.NUMBER:return i=="number"&&!isNaN(e);default:return i=="string"}case L.BOOL:return i=="boolean";case L.STRING:return i=="string";case L.BYTES:return e instanceof Uint8Array;case L.DOUBLE:case L.FLOAT:return i=="number"&&!isNaN(e);default:return i=="number"&&Number.isInteger(e)}}scalars(e,r,n,i){if(!Array.isArray(e))return!1;if(n<2)return!0;if(Array.isArray(e)){for(let s=0;s<e.length&&s<n;s++)if(!this.scalar(e[s],r,i))return!1}return!0}mapKeys(e,r,n){let i=Object.keys(e);switch(r){case L.INT32:case L.FIXED32:case L.SFIXED32:case L.SINT32:case L.UINT32:return this.scalars(i.slice(0,n).map(s=>parseInt(s)),r,n);case L.BOOL:return this.scalars(i.slice(0,n).map(s=>s=="true"?!0:s=="false"?!1:s),r,n);default:return this.scalars(i,r,n,yr.STRING)}}}function rr(t,e){switch(e){case yr.BIGINT:return t.toBigInt();case yr.NUMBER:return t.toNumber();default:return t.toString()}}class Ay{constructor(e){this.info=e}prepare(){var e;if(this.fMap===void 0){this.fMap={};const r=(e=this.info.fields)!==null&&e!==void 0?e:[];for(const n of r)this.fMap[n.name]=n,this.fMap[n.jsonName]=n,this.fMap[n.localName]=n}}assert(e,r,n){if(!e){let i=_d(n);throw(i=="number"||i=="boolean")&&(i=n.toString()),new Error(`Cannot parse JSON ${i} for ${this.info.typeName}#${r}`)}}read(e,r,n){this.prepare();const i=[];for(const[s,a]of Object.entries(e)){const o=this.fMap[s];if(!o){if(!n.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${s}`);continue}const d=o.localName;let h;if(o.oneof){if(a===null&&(o.kind!=="enum"||o.T()[0]!=="google.protobuf.NullValue"))continue;if(i.includes(o.oneof))throw new Error(`Multiple members of the oneof group "${o.oneof}" of ${this.info.typeName} are present in JSON.`);i.push(o.oneof),h=r[o.oneof]={oneofKind:d}}else h=r;if(o.kind=="map"){if(a===null)continue;this.assert(ly(a),o.name,a);const p=h[d];for(const[m,g]of Object.entries(a)){this.assert(g!==null,o.name+" map value",null);let v;switch(o.V.kind){case"message":v=o.V.T().internalJsonRead(g,n);break;case"enum":if(v=this.enum(o.V.T(),g,o.name,n.ignoreUnknownFields),v===!1)continue;break;case"scalar":v=this.scalar(g,o.V.T,o.V.L,o.name);break}this.assert(v!==void 0,o.name+" map value",g);let I=m;o.K==L.BOOL&&(I=I=="true"?!0:I=="false"?!1:I),I=this.scalar(I,o.K,yr.STRING,o.name).toString(),p[I]=v}}else if(o.repeat){if(a===null)continue;this.assert(Array.isArray(a),o.name,a);const p=h[d];for(const m of a){this.assert(m!==null,o.name,null);let g;switch(o.kind){case"message":g=o.T().internalJsonRead(m,n);break;case"enum":if(g=this.enum(o.T(),m,o.name,n.ignoreUnknownFields),g===!1)continue;break;case"scalar":g=this.scalar(m,o.T,o.L,o.name);break}this.assert(g!==void 0,o.name,a),p.push(g)}}else switch(o.kind){case"message":if(a===null&&o.T().typeName!="google.protobuf.Value"){this.assert(o.oneof===void 0,o.name+" (oneof member)",null);continue}h[d]=o.T().internalJsonRead(a,n,h[d]);break;case"enum":let p=this.enum(o.T(),a,o.name,n.ignoreUnknownFields);if(p===!1)continue;h[d]=p;break;case"scalar":h[d]=this.scalar(a,o.T,o.L,o.name);break}}}enum(e,r,n,i){if(e[0]=="google.protobuf.NullValue"&&ye(r===null||r==="NULL_VALUE",`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} only accepts null.`),r===null)return 0;switch(typeof r){case"number":return ye(Number.isInteger(r),`Unable to parse field ${this.info.typeName}#${n}, enum can only be integral number, got ${r}.`),r;case"string":let s=r;e[2]&&r.substring(0,e[2].length)===e[2]&&(s=r.substring(e[2].length));let a=e[1][s];return typeof a=="undefined"&&i?!1:(ye(typeof a=="number",`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} has no value for "${r}".`),a)}ye(!1,`Unable to parse field ${this.info.typeName}#${n}, cannot parse enum value from ${typeof r}".`)}scalar(e,r,n,i){let s;try{switch(r){case L.DOUBLE:case L.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===""){s="empty string";break}if(typeof e=="string"&&e.trim().length!==e.length){s="extra whitespace";break}if(typeof e!="string"&&typeof e!="number")break;let a=Number(e);if(Number.isNaN(a)){s="not a number";break}if(!Number.isFinite(a)){s="too large or small";break}return r==L.FLOAT&&Id(a),a;case L.INT32:case L.FIXED32:case L.SFIXED32:case L.SINT32:case L.UINT32:if(e===null)return 0;let o;if(typeof e=="number"?o=e:e===""?s="empty string":typeof e=="string"&&(e.trim().length!==e.length?s="extra whitespace":o=Number(e)),o===void 0)break;return r==L.UINT32?ao(o):Ss(o),o;case L.INT64:case L.SFIXED64:case L.SINT64:if(e===null)return rr(Ie.ZERO,n);if(typeof e!="number"&&typeof e!="string")break;return rr(Ie.from(e),n);case L.FIXED64:case L.UINT64:if(e===null)return rr(ft.ZERO,n);if(typeof e!="number"&&typeof e!="string")break;return rr(ft.from(e),n);case L.BOOL:if(e===null)return!1;if(typeof e!="boolean")break;return e;case L.STRING:if(e===null)return"";if(typeof e!="string"){s="extra whitespace";break}try{encodeURIComponent(e)}catch(d){d="invalid UTF8";break}return e;case L.BYTES:if(e===null||e==="")return new Uint8Array(0);if(typeof e!="string")break;return uy(e)}}catch(a){s=a.message}this.assert(!1,i+(s?" - "+s:""),e)}}class My{constructor(e){var r;this.fields=(r=e.fields)!==null&&r!==void 0?r:[]}write(e,r){const n={},i=e;for(const s of this.fields){if(!s.oneof){let h=this.field(s,i[s.localName],r);h!==void 0&&(n[r.useProtoFieldName?s.name:s.jsonName]=h);continue}const a=i[s.oneof];if(a.oneofKind!==s.localName)continue;const o=s.kind=="scalar"||s.kind=="enum"?Object.assign(Object.assign({},r),{emitDefaultValues:!0}):r;let d=this.field(s,a[s.localName],o);ye(d!==void 0),n[r.useProtoFieldName?s.name:s.jsonName]=d}return n}field(e,r,n){let i;if(e.kind=="map"){ye(typeof r=="object"&&r!==null);const s={};switch(e.V.kind){case"scalar":for(const[d,h]of Object.entries(r)){const p=this.scalar(e.V.T,h,e.name,!1,!0);ye(p!==void 0),s[d.toString()]=p}break;case"message":const a=e.V.T();for(const[d,h]of Object.entries(r)){const p=this.message(a,h,e.name,n);ye(p!==void 0),s[d.toString()]=p}break;case"enum":const o=e.V.T();for(const[d,h]of Object.entries(r)){ye(h===void 0||typeof h=="number");const p=this.enum(o,h,e.name,!1,!0,n.enumAsInteger);ye(p!==void 0),s[d.toString()]=p}break}(n.emitDefaultValues||Object.keys(s).length>0)&&(i=s)}else if(e.repeat){ye(Array.isArray(r));const s=[];switch(e.kind){case"scalar":for(let d=0;d<r.length;d++){const h=this.scalar(e.T,r[d],e.name,e.opt,!0);ye(h!==void 0),s.push(h)}break;case"enum":const a=e.T();for(let d=0;d<r.length;d++){ye(r[d]===void 0||typeof r[d]=="number");const h=this.enum(a,r[d],e.name,e.opt,!0,n.enumAsInteger);ye(h!==void 0),s.push(h)}break;case"message":const o=e.T();for(let d=0;d<r.length;d++){const h=this.message(o,r[d],e.name,n);ye(h!==void 0),s.push(h)}break}(n.emitDefaultValues||s.length>0||n.emitDefaultValues)&&(i=s)}else switch(e.kind){case"scalar":i=this.scalar(e.T,r,e.name,e.opt,n.emitDefaultValues);break;case"enum":i=this.enum(e.T(),r,e.name,e.opt,n.emitDefaultValues,n.enumAsInteger);break;case"message":i=this.message(e.T(),r,e.name,n);break}return i}enum(e,r,n,i,s,a){if(e[0]=="google.protobuf.NullValue")return!s&&!i?void 0:null;if(r===void 0){ye(i);return}if(!(r===0&&!s&&!i))return ye(typeof r=="number"),ye(Number.isInteger(r)),a||!e[1].hasOwnProperty(r)?r:e[2]?e[2]+e[1][r]:e[1][r]}message(e,r,n,i){return r===void 0?i.emitDefaultValues?null:void 0:e.internalJsonWrite(r,i)}scalar(e,r,n,i,s){if(r===void 0){ye(i);return}const a=s||i;switch(e){case L.INT32:case L.SFIXED32:case L.SINT32:return r===0?a?0:void 0:(Ss(r),r);case L.FIXED32:case L.UINT32:return r===0?a?0:void 0:(ao(r),r);case L.FLOAT:Id(r);case L.DOUBLE:return r===0?a?0:void 0:(ye(typeof r=="number"),Number.isNaN(r)?"NaN":r===Number.POSITIVE_INFINITY?"Infinity":r===Number.NEGATIVE_INFINITY?"-Infinity":r);case L.STRING:return r===""?a?"":void 0:(ye(typeof r=="string"),r);case L.BOOL:return r===!1?a?!1:void 0:(ye(typeof r=="boolean"),r);case L.UINT64:case L.FIXED64:ye(typeof r=="number"||typeof r=="string"||typeof r=="bigint");let o=ft.from(r);return o.isZero()&&!a?void 0:o.toString();case L.INT64:case L.SFIXED64:case L.SINT64:ye(typeof r=="number"||typeof r=="string"||typeof r=="bigint");let d=Ie.from(r);return d.isZero()&&!a?void 0:d.toString();case L.BYTES:return ye(r instanceof Uint8Array),r.byteLength?hy(r):a?"":void 0}}}function Cd(t,e=yr.STRING){switch(t){case L.BOOL:return!1;case L.UINT64:case L.FIXED64:return rr(ft.ZERO,e);case L.INT64:case L.SFIXED64:case L.SINT64:return rr(Ie.ZERO,e);case L.DOUBLE:case L.FLOAT:return 0;case L.BYTES:return new Uint8Array(0);case L.STRING:return"";default:return 0}}class Dy{constructor(e){this.info=e}prepare(){var e;if(!this.fieldNoToField){const r=(e=this.info.fields)!==null&&e!==void 0?e:[];this.fieldNoToField=new Map(r.map(n=>[n.no,n]))}}read(e,r,n,i){this.prepare();const s=i===void 0?e.len:e.pos+i;for(;e.pos<s;){const[a,o]=e.tag(),d=this.fieldNoToField.get(a);if(!d){let g=n.readUnknownField;if(g=="throw")throw new Error(`Unknown field ${a} (wire type ${o}) for ${this.info.typeName}`);let v=e.skip(o);g!==!1&&(g===!0?ro.onRead:g)(this.info.typeName,r,a,o,v);continue}let h=r,p=d.repeat,m=d.localName;switch(d.oneof&&(h=h[d.oneof],h.oneofKind!==m&&(h=r[d.oneof]={oneofKind:m})),d.kind){case"scalar":case"enum":let g=d.kind=="enum"?L.INT32:d.T,v=d.kind=="scalar"?d.L:void 0;if(p){let P=h[m];if(o==$e.LengthDelimited&&g!=L.STRING&&g!=L.BYTES){let D=e.uint32()+e.pos;for(;e.pos<D;)P.push(this.scalar(e,g,v))}else P.push(this.scalar(e,g,v))}else h[m]=this.scalar(e,g,v);break;case"message":if(p){let P=h[m],D=d.T().internalBinaryRead(e,e.uint32(),n);P.push(D)}else h[m]=d.T().internalBinaryRead(e,e.uint32(),n,h[m]);break;case"map":let[I,A]=this.mapEntry(d,e,n);h[m][I]=A;break}}}mapEntry(e,r,n){let i=r.uint32(),s=r.pos+i,a,o;for(;r.pos<s;){let[d,h]=r.tag();switch(d){case 1:e.K==L.BOOL?a=r.bool().toString():a=this.scalar(r,e.K,yr.STRING);break;case 2:switch(e.V.kind){case"scalar":o=this.scalar(r,e.V.T,e.V.L);break;case"enum":o=r.int32();break;case"message":o=e.V.T().internalBinaryRead(r,r.uint32(),n);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=Cd(e.K);a=e.K==L.BOOL?d.toString():d}if(o===void 0)switch(e.V.kind){case"scalar":o=Cd(e.V.T,e.V.L);break;case"enum":o=0;break;case"message":o=e.V.T().create();break}return[a,o]}scalar(e,r,n){switch(r){case L.INT32:return e.int32();case L.STRING:return e.string();case L.BOOL:return e.bool();case L.DOUBLE:return e.double();case L.FLOAT:return e.float();case L.INT64:return rr(e.int64(),n);case L.UINT64:return rr(e.uint64(),n);case L.FIXED64:return rr(e.fixed64(),n);case L.FIXED32:return e.fixed32();case L.BYTES:return e.bytes();case L.UINT32:return e.uint32();case L.SFIXED32:return e.sfixed32();case L.SFIXED64:return rr(e.sfixed64(),n);case L.SINT32:return e.sint32();case L.SINT64:return rr(e.sint64(),n)}}}class Oy{constructor(e){this.info=e}prepare(){if(!this.fields){const e=this.info.fields?this.info.fields.concat():[];this.fields=e.sort((r,n)=>r.no-n.no)}}write(e,r,n){this.prepare();for(const s of this.fields){let a,o,d=s.repeat,h=s.localName;if(s.oneof){const p=e[s.oneof];if(p.oneofKind!==h)continue;a=p[h],o=!0}else a=e[h],o=!1;switch(s.kind){case"scalar":case"enum":let p=s.kind=="enum"?L.INT32:s.T;if(d)if(ye(Array.isArray(a)),d==oo.PACKED)this.packed(r,p,s.no,a);else for(const m of a)this.scalar(r,p,s.no,m,!0);else a===void 0?ye(s.opt):this.scalar(r,p,s.no,a,o||s.opt);break;case"message":if(d){ye(Array.isArray(a));for(const m of a)this.message(r,n,s.T(),s.no,m)}else this.message(r,n,s.T(),s.no,a);break;case"map":ye(typeof a=="object"&&a!==null);for(const[m,g]of Object.entries(a))this.mapEntry(r,n,s,m,g);break}}let i=n.writeUnknownFields;i!==!1&&(i===!0?ro.onWrite:i)(this.info.typeName,e,r)}mapEntry(e,r,n,i,s){e.tag(n.no,$e.LengthDelimited),e.fork();let a=i;switch(n.K){case L.INT32:case L.FIXED32:case L.UINT32:case L.SFIXED32:case L.SINT32:a=Number.parseInt(i);break;case L.BOOL:ye(i=="true"||i=="false"),a=i=="true";break}switch(this.scalar(e,n.K,1,a,!0),n.V.kind){case"scalar":this.scalar(e,n.V.T,2,s,!0);break;case"enum":this.scalar(e,L.INT32,2,s,!0);break;case"message":this.message(e,r,n.V.T(),2,s);break}e.join()}message(e,r,n,i,s){s!==void 0&&(n.internalBinaryWrite(s,e.tag(i,$e.LengthDelimited).fork(),r),e.join())}scalar(e,r,n,i,s){let[a,o,d]=this.scalarInfo(r,i);(!d||s)&&(e.tag(n,a),e[o](i))}packed(e,r,n,i){if(!i.length)return;ye(r!==L.BYTES&&r!==L.STRING),e.tag(n,$e.LengthDelimited),e.fork();let[,s]=this.scalarInfo(r);for(let a=0;a<i.length;a++)e[s](i[a]);e.join()}scalarInfo(e,r){let n=$e.Varint,i,s=r===void 0,a=r===0;switch(e){case L.INT32:i="int32";break;case L.STRING:a=s||!r.length,n=$e.LengthDelimited,i="string";break;case L.BOOL:a=r===!1,i="bool";break;case L.UINT32:i="uint32";break;case L.DOUBLE:n=$e.Bit64,i="double";break;case L.FLOAT:n=$e.Bit32,i="float";break;case L.INT64:a=s||Ie.from(r).isZero(),i="int64";break;case L.UINT64:a=s||ft.from(r).isZero(),i="uint64";break;case L.FIXED64:a=s||ft.from(r).isZero(),n=$e.Bit64,i="fixed64";break;case L.BYTES:a=s||!r.byteLength,n=$e.LengthDelimited,i="bytes";break;case L.FIXED32:n=$e.Bit32,i="fixed32";break;case L.SFIXED32:n=$e.Bit32,i="sfixed32";break;case L.SFIXED64:a=s||Ie.from(r).isZero(),n=$e.Bit64,i="sfixed64";break;case L.SINT32:i="sint32";break;case L.SINT64:a=s||Ie.from(r).isZero(),i="sint64";break}return[n,i,s||a]}}function Ny(t){const e=t.messagePrototype?Object.create(t.messagePrototype):Object.defineProperty({},ch,{value:t});for(let r of t.fields){let n=r.localName;if(!r.opt)if(r.oneof)e[r.oneof]={oneofKind:void 0};else if(r.repeat)e[n]=[];else switch(r.kind){case"scalar":e[n]=Cd(r.T,r.L);break;case"enum":e[n]=0;break;case"map":e[n]={};break}}return e}function Pd(t,e,r){let n,i=r,s;for(let a of t.fields){let o=a.localName;if(a.oneof){const d=i[a.oneof];if((d==null?void 0:d.oneofKind)==null)continue;if(n=d[o],s=e[a.oneof],s.oneofKind=d.oneofKind,n==null){delete s[o];continue}}else if(n=i[o],s=e,n==null)continue;switch(a.repeat&&(s[o].length=n.length),a.kind){case"scalar":case"enum":if(a.repeat)for(let h=0;h<n.length;h++)s[o][h]=n[h];else s[o]=n;break;case"message":let d=a.T();if(a.repeat)for(let h=0;h<n.length;h++)s[o][h]=d.create(n[h]);else s[o]===void 0?s[o]=d.create(n):d.mergePartial(s[o],n);break;case"map":switch(a.V.kind){case"scalar":case"enum":Object.assign(s[o],n);break;case"message":let h=a.V.T();for(let p of Object.keys(n))s[o][p]=h.create(n[p]);break}break}}}function Ly(t,e,r){if(e===r)return!0;if(!e||!r)return!1;for(let n of t.fields){let i=n.localName,s=n.oneof?e[n.oneof][i]:e[i],a=n.oneof?r[n.oneof][i]:r[i];switch(n.kind){case"enum":case"scalar":let o=n.kind=="enum"?L.INT32:n.T;if(!(n.repeat?uh(o,s,a):lh(o,s,a)))return!1;break;case"map":if(!(n.V.kind=="message"?hh(n.V.T(),co(s),co(a)):uh(n.V.kind=="enum"?L.INT32:n.V.T,co(s),co(a))))return!1;break;case"message":let d=n.T();if(!(n.repeat?hh(d,s,a):d.equals(s,a)))return!1;break}}return!0}const co=Object.values;function lh(t,e,r){if(e===r)return!0;if(t!==L.BYTES)return!1;let n=e,i=r;if(n.length!==i.length)return!1;for(let s=0;s<n.length;s++)if(n[s]!=i[s])return!1;return!0}function uh(t,e,r){if(e.length!==r.length)return!1;for(let n=0;n<e.length;n++)if(!lh(t,e[n],r[n]))return!1;return!0}function hh(t,e,r){if(e.length!==r.length)return!1;for(let n=0;n<e.length;n++)if(!t.equals(e[n],r[n]))return!1;return!0}const xy=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({}));class E{constructor(e,r,n){this.defaultCheckDepth=16,this.typeName=e,this.fields=r.map(Cy),this.options=n!=null?n:{},this.messagePrototype=Object.create(null,Object.assign(Object.assign({},xy),{[ch]:{value:this}})),this.refTypeCheck=new Ry(this),this.refJsonReader=new Ay(this),this.refJsonWriter=new My(this),this.refBinReader=new Dy(this),this.refBinWriter=new Oy(this)}create(e){let r=Ny(this);return e!==void 0&&Pd(this,r,e),r}clone(e){let r=this.create();return Pd(this,r,e),r}equals(e,r){return Ly(this,e,r)}is(e,r=this.defaultCheckDepth){return this.refTypeCheck.is(e,r,!1)}isAssignable(e,r=this.defaultCheckDepth){return this.refTypeCheck.is(e,r,!0)}mergePartial(e,r){Pd(this,e,r)}fromBinary(e,r){let n=gy(r);return this.internalBinaryRead(n.readerFactory(e),e.byteLength,n)}fromJson(e,r){return this.internalJsonRead(e,wy(r))}fromJsonString(e,r){let n=JSON.parse(e);return this.fromJson(n,r)}toJson(e,r){return this.internalJsonWrite(e,Iy(r))}toJsonString(e,r){var n;let i=this.toJson(e,r);return JSON.stringify(i,null,(n=r==null?void 0:r.prettySpaces)!==null&&n!==void 0?n:0)}toBinary(e,r){let n=_y(r);return this.internalBinaryWrite(e,n.writerFactory(),n).finish()}internalJsonRead(e,r,n){if(e!==null&&typeof e=="object"&&!Array.isArray(e)){let i=n!=null?n:this.create();return this.refJsonReader.read(e,i,r),i}throw new Error(`Unable to parse message ${this.typeName} from JSON ${_d(e)}.`)}internalJsonWrite(e,r){return this.refJsonWriter.write(e,r)}internalBinaryWrite(e,r,n){return this.refBinWriter.write(e,r,n),r}internalBinaryRead(e,r,n,i){let s=i!=null?i:this.create();return this.refBinReader.read(e,s,n,r),s}}const Fy=t=>(e,r)=>(t.set(e,r),r),ph=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,mh=536870912,fh=mh*2,Vy=(t,e)=>r=>{const n=e.get(r);let i=n===void 0?r.size:n<fh?n+1:0;if(!r.has(i))return t(r,i);if(r.size<mh){for(;r.has(i);)i=Math.floor(Math.random()*fh);return t(r,i)}if(r.size>ph)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*ph);return t(r,i)},gh=new WeakMap,Uy=Fy(gh),lo=Vy(Uy,gh),By=t=>t.method!==void 0&&t.method==="call",jy=t=>t.error===null&&typeof t.id=="number",uo=((t,e)=>{let r=null;return()=>{if(r!==null)return r;const n=new Blob([e],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(n);return r=t(i),setTimeout(()=>URL.revokeObjectURL(i)),r}})(t=>{const e=new Map([[0,()=>{}]]),r=new Map([[0,()=>{}]]),n=new Map,i=new Worker(t);return i.addEventListener("message",({data:h})=>{if(By(h)){const{params:{timerId:p,timerType:m}}=h;if(m==="interval"){const g=e.get(p);if(typeof g=="number"){const v=n.get(g);if(v===void 0||v.timerId!==p||v.timerType!==m)throw new Error("The timer is in an undefined state.")}else if(typeof g!="undefined")g();else throw new Error("The timer is in an undefined state.")}else if(m==="timeout"){const g=r.get(p);if(typeof g=="number"){const v=n.get(g);if(v===void 0||v.timerId!==p||v.timerType!==m)throw new Error("The timer is in an undefined state.")}else if(typeof g!="undefined")g(),r.delete(p);else throw new Error("The timer is in an undefined state.")}}else if(jy(h)){const{id:p}=h,m=n.get(p);if(m===void 0)throw new Error("The timer is in an undefined state.");const{timerId:g,timerType:v}=m;n.delete(p),v==="interval"?e.delete(g):r.delete(g)}else{const{error:{message:p}}=h;throw new Error(p)}}),{clearInterval:h=>{const p=lo(n);n.set(p,{timerId:h,timerType:"interval"}),e.set(h,p),i.postMessage({id:p,method:"clear",params:{timerId:h,timerType:"interval"}})},clearTimeout:h=>{const p=lo(n);n.set(p,{timerId:h,timerType:"timeout"}),r.set(h,p),i.postMessage({id:p,method:"clear",params:{timerId:h,timerType:"timeout"}})},setInterval:(h,p=0)=>{const m=lo(e);return e.set(m,()=>{h(),typeof e.get(m)=="function"&&i.postMessage({id:null,method:"set",params:{delay:p,now:performance.now(),timerId:m,timerType:"interval"}})}),i.postMessage({id:null,method:"set",params:{delay:p,now:performance.now(),timerId:m,timerType:"interval"}}),m},setTimeout:(h,p=0)=>{const m=lo(r);return r.set(m,h),i.postMessage({id:null,method:"set",params:{delay:p,now:performance.now(),timerId:m,timerType:"timeout"}}),m}}},`(()=>{"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})}}))})();`),vh=t=>uo().clearInterval(t),Hy=t=>uo().clearTimeout(t),yh=(t,e)=>uo().setInterval(t,e);var Wy=Object.freeze(Object.defineProperty({__proto__:null,clearInterval:vh,clearTimeout:Hy,setInterval:yh,setTimeout:(t,e)=>uo().setTimeout(t,e)},Symbol.toStringTag,{value:"Module"})),Sh={},Rd={exports:{}},Eh=Rd.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(Eh).forEach(function(t){var e=Eh[t];e.forEach(function(r){r.reg||(r.reg=/(.*)/),r.format||(r.format="%s")})}),function(t){var e=function(o){return String(Number(o))===o?Number(o):o},r=function(o,d,h,p){if(p&&!h)d[p]=e(o[1]);else for(var m=0;m<h.length;m+=1)o[m+1]!=null&&(d[h[m]]=e(o[m+1]))},n=function(o,d,h){var p=o.name&&o.names;o.push&&!d[o.push]?d[o.push]=[]:p&&!d[o.name]&&(d[o.name]={});var m=o.push?{}:p?d[o.name]:d;r(h.match(o.reg),m,o.names,o.name),o.push&&d[o.push].push(m)},i=Rd.exports,s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(o){var d={},h=[],p=d;return o.split(/(\r\n|\r|\n)/).filter(s).forEach(function(m){var g=m[0],v=m.slice(2);g==="m"&&(h.push({rtp:[],fmtp:[]}),p=h[h.length-1]);for(var I=0;I<(i[g]||[]).length;I+=1){var A=i[g][I];if(A.reg.test(v))return n(A,p,v)}}),d.media=h,d};var a=function(o,d){var h=d.split(/=(.+)/,2);return h.length===2?o[h[0]]=e(h[1]):h.length===1&&d.length>1&&(o[h[0]]=void 0),o};t.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(o){return o.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(o){for(var d=[],h=o.split(" ").map(e),p=0;p<h.length;p+=3)d.push({component:h[p],ip:h[p+1],port:h[p+2]});return d},t.parseImageAttributes=function(o){return o.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(a,{})})},t.parseSimulcastStreamList=function(o){return o.split(";").map(function(d){return d.split(",").map(function(h){var p,m=!1;return h[0]!=="~"?p=e(h):(p=e(h.substring(1,h.length)),m=!0),{scid:p,paused:m}})})}}(Sh);var Ad=Rd.exports,$y=/%[sdv%]/g,Jy=function(t){var e=1,r=arguments,n=r.length;return t.replace($y,function(i){if(e>=n)return i;var s=r[e];switch(e+=1,i){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},Es=function(t,e,r){var n=e.format instanceof Function?e.format(e.push?r:r[e.name]):e.format,i=[t+"="+n];if(e.names)for(var s=0;s<e.names.length;s+=1){var a=e.names[s];e.name?i.push(r[e.name][a]):i.push(r[e.names[s]])}else i.push(r[e.name]);return Jy.apply(null,i)},Gy=["v","o","s","i","u","e","p","c","b","t","r","z","a"],qy=["i","c","b","a"],zy=function(t,e){e=e||{},t.version==null&&(t.version=0),t.name==null&&(t.name=" "),t.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var r=e.outerOrder||Gy,n=e.innerOrder||qy,i=[];return r.forEach(function(s){Ad[s].forEach(function(a){a.name in t&&t[a.name]!=null?i.push(Es(s,a,t)):a.push in t&&t[a.push]!=null&&t[a.push].forEach(function(o){i.push(Es(s,a,o))})})}),t.media.forEach(function(s){i.push(Es("m",Ad.m[0],s)),n.forEach(function(a){Ad[a].forEach(function(o){o.name in s&&s[o.name]!=null?i.push(Es(a,o,s)):o.push in s&&s[o.push]!=null&&s[o.push].forEach(function(d){i.push(Es(a,o,d))})})})}),i.join(`\r
8
8
  `)+`\r
9
- `},vn=Mu,ry=ty,ny=ry,Kc=vn.parse;vn.parseParams,vn.parseFmtpConfig,vn.parsePayloads,vn.parseRemoteCandidates,vn.parseImageAttributes,vn.parseSimulcastStreamList;var iy=Object.defineProperty,sy=Object.defineProperties,oy=Object.getOwnPropertyDescriptors,Io=Object.getOwnPropertySymbols,ay=Object.getPrototypeOf,Ou=Object.prototype.hasOwnProperty,Nu=Object.prototype.propertyIsEnumerable,cy=Reflect.get,dy=Math.pow,zc=(t,e,r)=>e in t?iy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,V=(t,e)=>{for(var r in e||(e={}))Ou.call(e,r)&&zc(t,r,e[r]);if(Io)for(var r of Io(e))Nu.call(e,r)&&zc(t,r,e[r]);return t},ne=(t,e)=>sy(t,oy(e)),Ro=(t,e)=>{var r={};for(var n in t)Ou.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&Io)for(var n of Io(t))e.indexOf(n)<0&&Nu.call(t,n)&&(r[n]=t[n]);return r},m=(t,e,r)=>(zc(t,typeof e!="symbol"?e+"":e,r),r),Yc=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},c=(t,e,r)=>(Yc(t,e,"read from private field"),r?r.call(t):e.get(t)),_=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},T=(t,e,r,n)=>(Yc(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),ue=(t,e,r)=>(Yc(t,e,"access private method"),r),ly=(t,e,r)=>cy(ay(t),r,e),u=(t,e,r)=>new Promise((n,i)=>{var s=d=>{try{a(r.next(d))}catch(h){i(h)}},o=d=>{try{a(r.throw(d))}catch(h){i(h)}},a=d=>d.done?n(d.value):Promise.resolve(d.value).then(s,o);a((r=r.apply(t,e)).next())}),Lu=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function uy(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var _t={},hy={get exports(){return _t},set exports(t){_t=t}},fi=typeof Reflect=="object"?Reflect:null,xu=fi&&typeof fi.apply=="function"?fi.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},Po;fi&&typeof fi.ownKeys=="function"?Po=fi.ownKeys:Object.getOwnPropertySymbols?Po=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Po=function(t){return Object.getOwnPropertyNames(t)};function py(t){console&&console.warn&&console.warn(t)}var Fu=Number.isNaN||function(t){return t!==t};function ve(){ve.init.call(this)}hy.exports=ve,_t.once=vy,ve.EventEmitter=ve,ve.prototype._events=void 0,ve.prototype._eventsCount=0,ve.prototype._maxListeners=void 0;var Uu=10;function Ao(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(ve,"defaultMaxListeners",{enumerable:!0,get:function(){return Uu},set:function(t){if(typeof t!="number"||t<0||Fu(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Uu=t}}),ve.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},ve.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Fu(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 Vu(t){return t._maxListeners===void 0?ve.defaultMaxListeners:t._maxListeners}ve.prototype.getMaxListeners=function(){return Vu(this)},ve.prototype.emit=function(t){for(var e=[],r=1;r<arguments.length;r++)e.push(arguments[r]);var n=t==="error",i=this._events;if(i!==void 0)n=n&&i.error===void 0;else if(!n)return!1;if(n){var s;if(e.length>0&&(s=e[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=i[t];if(a===void 0)return!1;if(typeof a=="function")xu(a,this,e);else for(var d=a.length,h=$u(a,d),r=0;r<d;++r)xu(h[r],this,e);return!0};function Bu(t,e,r,n){var i,s,o;if(Ao(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=Vu(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,py(a)}return t}ve.prototype.addListener=function(t,e){return Bu(this,t,e,!1)},ve.prototype.on=ve.prototype.addListener,ve.prototype.prependListener=function(t,e){return Bu(this,t,e,!0)};function my(){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 ju(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=my.bind(n);return i.listener=r,n.wrapFn=i,i}ve.prototype.once=function(t,e){return Ao(e),this.on(t,ju(this,t,e)),this},ve.prototype.prependOnceListener=function(t,e){return Ao(e),this.prependListener(t,ju(this,t,e)),this},ve.prototype.removeListener=function(t,e){var r,n,i,s,o;if(Ao(e),n=this._events,n===void 0)return this;if(r=n[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete n[t],n.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(i=-1,s=r.length-1;s>=0;s--)if(r[s]===e||r[s].listener===e){o=r[s].listener,i=s;break}if(i<0)return this;i===0?r.shift():fy(r,i),r.length===1&&(n[t]=r[0]),n.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this},ve.prototype.off=ve.prototype.removeListener,ve.prototype.removeAllListeners=function(t){var e,r,n;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[t]),this;if(arguments.length===0){var i=Object.keys(r),s;for(n=0;n<i.length;++n)s=i[n],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=r[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(n=e.length-1;n>=0;n--)this.removeListener(t,e[n]);return this};function Hu(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?gy(i):$u(i,i.length)}ve.prototype.listeners=function(t){return Hu(this,t,!0)},ve.prototype.rawListeners=function(t){return Hu(this,t,!1)},ve.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Wu.call(t,e)},ve.prototype.listenerCount=Wu;function Wu(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}ve.prototype.eventNames=function(){return this._eventsCount>0?Po(this._events):[]};function $u(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function fy(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function gy(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function vy(t,e){return new Promise(function(r,n){function i(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}Gu(t,e,s,{once:!0}),e!=="error"&&yy(t,i,{once:!0})})}function yy(t,e,r){typeof t.on=="function"&&Gu(t,"error",e,r)}function Gu(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var or={},Ey={get exports(){return or},set exports(t){or=t}},Qc,Ju;function Sy(){if(Ju)return Qc;Ju=1;var t=1e3,e=t*60,r=e*60,n=r*24,i=n*7,s=n*365.25;Qc=function(p,f){f=f||{};var g=typeof p;if(g==="string"&&p.length>0)return o(p);if(g==="number"&&isFinite(p))return f.long?d(p):a(p);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(p))};function o(p){if(p=String(p),!(p.length>100)){var f=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(p);if(f){var g=parseFloat(f[1]),E=(f[2]||"ms").toLowerCase();switch(E){case"years":case"year":case"yrs":case"yr":case"y":return g*s;case"weeks":case"week":case"w":return g*i;case"days":case"day":case"d":return g*n;case"hours":case"hour":case"hrs":case"hr":case"h":return g*r;case"minutes":case"minute":case"mins":case"min":case"m":return g*e;case"seconds":case"second":case"secs":case"sec":case"s":return g*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return g;default:return}}}}function a(p){var f=Math.abs(p);return f>=n?Math.round(p/n)+"d":f>=r?Math.round(p/r)+"h":f>=e?Math.round(p/e)+"m":f>=t?Math.round(p/t)+"s":p+"ms"}function d(p){var f=Math.abs(p);return f>=n?h(p,f,n,"day"):f>=r?h(p,f,r,"hour"):f>=e?h(p,f,e,"minute"):f>=t?h(p,f,t,"second"):p+" ms"}function h(p,f,g,E){var v=f>=g*1.5;return Math.round(p/g)+" "+E+(v?"s":"")}return Qc}function Ty(t){r.debug=r,r.default=r,r.coerce=d,r.disable=s,r.enable=i,r.enabled=o,r.humanize=Sy(),r.destroy=h,Object.keys(t).forEach(p=>{r[p]=t[p]}),r.names=[],r.skips=[],r.formatters={};function e(p){let f=0;for(let g=0;g<p.length;g++)f=(f<<5)-f+p.charCodeAt(g),f|=0;return r.colors[Math.abs(f)%r.colors.length]}r.selectColor=e;function r(p){let f,g=null,E,v;function R(...A){if(!R.enabled)return;const L=R,F=Number(new Date),W=F-(f||F);L.diff=W,L.prev=f,L.curr=F,f=F,A[0]=r.coerce(A[0]),typeof A[0]!="string"&&A.unshift("%O");let H=0;A[0]=A[0].replace(/%([a-zA-Z%])/g,(I,S)=>{if(I==="%%")return"%";H++;const P=r.formatters[S];if(typeof P=="function"){const N=A[H];I=P.call(L,N),A.splice(H,1),H--}return I}),r.formatArgs.call(L,A),(L.log||r.log).apply(L,A)}return R.namespace=p,R.useColors=r.useColors(),R.color=r.selectColor(p),R.extend=n,R.destroy=r.destroy,Object.defineProperty(R,"enabled",{enumerable:!0,configurable:!1,get:()=>g!==null?g:(E!==r.namespaces&&(E=r.namespaces,v=r.enabled(p)),v),set:A=>{g=A}}),typeof r.init=="function"&&r.init(R),R}function n(p,f){const g=r(this.namespace+(typeof f=="undefined"?":":f)+p);return g.log=this.log,g}function i(p){r.save(p),r.namespaces=p,r.names=[],r.skips=[];let f;const g=(typeof p=="string"?p:"").split(/[\s,]+/),E=g.length;for(f=0;f<E;f++)g[f]&&(p=g[f].replace(/\*/g,".*?"),p[0]==="-"?r.skips.push(new RegExp("^"+p.slice(1)+"$")):r.names.push(new RegExp("^"+p+"$")))}function s(){const p=[...r.names.map(a),...r.skips.map(a).map(f=>"-"+f)].join(",");return r.enable(""),p}function o(p){if(p[p.length-1]==="*")return!0;let f,g;for(f=0,g=r.skips.length;f<g;f++)if(r.skips[f].test(p))return!1;for(f=0,g=r.names.length;f<g;f++)if(r.names[f].test(p))return!0;return!1}function a(p){return p.toString().substring(2,p.toString().length-2).replace(/\.\*\?$/,"*")}function d(p){return p instanceof Error?p.stack||p.message:p}function h(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}var ky=Ty;(function(t,e){e.formatArgs=n,e.save=i,e.load=s,e.useColors=r,e.storage=o(),e.destroy=(()=>{let d=!1;return()=>{d||(d=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function r(){if(typeof window!="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let d;return typeof document!="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!="undefined"&&navigator.userAgent&&(d=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(d[1],10)>=31||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function n(d){if(d[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+d[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const h="color: "+this.color;d.splice(1,0,h,"color: inherit");let p=0,f=0;d[0].replace(/%[a-zA-Z%]/g,g=>{g!=="%%"&&(p++,g==="%c"&&(f=p))}),d.splice(f,0,h)}e.log=console.debug||console.log||(()=>{});function i(d){try{d?e.storage.setItem("debug",d):e.storage.removeItem("debug")}catch(h){}}function s(){let d;try{d=e.storage.getItem("debug")}catch(h){}return!d&&typeof process!="undefined"&&"env"in process&&(d={}.DEBUG),d}function o(){try{return localStorage}catch(d){}}t.exports=ky(e);const{formatters:a}=t.exports;a.j=function(d){try{return JSON.stringify(d)}catch(h){return"[UnexpectedJSONParseError]: "+h.message}}})(Ey,or);const gi="mediasoup-client";let _y=class{constructor(t){t?(this._debug=or(`${gi}:${t}`),this._warn=or(`${gi}:WARN:${t}`),this._error=or(`${gi}:ERROR:${t}`)):(this._debug=or(gi),this._warn=or(`${gi}:WARN`),this._error=or(`${gi}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};const by=new _y("EnhancedEventEmitter");let Mo=class extends _t.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}emit(t,...e){return super.emit(t,...e)}safeEmit(t,...e){const r=super.listenerCount(t);try{return super.emit(t,...e)}catch(n){return by.error("safeEmit() | event listener threw an error [eventName:%s]:%o",t,n),Boolean(r)}}on(t,e){return super.on(t,e),this}off(t,e){return super.off(t,e),this}addListener(t,e){return super.on(t,e),this}prependListener(t,e){return super.prependListener(t,e),this}once(t,e){return super.once(t,e),this}prependOnceListener(t,e){return super.prependOnceListener(t,e),this}removeListener(t,e){return super.off(t,e),this}removeAllListeners(t){return super.removeAllListeners(t),this}listenerCount(t){return super.listenerCount(t)}listeners(t){return super.listeners(t)}rawListeners(t){return super.rawListeners(t)}};var z;(function(t){t[t.MAJOR_EVENT=0]="MAJOR_EVENT",t[t.MINOR_EVENT=1]="MINOR_EVENT"})(z||(z={}));var U;(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.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"})(U||(U={}));const wy=new Map([[U.PRECALL_TEST_BEGIN,z.MINOR_EVENT],[U.PRECALL_TEST_COMPLETE,z.MINOR_EVENT],[U.CALL_JOIN_BEGIN,z.MAJOR_EVENT],[U.NET_QUALITY_TEST_BEGIN,z.MINOR_EVENT],[U.NET_QUALITY_TEST_END,z.MINOR_EVENT],[U.WEBSOCKET_CONNECTED,z.MINOR_EVENT],[U.TRANSPORT_CONNECTED,z.MAJOR_EVENT],[U.AUDIO_ON,z.MINOR_EVENT],[U.AUDIO_OFF,z.MINOR_EVENT],[U.VIDEO_ON,z.MINOR_EVENT],[U.VIDEO_OFF,z.MINOR_EVENT],[U.PARTICIPANT_ROLE,z.MINOR_EVENT],[U.PING_STAT,z.MAJOR_EVENT],[U.DISCONNECT,z.MAJOR_EVENT],[U.RECONNECT_ATTEMPT,z.MAJOR_EVENT],[U.SCREENSHARE_START_REQUESTED,z.MINOR_EVENT],[U.SCREENSHARE_STARTED,z.MINOR_EVENT],[U.SCREENSHARE_STOPPED,z.MINOR_EVENT],[U.TAB_CHANGE,z.MINOR_EVENT],[U.BROWSER_BACKGROUNDED,z.MINOR_EVENT],[U.BROWSER_FOREGROUNDED,z.MINOR_EVENT],[U.DOMINANT_SPEAKER,z.MINOR_EVENT],[U.AUDIO_DEVICES_UPDATES,z.MINOR_EVENT],[U.VIDEO_DEVICES_UPDATES,z.MINOR_EVENT],[U.SPEAKER_DEVICES_UPDATES,z.MINOR_EVENT],[U.SELECTED_MICROHPONE_UPDATE,z.MINOR_EVENT],[U.SELECTED_CAMERA_UPDATE,z.MINOR_EVENT],[U.SELECTED_SPEAKER_UPDATE,z.MINOR_EVENT],[U.MEDIA_PERMISSION,z.MINOR_EVENT],[U.LEGACY_SWITCH,z.MINOR_EVENT],[U.AUDIO_PLAY_FAILED,z.MINOR_EVENT],[U.VIDEO_PLAY_FAILED,z.MINOR_EVENT],[U.AUDIO_TRACK_MUTED,z.MINOR_EVENT],[U.VIDEO_TRACK_MUTED,z.MINOR_EVENT],[U.IVS_PLAYER_REBUFFERING,z.MAJOR_EVENT],[U.IVS_PLAYER_AUDIO_BLOCKED,z.MAJOR_EVENT],[U.IVS_PLAYER_PLAYBACK_BLOCKED,z.MAJOR_EVENT],[U.IVS_PLAYER_ERROR,z.MAJOR_EVENT],[U.IVS_PLAYER_RECOVERABLE_ERROR,z.MAJOR_EVENT],[U.IVS_PLAYER_WORKER_ERROR,z.MAJOR_EVENT],[U.IVS_PLAYER_NETWORK_UNAVAILABLE,z.MAJOR_EVENT],[U.LIVESTREAM_LATENCY,z.MAJOR_EVENT],[U.IVS_PLAYER_ANALYTICS_EVENT,z.MINOR_EVENT],[U.IVS_PLAYER_PLAYBACK_RATE_CHANGED,z.MINOR_EVENT],[U.IVS_PLAYER_QUALITY_CHANGED,z.MINOR_EVENT],[U.IVS_PLAYER_INITIALIZED,z.MINOR_EVENT]]);class Cy{constructor(){m(this,"events"),this.events=[]}add(e){this.events.push(e)}flush(){return{entries:this.events.splice(0,25)}}}class Iy extends _t{constructor({logger:e,peerId:r,apiHostnames:n}){super(),m(this,"logger"),m(this,"peerId"),m(this,"eventStore"),m(this,"apiEndpoint"),this.logger=e,this.peerId=r,this.apiEndpoint=`https://${n.daCollector}/api/v1/message`,this.eventStore=new Cy}sendEventsChunkToServer(e){return u(this,null,function*(){var r;const n={payload:e,peerId:this.peerId};try{return yield fetch(this.apiEndpoint,{method:"POST",body:JSON.stringify(n)}),!0}catch(i){return this.logger.error("callStats::sendEventsChunkToServer::catch",{error:i}),(r=e.entries)==null||r.forEach(s=>{this.eventStore.add(s)}),!1}})}callEvent(e){e.timestamp=new Date,this.eventStore.add(e),this.emit(e.event,e.metaData),wy.get(e.event)===z.MAJOR_EVENT&&this.flush()}flush(){return u(this,null,function*(){var e;const r=this.eventStore.flush();return(e=r==null?void 0:r.entries)!=null&&e.length?(yield this.sendEventsChunkToServer(r),!0):!1})}}var qu;(function(t){t.CHROMIUM="chromum",t.FIREFOX="firefox",t.SAFARI="safari"})(qu||(qu={}));const ls={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var Vt;(function(t){t.AUDIO="AUDIO",t.VIDEO="VIDEO",t.SPEAKER="SPEAKER",t.SCREENSHARE="SCREENSHARE"})(Vt||(Vt={}));var Ku;(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"})(Ku||(Ku={}));const zu=240,Yu=720,Qu=8,Xu=3,Do=10,Oo=.02,No=.03;function yr({stat:t,weight:e,rangeMin:r,rangeMax:n,rangeRankingDirection:i}){return t==null?e:r===n?i==="UP"?t<=r?e:0:t>=n?e:0:i==="UP"?(1-Math.max(Math.min(n,Math.abs(t))-r,0)/(n-r))*e:i==="DOWN"?Math.max(Math.min(n,Math.abs(t))-r,0)/(n-r)*e:e}function Zu({isLowQualityVideo:t,isVideoStuck:e,isVideoLagging:r,jitterQuality:n,packetsLostQuality:i}){const s=.8*((t?.85:1)*(r?.7:1)*(e?.5:1))+.2*(n*i);return Math.round((s+Number.EPSILON)*100)/100}function eh({packetsLost:t,packetsSent:e}){return e>0?t*100/e:0}function th({packetsLost:t,packetsSent:e,jitter:r}){const n=yr({stat:eh({packetsLost:t,packetsSent:e}),weight:.7,rangeMin:0,rangeMax:Do,rangeRankingDirection:"UP"}),i=yr({stat:r,weight:.3,rangeMin:Oo,rangeMax:No,rangeRankingDirection:"UP"});return n+i}function Ry({frameWidth:t,isScreenShare:e}){return t<(e?Yu:zu)}function Py({framesPerSecond:t,isScreenShare:e}){return t<(e?Xu:Qu)}function Ay({framesEncoded:t}){return t===0}function rh({frameWidth:t,framesPerSecond:e,packetsLost:r,packetsSent:n,jitter:i,isScreenShare:s,framesEncoded:o}){const a=yr({stat:eh({packetsLost:r,packetsSent:n}),weight:1,rangeMin:0,rangeMax:Do,rangeRankingDirection:"UP"}),d=yr({stat:i,weight:1,rangeMin:Oo,rangeMax:No,rangeRankingDirection:"UP"}),h=Ry({frameWidth:t,isScreenShare:s}),p=Py({framesPerSecond:e,isScreenShare:s}),f=Ay({framesEncoded:o,isScreenShare:s});return Zu({isLowQualityVideo:h,isVideoLagging:p,isVideoStuck:f,jitterQuality:d,packetsLostQuality:a})}function nh({packetsLost:t,packetsReceived:e}){return e+t>0?t*100/(e+t):0}function ih({concealmentEvents:t,packetsLost:e,packetsReceived:r,jitter:n}){const i=yr({stat:t,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),s=.5,o=yr({stat:nh({packetsLost:e,packetsReceived:r}),weight:s,rangeMin:0,rangeMax:Do,rangeRankingDirection:"UP"}),a=yr({stat:n,weight:.3,rangeMin:Oo,rangeMax:No,rangeRankingDirection:"UP"});return i+o+a}function My({framesDecoded:t}){return t===0}function Dy({framesPerSecond:t,isScreenShare:e}){return t<(e?Xu:Qu)}function Oy({frameWidth:t,isScreenShare:e}){return t<(e?Yu:zu)}function sh({frameWidth:t,framesPerSecond:e,packetsLost:r,packetsReceived:n,jitter:i,isScreenShare:s,framesDecoded:o}){const a=yr({stat:nh({packetsLost:r,packetsReceived:n}),weight:1,rangeMin:0,rangeMax:Do,rangeRankingDirection:"UP"}),d=yr({stat:i,weight:1,rangeMin:Oo,rangeMax:No,rangeRankingDirection:"UP"}),h=Oy({frameWidth:t,isScreenShare:s}),p=Dy({framesPerSecond:e,isScreenShare:s}),f=My({framesDecoded:o,isScreenShare:s});return Zu({isLowQualityVideo:h,isVideoLagging:p,isVideoStuck:f,jitterQuality:d,packetsLostQuality:a})}class Er{constructor(e){m(this,"pc1"),m(this,"pc2"),m(this,"constrainVideoBitrateKbps"),m(this,"constrainOfferToRemoveVideoFec",!1),m(this,"iceCandidateFilter");const r=new RTCPeerConnection(e),n=new RTCPeerConnection(e);this.pc1=r,this.pc2=n,this.iceCandidateFilter=Er.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 r="candidate:",n=e.indexOf(r)+r.length,i=e.substr(n).split(" ");return{type:i[7],protocol:i[2],address:i[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,r){if(r.candidate){const n=Er.parseCandidate(r.candidate.candidate);this.iceCandidateFilter(n)&&e.addIceCandidate(r.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
9
+ `},Bn=Sh,Ky=zy,Yy=Ky,Md=Bn.parse;Bn.parseParams,Bn.parseFmtpConfig,Bn.parsePayloads,Bn.parseRemoteCandidates,Bn.parseImageAttributes,Bn.parseSimulcastStreamList;var Qy=Object.defineProperty,Xy=Object.defineProperties,Zy=Object.getOwnPropertyDescriptors,ho=Object.getOwnPropertySymbols,eS=Object.getPrototypeOf,Th=Object.prototype.hasOwnProperty,kh=Object.prototype.propertyIsEnumerable,tS=Reflect.get,rS=Math.pow,Dd=(t,e,r)=>e in t?Qy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,U=(t,e)=>{for(var r in e||(e={}))Th.call(e,r)&&Dd(t,r,e[r]);if(ho)for(var r of ho(e))kh.call(e,r)&&Dd(t,r,e[r]);return t},X=(t,e)=>Xy(t,Zy(e)),po=(t,e)=>{var r={};for(var n in t)Th.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&ho)for(var n of ho(t))e.indexOf(n)<0&&kh.call(t,n)&&(r[n]=t[n]);return r},f=(t,e,r)=>(Dd(t,typeof e!="symbol"?e+"":e,r),r),Od=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},c=(t,e,r)=>(Od(t,e,"read from private field"),r?r.call(t):e.get(t)),T=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},S=(t,e,r,n)=>(Od(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),Je=(t,e,r)=>(Od(t,e,"access private method"),r),nS=(t,e,r)=>tS(eS(t),r,e),u=(t,e,r)=>new Promise((n,i)=>{var s=d=>{try{o(r.next(d))}catch(h){i(h)}},a=d=>{try{o(r.throw(d))}catch(h){i(h)}},o=d=>d.done?n(d.value):Promise.resolve(d.value).then(s,a);o((r=r.apply(t,e)).next())}),_h=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function iS(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ht={},sS={get exports(){return ht},set exports(t){ht=t}},Ri=typeof Reflect=="object"?Reflect:null,bh=Ri&&typeof Ri.apply=="function"?Ri.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},mo;Ri&&typeof Ri.ownKeys=="function"?mo=Ri.ownKeys:Object.getOwnPropertySymbols?mo=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:mo=function(t){return Object.getOwnPropertyNames(t)};function aS(t){console&&console.warn&&console.warn(t)}var wh=Number.isNaN||function(t){return t!==t};function Ee(){Ee.init.call(this)}sS.exports=Ee,ht.once=lS,Ee.EventEmitter=Ee,Ee.prototype._events=void 0,Ee.prototype._eventsCount=0,Ee.prototype._maxListeners=void 0;var Ih=10;function fo(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(Ee,"defaultMaxListeners",{enumerable:!0,get:function(){return Ih},set:function(t){if(typeof t!="number"||t<0||wh(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Ih=t}}),Ee.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},Ee.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||wh(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 Ch(t){return t._maxListeners===void 0?Ee.defaultMaxListeners:t._maxListeners}Ee.prototype.getMaxListeners=function(){return Ch(this)},Ee.prototype.emit=function(t){for(var e=[],r=1;r<arguments.length;r++)e.push(arguments[r]);var n=t==="error",i=this._events;if(i!==void 0)n=n&&i.error===void 0;else if(!n)return!1;if(n){var s;if(e.length>0&&(s=e[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var o=i[t];if(o===void 0)return!1;if(typeof o=="function")bh(o,this,e);else for(var d=o.length,h=Dh(o,d),r=0;r<d;++r)bh(h[r],this,e);return!0};function Ph(t,e,r,n){var i,s,a;if(fo(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),a=s[e]),a===void 0)a=s[e]=r,++t._eventsCount;else if(typeof a=="function"?a=s[e]=n?[r,a]:[a,r]:n?a.unshift(r):a.push(r),i=Ch(t),i>0&&a.length>i&&!a.warned){a.warned=!0;var o=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");o.name="MaxListenersExceededWarning",o.emitter=t,o.type=e,o.count=a.length,aS(o)}return t}Ee.prototype.addListener=function(t,e){return Ph(this,t,e,!1)},Ee.prototype.on=Ee.prototype.addListener,Ee.prototype.prependListener=function(t,e){return Ph(this,t,e,!0)};function oS(){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 Rh(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=oS.bind(n);return i.listener=r,n.wrapFn=i,i}Ee.prototype.once=function(t,e){return fo(e),this.on(t,Rh(this,t,e)),this},Ee.prototype.prependOnceListener=function(t,e){return fo(e),this.prependListener(t,Rh(this,t,e)),this},Ee.prototype.removeListener=function(t,e){var r,n,i,s,a;if(fo(e),n=this._events,n===void 0)return this;if(r=n[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete n[t],n.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(i=-1,s=r.length-1;s>=0;s--)if(r[s]===e||r[s].listener===e){a=r[s].listener,i=s;break}if(i<0)return this;i===0?r.shift():cS(r,i),r.length===1&&(n[t]=r[0]),n.removeListener!==void 0&&this.emit("removeListener",t,a||e)}return this},Ee.prototype.off=Ee.prototype.removeListener,Ee.prototype.removeAllListeners=function(t){var e,r,n;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[t]),this;if(arguments.length===0){var i=Object.keys(r),s;for(n=0;n<i.length;++n)s=i[n],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=r[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(n=e.length-1;n>=0;n--)this.removeListener(t,e[n]);return this};function Ah(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?dS(i):Dh(i,i.length)}Ee.prototype.listeners=function(t){return Ah(this,t,!0)},Ee.prototype.rawListeners=function(t){return Ah(this,t,!1)},Ee.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Mh.call(t,e)},Ee.prototype.listenerCount=Mh;function Mh(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}Ee.prototype.eventNames=function(){return this._eventsCount>0?mo(this._events):[]};function Dh(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function cS(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function dS(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function lS(t,e){return new Promise(function(r,n){function i(a){t.removeListener(e,s),n(a)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}Oh(t,e,s,{once:!0}),e!=="error"&&uS(t,i,{once:!0})})}function uS(t,e,r){typeof t.on=="function"&&Oh(t,"error",e,r)}function Oh(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var Z;(function(t){t[t.MAJOR_EVENT=0]="MAJOR_EVENT",t[t.MINOR_EVENT=1]="MINOR_EVENT"})(Z||(Z={}));var V;(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"})(V||(V={}));const hS=new Map([[V.PRECALL_TEST_BEGIN,Z.MINOR_EVENT],[V.PRECALL_TEST_COMPLETE,Z.MINOR_EVENT],[V.CALL_JOIN_BEGIN,Z.MAJOR_EVENT],[V.NET_QUALITY_TEST_BEGIN,Z.MINOR_EVENT],[V.NET_QUALITY_TEST_END,Z.MINOR_EVENT],[V.WEBSOCKET_CONNECTED,Z.MINOR_EVENT],[V.TRANSPORT_CONNECTED,Z.MAJOR_EVENT],[V.AUDIO_ON,Z.MINOR_EVENT],[V.AUDIO_OFF,Z.MINOR_EVENT],[V.VIDEO_ON,Z.MINOR_EVENT],[V.VIDEO_OFF,Z.MINOR_EVENT],[V.PARTICIPANT_ROLE,Z.MINOR_EVENT],[V.PING_STAT,Z.MAJOR_EVENT],[V.DISCONNECT,Z.MAJOR_EVENT],[V.RECONNECT_ATTEMPT,Z.MAJOR_EVENT],[V.SCREENSHARE_START_REQUESTED,Z.MINOR_EVENT],[V.SCREENSHARE_STARTED,Z.MINOR_EVENT],[V.SCREENSHARE_STOPPED,Z.MINOR_EVENT],[V.TAB_CHANGE,Z.MINOR_EVENT],[V.BROWSER_BACKGROUNDED,Z.MINOR_EVENT],[V.BROWSER_FOREGROUNDED,Z.MINOR_EVENT],[V.DOMINANT_SPEAKER,Z.MINOR_EVENT],[V.AUDIO_DEVICES_UPDATES,Z.MINOR_EVENT],[V.VIDEO_DEVICES_UPDATES,Z.MINOR_EVENT],[V.SPEAKER_DEVICES_UPDATES,Z.MINOR_EVENT],[V.SELECTED_MICROHPONE_UPDATE,Z.MINOR_EVENT],[V.SELECTED_CAMERA_UPDATE,Z.MINOR_EVENT],[V.SELECTED_SPEAKER_UPDATE,Z.MINOR_EVENT],[V.MEDIA_PERMISSION,Z.MINOR_EVENT],[V.LEGACY_SWITCH,Z.MINOR_EVENT],[V.AUDIO_PLAY_FAILED,Z.MINOR_EVENT],[V.VIDEO_PLAY_FAILED,Z.MINOR_EVENT],[V.AUDIO_TRACK_MUTED,Z.MINOR_EVENT],[V.VIDEO_TRACK_MUTED,Z.MINOR_EVENT],[V.IVS_PLAYER_REBUFFERING,Z.MAJOR_EVENT],[V.IVS_PLAYER_AUDIO_BLOCKED,Z.MAJOR_EVENT],[V.IVS_PLAYER_PLAYBACK_BLOCKED,Z.MAJOR_EVENT],[V.IVS_PLAYER_ERROR,Z.MAJOR_EVENT],[V.IVS_PLAYER_RECOVERABLE_ERROR,Z.MAJOR_EVENT],[V.IVS_PLAYER_WORKER_ERROR,Z.MAJOR_EVENT],[V.IVS_PLAYER_NETWORK_UNAVAILABLE,Z.MAJOR_EVENT],[V.LIVESTREAM_LATENCY,Z.MAJOR_EVENT],[V.IVS_PLAYER_ANALYTICS_EVENT,Z.MINOR_EVENT],[V.IVS_PLAYER_PLAYBACK_RATE_CHANGED,Z.MINOR_EVENT],[V.IVS_PLAYER_QUALITY_CHANGED,Z.MINOR_EVENT],[V.IVS_PLAYER_INITIALIZED,Z.MINOR_EVENT],[V.EXPECTED_VIDEO_RESOLUTION,Z.MINOR_EVENT],[V.EXPECTED_SCREENSHARE_RESOLUTION,Z.MINOR_EVENT]]);class pS{constructor(){f(this,"events"),this.events=[]}add(e){this.events.push(e)}flush(){return{entries:this.events.splice(0,25)}}}class mS extends ht{constructor({logger:e,peerId:r,apiHostnames:n}){super(),f(this,"logger"),f(this,"peerId"),f(this,"eventStore"),f(this,"apiEndpoint"),this.logger=e,this.peerId=r,this.apiEndpoint=`https://${n.daCollector}/api/v1/message`,this.eventStore=new pS}sendEventsChunkToServer(e){return u(this,null,function*(){var r;const n={payload:e,peerId:this.peerId};try{return yield fetch(this.apiEndpoint,{method:"POST",body:JSON.stringify(n)}),!0}catch(i){return this.logger.error("callStats::sendEventsChunkToServer::catch",{error:i}),(r=e.entries)==null||r.forEach(s=>{this.eventStore.add(s)}),!1}})}callEvent(e){e.timestamp=new Date,this.eventStore.add(e),this.emit(e.event,e.metaData),hS.get(e.event)===Z.MAJOR_EVENT&&this.flush()}flush(){return u(this,null,function*(){var e;const r=this.eventStore.flush();return(e=r==null?void 0:r.entries)!=null&&e.length?(yield this.sendEventsChunkToServer(r),!0):!1})}}var Nh;(function(t){t.CHROMIUM="chromum",t.FIREFOX="firefox",t.SAFARI="safari"})(Nh||(Nh={}));const Ts={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var Qt;(function(t){t.AUDIO="AUDIO",t.VIDEO="VIDEO",t.SPEAKER="SPEAKER",t.SCREENSHARE="SCREENSHARE"})(Qt||(Qt={}));var Lh;(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"})(Lh||(Lh={}));function nn(t){return t?t.split(".").slice(0,2).concat(["0","0"]).join("."):""}function go({packetsLost:t,packetsSent:e}){return e>0?t*100/e:0}function vo({packetsLost:t,packetsReceived:e}){return e+t>0?t*100/(e+t):0}const xh=240,Fh=720,Vh=8,Uh=3,yo=10,So=.02,Eo=.03;function Pr({stat:t,weight:e,rangeMin:r,rangeMax:n,rangeRankingDirection:i}){return t==null?e:r===n?i==="UP"?t<=r?e:0:t>=n?e:0:i==="UP"?(1-Math.max(Math.min(n,Math.abs(t))-r,0)/(n-r))*e:i==="DOWN"?Math.max(Math.min(n,Math.abs(t))-r,0)/(n-r)*e:e}function Bh({isLowQualityVideo:t,isVideoStuck:e,isVideoLagging:r,jitterQuality:n,packetsLostQuality:i}){const s=.8*((t?.85:1)*(r?.7:1)*(e?.5:1))+.2*(n*i);return Math.round((s+Number.EPSILON)*100)/100}function jh({packetsLost:t,packetsSent:e}){return e>0?t*100/e:0}function Hh({packetsLost:t,packetsSent:e,jitter:r}){const n=Pr({stat:jh({packetsLost:t,packetsSent:e}),weight:.7,rangeMin:0,rangeMax:yo,rangeRankingDirection:"UP"}),i=Pr({stat:r,weight:.3,rangeMin:So,rangeMax:Eo,rangeRankingDirection:"UP"});return n+i}function fS({frameWidth:t,isScreenShare:e}){return t<(e?Fh:xh)}function gS({framesPerSecond:t,isScreenShare:e}){return t<(e?Uh:Vh)}function vS({framesEncoded:t}){return t===0}function Wh({frameWidth:t,framesPerSecond:e,packetsLost:r,packetsSent:n,jitter:i,isScreenShare:s,framesEncoded:a}){const o=Pr({stat:jh({packetsLost:r,packetsSent:n}),weight:1,rangeMin:0,rangeMax:yo,rangeRankingDirection:"UP"}),d=Pr({stat:i,weight:1,rangeMin:So,rangeMax:Eo,rangeRankingDirection:"UP"}),h=fS({frameWidth:t,isScreenShare:s}),p=gS({framesPerSecond:e,isScreenShare:s}),m=vS({framesEncoded:a,isScreenShare:s});return Bh({isLowQualityVideo:h,isVideoLagging:p,isVideoStuck:m,jitterQuality:d,packetsLostQuality:o})}function $h({packetsLost:t,packetsReceived:e}){return e+t>0?t*100/(e+t):0}function Jh({concealmentEvents:t,packetsLost:e,packetsReceived:r,jitter:n}){const i=Pr({stat:t,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),s=.5,a=Pr({stat:$h({packetsLost:e,packetsReceived:r}),weight:s,rangeMin:0,rangeMax:yo,rangeRankingDirection:"UP"}),o=Pr({stat:n,weight:.3,rangeMin:So,rangeMax:Eo,rangeRankingDirection:"UP"});return i+a+o}function yS({framesDecoded:t}){return t===0}function SS({framesPerSecond:t,isScreenShare:e}){return t<(e?Uh:Vh)}function ES({frameWidth:t,isScreenShare:e}){return t<(e?Fh:xh)}function Gh({frameWidth:t,framesPerSecond:e,packetsLost:r,packetsReceived:n,jitter:i,isScreenShare:s,framesDecoded:a}){const o=Pr({stat:$h({packetsLost:r,packetsReceived:n}),weight:1,rangeMin:0,rangeMax:yo,rangeRankingDirection:"UP"}),d=Pr({stat:i,weight:1,rangeMin:So,rangeMax:Eo,rangeRankingDirection:"UP"}),h=ES({frameWidth:t,isScreenShare:s}),p=SS({framesPerSecond:e,isScreenShare:s}),m=yS({framesDecoded:a,isScreenShare:s});return Bh({isLowQualityVideo:h,isVideoLagging:p,isVideoStuck:m,jitterQuality:d,packetsLostQuality:o})}class Rr{constructor(e){f(this,"pc1"),f(this,"pc2"),f(this,"constrainVideoBitrateKbps"),f(this,"constrainOfferToRemoveVideoFec",!1),f(this,"iceCandidateFilter");const r=new RTCPeerConnection(e),n=new RTCPeerConnection(e);this.pc1=r,this.pc2=n,this.iceCandidateFilter=Rr.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 r="candidate:",n=e.indexOf(r)+r.length,i=e.substr(n).split(" ");return{type:i[7],protocol:i[2],address:i[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,r){if(r.candidate){const n=Rr.parseCandidate(r.candidate.candidate);this.iceCandidateFilter(n)&&e.addIceCandidate(r.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
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
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 u(this,null,function*(){const[e,r]=yield Promise.all([this.pc1.getStats(),this.pc2.getStats()]);let n,i;if(e.forEach(s=>{s.type==="candidate-pair"&&s.nominated===!0&&s.bytesSent>0&&(n=s)}),r.forEach(s=>{s.type==="candidate-pair"&&s.nominated===!0&&s.bytesReceived>0&&(i=s)}),n&&i)try{if(n.currentRoundTripTime&&i.currentRoundTripTime)return{rtt:n.currentRoundTripTime,backendRTT:i.currentRoundTripTime};const s=(i.lastPacketReceivedTimestamp-n.lastPacketSentTimestamp)/1e3;return{rtt:s,backendRTT:s}}catch(s){return}})}close(){this.pc1.close(),this.pc2.close()}}class oh extends _t{constructor(e){super(),m(this,"call"),m(this,"timeOut"),this.call=new Er(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 Ny=8,Ly=1/1e3;class xy extends oh{constructor(e){super(e),m(this,"senderChannel"),m(this,"recieveChannel"),m(this,"startTime"),m(this,"lastBitrateMeasureTime"),m(this,"sentPayloadBytes",0),m(this,"recievedPayloadBytes",0),m(this,"lastReceivedPayloadBytes",0),m(this,"stopSending",!1),m(this,"testProgress",0),m(this,"samplePacket",""),m(this,"finalBitrateSum",0),m(this,"bitRateSampels",0),m(this,"maxNumberOfPacketsToSend",0),m(this,"bytesToKeepBuffered",0),m(this,"testDurationSeconds",5),this.call.setIceCandidateFilter(Er.isNotHostCandidate),this.senderChannel=this.call.pc1.createDataChannel(null);for(let r=0;r<262144;r+=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 n=0;n!==this.maxNumberOfPacketsToSend&&!(this.senderChannel.bufferedAmount>=this.bytesToKeepBuffered);n+=1){this.sentPayloadBytes+=this.samplePacket.length;try{this.senderChannel.send(this.samplePacket)}catch(i){}}const r=e.getTime()-this.startTime.getTime();r>=1e3*this.testDurationSeconds?(this.stopSending=!0,this.testProgress=100):(this.testProgress=r/(10*this.testDurationSeconds),setTimeout(this.sendingStep.bind(this),1))}onMessageRecieved(e){this.recievedPayloadBytes+=e.data.length;const r=new Date,n=r.getTime()-this.lastBitrateMeasureTime.getTime();if(n>=1e3){const i=(this.recievedPayloadBytes-this.lastReceivedPayloadBytes)*Ny/(n/1e3);this.finalBitrateSum+=i,this.bitRateSampels+=1,this.lastReceivedPayloadBytes=this.recievedPayloadBytes,this.lastBitrateMeasureTime=r}if(this.stopSending&&this.sentPayloadBytes===this.recievedPayloadBytes){const i=this.finalBitrateSum/this.bitRateSampels;this.testComplete({throughput:Math.round(i*Ly)})}}testComplete(e){this.call.getRoundTripTime().then(({rtt:r,backendRTT:n})=>super.testComplete({RTT:r,backendRTT:n,throughput:e.throughput}))}onRecieverChannel(e){this.recieveChannel=e.channel,this.recieveChannel.addEventListener("message",this.onMessageRecieved.bind(this))}}class Xc extends oh{constructor(e,r=Er.noFilter){super(e),m(this,"ch1"),m(this,"ch2"),this.call.setIceCandidateFilter(r);const n=this.call.pc1.createDataChannel(null);this.ch1=n,n.addEventListener("open",()=>{n.send("hello")}),n.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(r){}}dataChannelHandler(e){const r=e.channel;this.ch2=r,r.addEventListener("message",this.onCh2Recieve.bind(this))}hangup(e){this.testFailed(e)}}class Fy extends Xc{constructor(e){super(e,Er.isHost)}}class Uy extends Xc{constructor(e){super(e,Er.isRelay)}}class Vy extends Xc{constructor(e){super(e,Er.isReflexive)}}class By{constructor(){m(this,"ipInformation",null)}getIPDetails(e){return u(this,arguments,function*({peerId:r,apiHostnames:n}){var i;if(!this.ipInformation){try{const o=`https://${n.location}`,a=yield(yield fetch(o)).json();if(((i=a.loc)==null?void 0:i.length)>5)return this.ipInformation=a,a;throw Error("Insufficient data")}catch(o){}const s=yield fetch(`https://${n.locationLegacy}/?token=3c493932b0624c&peerId=${r}`,{method:"POST"});this.ipInformation=yield s.json()}return this.ipInformation})}resetCache(){this.ipInformation=null}}const Zc=new By,ah=[{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 ch(t){const[e,r]=t.split(",");return{coords:{latitude:Number(e),longitude:Number(r)}}}class dh{constructor(){m(this,"transport"),m(this,"candidatePair"),m(this,"outboundVideoRtp",new Map),m(this,"inboundVideoRtp",new Map),m(this,"outboundAudioRtp",new Map),m(this,"inboundAudioRtp",new Map),m(this,"remoteInboundRtp",new Map),m(this,"producerStreamMap",new Map),m(this,"consumerStreamMap",new Map),m(this,"staleProducerStreamMap",!1),m(this,"staleConsumerStreamMap",!1)}}class lh extends Mo{constructor(){super(),m(this,"observer"),m(this,"outboundProducerMap",new Map),m(this,"inboundConsumerMap",new Map),m(this,"consumerPeerIdMap",new Map),m(this,"pausedConsumerMap",new Map),m(this,"pausedProducerMap",new Map),m(this,"overallProducingTransportsStatsMap",{}),m(this,"overallConsumingTransportsStatsMap",{}),m(this,"overallConsumersStatsMap",{}),m(this,"overallProducersStatsMap",{}),m(this,"videoProducerToStatsMap",new Map),m(this,"audioProducerToStatsMap",new Map),m(this,"videoConsumerToStatsMap",new Map),m(this,"audioConsumerToStatsMap",new Map),m(this,"consumerIdsWithFreezedVideo",new Set),m(this,"consumerIdsWithFreezedAudio",new Set),m(this,"producerIdsWithFreezedVideo",new Set),m(this,"producerIdsWithFreezedAudio",new Set),m(this,"freezedProducingTransportIds",new Set),m(this,"freezedConsumingTransportIds",new Set),m(this,"screenShareProducers",new Set),m(this,"screenShareConsumers",new Set),m(this,"ipDetails"),m(this,"callStatsInstance"),this.observer=new Mo}registerProducer(e){return u(this,null,function*(){yield this.generateProducerStreamMap(e),e.observer.on("close",this.deregisterProducer.bind(this,e)),e.observer.on("pause",this.pauseProducer.bind(this,e.id)),e.observer.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,r,n){var i,s;const o=((s=(i=this==null?void 0:this.callStatsInstance)==null?void 0:i.consumerSharedMediaStatesMap)==null?void 0:s.get(e))||{};r.totalVideoPacketsReceived===n.packetsReceived?(this.consumerIdsWithFreezedVideo.add(e),this.callStatsInstance&&o.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","pause",e))):(r.totalVideoPacketsReceived=n.packetsReceived,this.consumerIdsWithFreezedVideo.has(e)&&(this.consumerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&o.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","resume",e))))}processInboundConsumerAudioStats(e,r,n){var i,s;const o=((s=(i=this==null?void 0:this.callStatsInstance)==null?void 0:i.consumerSharedMediaStatesMap)==null?void 0:s.get(e))||{};r.totalAudioPacketsReceived===n.packetsReceived?(this.consumerIdsWithFreezedAudio.add(e),this.callStatsInstance&&o.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","pause",e))):(r.totalAudioPacketsReceived=n.packetsReceived,this.consumerIdsWithFreezedAudio.has(e)&&(this.consumerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&o.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","resume",e))))}processOutboundProducerVideoStats(e,r,n){var i;const s=((i=this==null?void 0:this.callStatsInstance)==null?void 0:i.currentUserMediaStates)||{};r.totalVideoPacketsSent===n.packetsSent?(this.producerIdsWithFreezedVideo.add(e),this.callStatsInstance&&s.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","pause",e))):(r.totalVideoPacketsSent=n.packetsSent,this.producerIdsWithFreezedVideo.has(e)&&(this.producerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&s.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","resume",e))))}processOutboundProducerAudioStats(e,r,n){var i;const s=((i=this==null?void 0:this.callStatsInstance)==null?void 0:i.currentUserMediaStates)||{};r.totalAudioPacketsSent===n.packetsSent?(this.producerIdsWithFreezedAudio.add(e),this.callStatsInstance&&s.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","pause",e))):(r.totalAudioPacketsSent=n.packetsSent,this.producerIdsWithFreezedAudio.has(e)&&(this.producerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&s.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","resume",e))))}processProducingTransportStats(e,r,n){var i;const s=((i=this==null?void 0:this.callStatsInstance)==null?void 0:i.currentUserMediaStates)||{},{audio:o,video:a,screen:d}=s,h=o||a||d;r.totalPacketsSent===n.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))):(r.totalPacketsSent=n.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,r,n){var i,s;const o=!!Array.from(((s=(i=this==null?void 0:this.callStatsInstance)==null?void 0:i.consumerSharedMediaStatesMap)==null?void 0:s.values())||[]).reduce((a,d)=>a||d.audio||d.video||d.screen,!1);r.totalPacketsReceived===n.packetsSent?(this.freezedConsumingTransportIds.add(e),this.callStatsInstance&&o&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","pause",e))):(r.totalPacketsReceived=n.packetsSent,this.freezedConsumingTransportIds.has(e)&&(this.freezedConsumingTransportIds.delete(e),this.callStatsInstance&&o&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","resume",e))))}registerConsumer(e){return u(this,null,function*(){yield this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.observer.on("close",this.deregisterConsumer.bind(this,e)),e.observer.on("pause",this.pauseConsumer.bind(this,e.id)),e.observer.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,r=!1){return u(this,null,function*(){const n=yield e.getStats(),i=r?this.getProducerStatsFromReport(this.parseRTCReport(n,["outbound-rtp","remote-inbound-rtp"],!1,e.id))[0]:void 0;for(const s of n.values())switch(s.type){case"outbound-rtp":{this.outboundProducerMap.set(s.id,e.id);break}}return i})}generateConsumerStreamMap(e,r=!1){return u(this,null,function*(){const n=yield e.getStats(),i=r?this.getConsumerStatsFromReport(this.parseRTCReport(n,["inbound-rtp"],!1,e.id))[0]:void 0;for(const s of n.values())switch(s.type){case"inbound-rtp":{this.inboundConsumerMap.set(s.id,e.id);break}}return i})}deregisterProducer(e){this.outboundProducerMap.forEach((r,n)=>{r===e.id&&this.outboundProducerMap.delete(n)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.inboundConsumerMap.forEach((r,n)=>{r===e.id&&this.inboundConsumerMap.delete(n)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var r;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(r=e.relayProtocol)!=null?r:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}getWorkingSimulcastVideoStats(e){return e.find(r=>{const n=r.framesEncoded>0,i=r.packetsSent>0,s=r.frameWidth&&r.frameHeight;return n&&i&&!!s})||e[e.length-1]}parseRTCReport(e,r=[],n=!1,i=void 0,s=void 0){var o,a,d,h,p,f,g;const E=e,v=new dh,R=r.length?new Set(r):void 0,A=[],L=[],F=[],W=new Map,H=new Map;for(const I of E.values()){if(R){if(R.size===0)break;if(R.has(I.type))n&&R.delete(I.type);else continue}switch(I.type){case"local-candidate":{A.push(this.getIceCandidateStats(I));break}case"remote-candidate":{L.push(this.getIceCandidateStats(I));break}case"candidate-pair":{const{nominated:S}=I,{selected:P}=I,N=I,ce={nominated:S!=null?S:P,currentRoundTripTime:N.currentRoundTripTime,totalRoundTripTime:N.totalRoundTripTime,bytesReceived:N.bytesReceived,bytesSent:N.bytesSent,availableOutgoingBitrate:N.availableOutgoingBitrate,lastPacketReceivedTimestamp:N.lastPacketReceivedTimestamp,lastPacketSentTimestamp:N.lastPacketSentTimestamp,localCandidateId:N.localCandidateId,remoteCandidateId:N.remoteCandidateId,bytesDiscardedOnSend:N.bytesDiscardedOnSend,packetsSent:N.packetsSent,packetsReceived:N.packetsReceived,packetsDiscardedOnSend:N.packetsDiscardedOnSend};F.push(ce),(I.nominated===!0||I.selected===!0)&&(v.candidatePair=ce);break}case"transport":{const S=I;s&&(s.producing&&(this.overallProducingTransportsStatsMap[s.id]||(this.overallProducingTransportsStatsMap[s.id]={totalPacketsSent:0})),s.consuming&&(this.overallConsumingTransportsStatsMap[s.id]||(this.overallConsumingTransportsStatsMap[s.id]={totalPacketsReceived:0})));const P={bytesReceived:S.bytesReceived,bytesSent:S.bytesSent,packetsSent:S.packetsSent,packetsReceived:S.packetsReceived,dtlsCipher:S.dtlsCipher,dtlsState:S.dtlsState,iceRole:S.iceRole};if(v.transport=P,s){if(s.producing){const N=this.overallProducingTransportsStatsMap[s.id];this.processProducingTransportStats(s.id,N,P)}if(s.consuming){const N=this.overallConsumingTransportsStatsMap[s.id];this.processConsumingTransportStats(s.id,N,P)}}break}case"remote-inbound-rtp":{const S=I,P={jitter:S.jitter,fractionLost:S.fractionLost,roundTripTime:S.roundTripTime,roundTripTimeMeasurements:S.roundTripTimeMeasurements,totalRoundTripTime:S.totalRoundTripTime,packetsLost:S.packetsLost};v.remoteInboundRtp.set(S.localId,P);break}case"outbound-rtp":{const S=I,P=i||this.outboundProducerMap.get(I.id),N=this.pausedProducerMap.get(P);if(N){if(N.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const ce=this.overallProducersStatsMap[P];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.outboundProducerMap.has(I.id)){v.staleProducerStreamMap=!0;break}const Le=this.callStatsInstance.producers.get(P);if(((o=Le==null?void 0:Le.track)==null?void 0:o.readyState)==="ended")break;v.producerStreamMap.has(P)||v.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const $={bytesSent:S.bytesSent,packetsSent:S.packetsSent,nackCount:S.nackCount,ssrc:S.ssrc,mid:S.mid};if(S.mediaType==="video"||S.kind==="video"){if(S.decoderImplementation==="unknown")break;const x=S,Se=V({frameHeight:x.frameHeight,frameWidth:x.frameWidth,framesEncoded:x.framesEncoded,framesDropped:x.framesDropped,framesPerSecond:x.framesPerSecond,framesSent:x.framesSent,keyFramesEncoded:x.keyFramesEncoded,firCount:x.firCount,encoderImplementation:x.encoderImplementation,hugeFramesSent:x.hugeFramesSent,pliCount:x.pliCount,qpSum:x.qpSum,qualityLimitationDurations:x.qualityLimitationDurations,qualityLimitationReason:x.qualityLimitationReason,qualityLimitationResolutionChanges:x.qualityLimitationResolutionChanges,totalEncodeTime:x.targetBitrate,totalPacketSendDelay:x.totalPacketSendDelay,retransmittedBytesSent:x.retransmittedBytesSent,retransmittedPacketsSent:x.retransmittedPacketsSent},$);this.videoProducerToStatsMap.set(P,Se),v.outboundVideoRtp.set(I.id,Se),v.producerStreamMap.get(P).outboundVideoRtpId.push(I.id),this.processOutboundProducerVideoStats(P,ce,Se)}else if(S.mediaType==="audio"||S.kind==="audio"){const x=S,Se=V({retransmittedBytesSent:x.retransmittedBytesSent,retransmittedPacketsSent:x.retransmittedPacketsSent},$);this.audioProducerToStatsMap.set(P,Se),v.outboundAudioRtp.set(I.id,Se),v.producerStreamMap.get(P).outboundAudioRtpId.push(I.id),this.processOutboundProducerAudioStats(P,ce,Se)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}case"inbound-rtp":{const S=I,P=i||this.inboundConsumerMap.get(I.id),N=this.pausedConsumerMap.get(P);if(N){if(N.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(S.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const ce=this.overallConsumersStatsMap[P];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.inboundConsumerMap.has(I.id)){v.staleConsumerStreamMap=!0;break}v.consumerStreamMap.has(P)||v.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Le={bytesReceived:S.bytesReceived,packetsReceived:S.packetsReceived,packetsLost:S.packetsLost,jitter:S.jitter,nackCount:S.nackCount,jitterBufferDelay:S.jitterBufferDelay,jitterBufferEmittedCount:S.jitterBufferEmittedCount,lastPacketReceivedTimestamp:S.lastPacketReceivedTimestamp,ssrc:S.ssrc,mid:S.mid};if(S.mediaType==="video"||S.kind==="video"){if(S.decoderImplementation==="unknown")break;const $=S,x=V({frameHeight:$.frameHeight,frameWidth:$.frameWidth,framesDecoded:$.framesDecoded,framesDropped:$.framesDropped,framesPerSecond:$.framesPerSecond,framesReceived:$.framesReceived,keyFramesDecoded:$.keyFramesDecoded,firCount:$.firCount,decoderImplementation:$.decoderImplementation,pliCount:$.pliCount,totalProcessingDelay:$.totalProcessingDelay},Le);x.score=sh({frameWidth:x.frameWidth||0,framesDecoded:(x.framesDecoded||0)-(((a=this.videoConsumerToStatsMap.get(P))==null?void 0:a.framesDecoded)||0),framesPerSecond:x.framesPerSecond||0,packetsLost:(x.packetsLost||0)-(((d=this.videoConsumerToStatsMap.get(P))==null?void 0:d.packetsLost)||0),packetsReceived:(x.packetsReceived||0)-(((h=this.videoConsumerToStatsMap.get(P))==null?void 0:h.packetsReceived)||0),jitter:x.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),H.set(P,x.score),this.videoConsumerToStatsMap.set(P,x),v.inboundVideoRtp.set(I.id,x),v.consumerStreamMap.get(P).inboundVideoRtpId.push(I.id),this.processInboundConsumerVideoStats(P,ce,x)}else if(S.mediaType==="audio"||S.kind==="audio"){const $=S,x=V({audioLevel:$.audioLevel,concealedSampels:$.concealedSampels,concealmentEvents:$.concealmentEvents,totalAudioEnergy:$.totalAudioEnergy,totalSamplesDuration:$.totalSamplesDuration,totalSamplesReceived:$.totalSamplesReceived},Le);x.score=ih({concealmentEvents:(x.concealmentEvents||0)-(((p=this.audioConsumerToStatsMap.get(P))==null?void 0:p.concealmentEvents)||0),packetsLost:(x.packetsLost||0)-(((f=this.audioConsumerToStatsMap.get(P))==null?void 0:f.packetsLost)||0),packetsReceived:(x.packetsReceived||0)-(((g=this.audioConsumerToStatsMap.get(P))==null?void 0:g.packetsReceived)||0),jitter:x.jitter||0}),H.set(P,x.score),this.audioConsumerToStatsMap.set(P,x),v.inboundAudioRtp.set(I.id,x),v.consumerStreamMap.get(P).inboundAudioRtpId.push(I.id),this.processInboundConsumerAudioStats(P,ce,x)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}}}if(v.producerStreamMap.forEach((I,S)=>{var P,N,ce,Le,$,x,Se,fn,pi,mi,ht;if(I.outboundVideoRtpId.length>0){const Qe=[];I.outboundVideoRtpId.forEach(fo=>{Qe.push(v.outboundVideoRtp.get(fo))});const Xe=this.getWorkingSimulcastVideoStats(Qe);Xe.score=rh({frameWidth:Xe.frameWidth||0,framesPerSecond:Xe.framesPerSecond||0,jitter:((P=Xe.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsSent:(Xe.packetsSent||0)-(((N=this.videoProducerToStatsMap.get(S))==null?void 0:N.packetsSent)||0),packetsLost:(((ce=Xe.remoteData)==null?void 0:ce.packetsLost)||0)-((($=(Le=this.videoProducerToStatsMap.get(S))==null?void 0:Le.remoteData)==null?void 0:$.packetsLost)||0),framesEncoded:(Xe.framesEncoded||0)-(((x=this.videoProducerToStatsMap.get(S))==null?void 0:x.framesEncoded)||0)}),W.set(S,Xe.score)}else if(I.outboundAudioRtpId.length>0){const Qe=v.outboundAudioRtp.get(I.outboundAudioRtpId[0]);Qe.score=th({packetsSent:(Qe.packetsSent||0)-(((Se=this.audioProducerToStatsMap.get(S))==null?void 0:Se.packetsSent)||0),packetsLost:(((fn=Qe.remoteData)==null?void 0:fn.packetsLost)||0)-(((mi=(pi=this.audioProducerToStatsMap.get(S))==null?void 0:pi.remoteData)==null?void 0:mi.packetsLost)||0),jitter:((ht=Qe.remoteData)==null?void 0:ht.jitter)||0}),W.set(S,Qe.score)}}),F.forEach(I=>{const S=A.find(N=>N.id===I.localCandidateId?(I.localCandidateId=N.id,N):null),P=L.find(N=>N.id===I.remoteCandidateId?(I.remoteCandidateId=N.id,N):null);S&&(I.localCandidateType=S.type,I.localCandidateAddress=S.address,I.localCandidatePort=S.port,I.localCandidateProtocol=S.protocol,I.localCandidateUrl=S.url,I.localCandidateNetworkType=S.networkType,I.localCandidateRelatedAddress=S.relatedAddress,I.localCandidateRelatedPort=S.relatedPort),P&&(I.remoteCandidateType=P.type,I.remoteCandidateAddress=P.address,I.remoteCandidatePort=P.port,I.remoteCandidateProtocol=P.protocol,I.remoteCandidateUrl=P.url)}),v.candidatePair&&(v.transport?(v.transport.totalRoundTripTime=v.candidatePair.totalRoundTripTime,v.transport.availableOutgoingBitrate=v.candidatePair.availableOutgoingBitrate,v.transport.roundTripTime=v.candidatePair.currentRoundTripTime):v.transport={bytesReceived:v.candidatePair.bytesReceived,bytesSent:v.candidatePair.bytesSent,totalRoundTripTime:v.candidatePair.totalRoundTripTime,availableOutgoingBitrate:v.candidatePair.availableOutgoingBitrate,roundTripTime:v.candidatePair.currentRoundTripTime}),v.transport&&(v.transport.candidatePairs=F),v.transport&&!v.transport.roundTripTime){let I=0,S=0;v.remoteInboundRtp.forEach((P,N)=>{P.roundTripTime&&P.roundTripTime>I&&(I=P.roundTripTime,S=P.totalRoundTripTime)}),v.transport.roundTripTime=I,v.transport.totalRoundTripTime=S}return H.size>0&&this.observer.safeEmit("consumer_score",H),W.size>0&&this.observer.safeEmit("producer_score",W),v}getProducersReport(e){return u(this,null,function*(){const r=e.map(n=>this.generateProducerStreamMap(n,!0));return r.length>0?Promise.all(r):void 0})}getConsumersReport(e){return u(this,null,function*(){const r=e.map(n=>this.generateConsumerStreamMap(n,!0));return r.length>0?Promise.all(r):void 0})}getTransportReport(e){return u(this,null,function*(){return e.getStats()})}getProcessedStats(e,r,n){return u(this,null,function*(){const i=yield this.getTransportReport(e),s={producing:n,consuming:r,id:e.id},o=i,a=this.parseRTCReport(o,["transport","candidate-pair","inbound-rtp","outbound-rtp","remote-inbound-rtp","local-candidate","remote-candidate"],!1,void 0,s);if(!a)return;const d={stats:a.transport,transportId:e.id,consuming:r,producing:n},h=a.staleProducerStreamMap?void 0:this.getProducerStatsFromReport(a),p=a.staleConsumerStreamMap?void 0:this.getConsumerStatsFromReport(a);return{transportReport:d,producerReport:h,consumerReport:p}})}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((n,i)=>{var s,o;r.push({producerId:i,videoStats:n.outboundVideoRtpId.map(a=>e.outboundVideoRtp.get(a)),audioStats:n.outboundAudioRtpId.map(a=>e.outboundAudioRtp.get(a)),appData:((o=(s=this.callStatsInstance.producers)==null?void 0:s.get(i))==null?void 0:o.appData)||null})})}catch(n){this.callStatsInstance.logger.error("callStats::measurements::getProducerStatsFromReport",{error:{reason:n.reason,message:n.message}})}return r}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((n,i)=>{const{peerId:s,producerId:o,appData:a}=this.consumerPeerIdMap.get(i);r.push({consumerId:i,peerId:s,producerId:o,appData:a,videoStats:n.inboundVideoRtpId.map(d=>e.inboundVideoRtp.get(d)),audioStats:n.inboundAudioRtpId.map(d=>e.inboundAudioRtp.get(d))})})}catch(n){console.error("getConsumersReport: ",n,e)}return r}getUserLocation(){return u(this,null,function*(){return new Promise((e,r)=>{try{navigator.geolocation?navigator.geolocation.getCurrentPosition(n=>{e(n)}):r()}catch(n){r(n)}})})}getConnectivity(e){return u(this,null,function*(){try{const r={iceServers:e||ah},n=new Promise((h,p)=>{try{const f=new Fy(r);f.addListener("done",h),f.addListener("failed",()=>{h({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),i=new Promise((h,p)=>{try{const f=new Uy(r);f.addListener("done",h),f.addListener("failed",()=>{h({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),s=new Promise((h,p)=>{try{const f=new Vy(r);f.addListener("done",h),f.addListener("failed",()=>{h({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),[o,a,d]=yield Promise.all([n,i,s]);return{host:o==null?void 0:o.connectivity,relay:a==null?void 0:a.connectivity,reflexive:d==null?void 0:d.connectivity}}catch(r){return{host:!1,relay:!1,reflexive:!1}}})}getThroughput(e){return u(this,null,function*(){try{const r=yield new Promise((n,i)=>{try{const s={iceServers:e||ah},o=new xy(s);o.addListener("done",n),o.addListener("failed",i),o.start(1e4)}catch(s){i(s)}});return{throughput:r.throughput,fractionalLoss:0,RTT:r.RTT,jitter:0,backendRTT:r.backendRTT}}catch(r){return}})}getIPDetails(){return u(this,null,function*(){var e,r;try{return this.ipDetails||(this.ipDetails=yield Zc.getIPDetails({peerId:(e=this.callStatsInstance)==null?void 0:e.peerId,apiHostnames:(r=this.callStatsInstance)==null?void 0:r.apiHostnames})),this.ipDetails}catch(n){return}})}getNetworkQuality(e){return u(this,null,function*(){const[r,n]=yield Promise.all([this.getConnectivity(e),this.getThroughput(e)]);return{connectivity:r,throughput:n==null?void 0:n.throughput,fractionalLoss:n==null?void 0:n.fractionalLoss,RTT:n==null?void 0:n.RTT,jitter:n==null?void 0:n.jitter,backendRTT:n==null?void 0:n.backendRTT}})}getNetworkInfo(e,r=!1){return u(this,null,function*(){var n,i;if(r){const d=yield this.getIPDetails();return{ipDetails:d,effectiveNetworkType:(n=navigator.connection)==null?void 0:n.effectiveType,location:d.loc?ch(d.loc):void 0}}const[s,o,a]=yield Promise.all([this.getConnectivity(e),this.getThroughput(e),this.getIPDetails()]);return{ipDetails:a,effectiveNetworkType:(i=navigator.connection)==null?void 0:i.effectiveType,location:a.loc?ch(a.loc):void 0,turnConnectivity:s?s.host||s.relay||s.reflexive:!1,connectivity:s,throughput:o==null?void 0:o.throughput,fractionalLoss:o==null?void 0:o.fractionalLoss,RTT:o==null?void 0:o.RTT,jitter:o==null?void 0:o.jitter,backendRTT:o==null?void 0:o.backendRTT}})}}class jy extends lh{}class uh extends lh{constructor(){super(...arguments),m(this,"producerMap",new Map),m(this,"consumerMap",new Map)}registerProducer(e){return u(this,null,function*(){this.producerMap.set(e.id,e),yield this.generateProducerStreamMap(e),e.observer.on("close",this.deregisterProducer.bind(this,e)),e.observer.on("pause",this.pauseProducer.bind(this,e.id)),e.observer.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)})}registerConsumer(e){return u(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.observer.on("close",this.deregisterConsumer.bind(this,e)),e.observer.on("pause",this.pauseConsumer.bind(this,e.id)),e.observer.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)})}generateConsumerStreamMap(e,r=!1){return u(this,null,function*(){const n=yield e.getStats(),i=this.parseRTCReport(n,["inbound-rtp"],!1,e.id),s=[...i.consumerStreamMap.values()][0],o=r?this.getConsumerStatsFromParsedConsumerStats(i,s,e.id):void 0;for(const a of n.values())switch(a.type){case"inbound-rtp":{this.inboundConsumerMap.set(a.id,e.id);break}}return o})}deregisterProducer(e){this.producerMap.delete(e.id),this.outboundProducerMap.forEach((r,n)=>{r===e.id&&this.outboundProducerMap.delete(n)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.consumerMap.delete(e.id),this.inboundConsumerMap.forEach((r,n)=>{r===e.id&&this.inboundConsumerMap.delete(n)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var r;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(r=e.relayProtocol)!=null?r:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}parseRTCReport(e,r=[],n=!1,i=void 0,s=void 0){var o,a,d,h,p,f,g;const E=e,v=new dh,R=r.length?new Set(r):void 0,A=[],L=[],F=[],W=new Map,H=new Map;for(const I of E.values()){if(R){if(R.size===0)break;if(R.has(I.type))n&&R.delete(I.type);else continue}switch(I.type){case"local-candidate":{A.push(this.getIceCandidateStats(I));break}case"remote-candidate":{L.push(this.getIceCandidateStats(I));break}case"candidate-pair":{const{nominated:S}=I,{selected:P}=I,N=I,ce={nominated:S!=null?S:P,currentRoundTripTime:N.currentRoundTripTime,totalRoundTripTime:N.totalRoundTripTime,bytesReceived:N.bytesReceived,bytesSent:N.bytesSent,availableOutgoingBitrate:N.availableOutgoingBitrate,lastPacketReceivedTimestamp:N.lastPacketReceivedTimestamp,lastPacketSentTimestamp:N.lastPacketSentTimestamp,localCandidateId:N.localCandidateId,remoteCandidateId:N.remoteCandidateId,bytesDiscardedOnSend:N.bytesDiscardedOnSend,packetsSent:N.packetsSent,packetsReceived:N.packetsReceived,packetsDiscardedOnSend:N.packetsDiscardedOnSend};F.push(ce),(I.nominated===!0||I.selected===!0)&&(v.candidatePair=ce);break}case"transport":{const S=I;s&&(s.producing&&(this.overallProducingTransportsStatsMap[s.id]||(this.overallProducingTransportsStatsMap[s.id]={totalPacketsSent:0})),s.consuming&&(this.overallConsumingTransportsStatsMap[s.id]||(this.overallConsumingTransportsStatsMap[s.id]={totalPacketsReceived:0})));const P={bytesReceived:S.bytesReceived,bytesSent:S.bytesSent,packetsSent:S.packetsSent,packetsReceived:S.packetsReceived,dtlsCipher:S.dtlsCipher,dtlsState:S.dtlsState,iceRole:S.iceRole};if(v.transport=P,s){if(s.producing){const N=this.overallProducingTransportsStatsMap[s.id];this.processProducingTransportStats(s.id,N,P)}if(s.consuming){const N=this.overallConsumingTransportsStatsMap[s.id];this.processConsumingTransportStats(s.id,N,P)}}break}case"remote-inbound-rtp":{const S=I,P={jitter:S.jitter,fractionLost:S.fractionLost,roundTripTime:S.roundTripTime,roundTripTimeMeasurements:S.roundTripTimeMeasurements,totalRoundTripTime:S.totalRoundTripTime,packetsLost:S.packetsLost};v.remoteInboundRtp.set(S.localId,P);break}case"outbound-rtp":{const S=I,P=i||this.outboundProducerMap.get(I.id),N=this.pausedProducerMap.get(P);if(N){if(N.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const ce=this.overallProducersStatsMap[P];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.outboundProducerMap.has(I.id)){v.staleProducerStreamMap=!0;break}const Le=this.callStatsInstance.producers.get(P);if(((o=Le==null?void 0:Le.track)==null?void 0:o.readyState)==="ended")break;v.producerStreamMap.has(P)||v.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const $={bytesSent:S.bytesSent,packetsSent:S.packetsSent,nackCount:S.nackCount,ssrc:S.ssrc,mid:S.mid};if(S.mediaType==="video"||S.kind==="video"){if(S.decoderImplementation==="unknown")break;const x=S,Se=V({frameHeight:x.frameHeight,frameWidth:x.frameWidth,framesEncoded:x.framesEncoded,framesDropped:x.framesDropped?x.framesDropped:x.droppedFrames,framesPerSecond:x.framesPerSecond?x.framesPerSecond:x.framerateMean,framesSent:x.framesSent,keyFramesEncoded:x.keyFramesEncoded,firCount:x.firCount,encoderImplementation:x.encoderImplementation,hugeFramesSent:x.hugeFramesSent,pliCount:x.pliCount,qpSum:x.qpSum,qualityLimitationReason:x.qualityLimitationReason,qualityLimitationDurations:x.qualityLimitationDurations,qualityLimitationResolutionChanges:x.qualityLimitationResolutionChanges,totalEncodeTime:x.totalEncodeTime,totalPacketSendDelay:x.totalEncodeTime,retransmittedBytesSent:x.retransmittedBytesSent,retransmittedPacketsSent:x.retransmittedPacketsSent},$);this.videoProducerToStatsMap.set(I.id,Se),v.outboundVideoRtp.set(I.id,Se),v.producerStreamMap.get(P).outboundVideoRtpId.push(I.id),this.processOutboundProducerVideoStats(P,ce,Se)}else if(S.mediaType==="audio"||S.kind==="audio"){const x=S,Se=V({retransmittedBytesSent:x.retransmittedBytesSent,retransmittedPacketsSent:x.retransmittedPacketsSent},$);this.audioProducerToStatsMap.set(I.id,Se),v.outboundAudioRtp.set(I.id,Se),v.producerStreamMap.get(P).outboundAudioRtpId.push(I.id),this.processOutboundProducerAudioStats(P,ce,Se)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}case"inbound-rtp":{const S=I,P=i||this.inboundConsumerMap.get(I.id),N=this.pausedConsumerMap.get(P);if(N){if(N.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(S.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const ce=this.overallConsumersStatsMap[P];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.inboundConsumerMap.has(I.id)){v.staleConsumerStreamMap=!0;break}v.consumerStreamMap.has(P)||v.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Le={bytesReceived:S.bytesReceived,packetsReceived:S.packetsReceived,packetsLost:S.packetsLost,jitter:S.jitter,nackCount:S.nackCount,jitterBufferDelay:S.jitterBufferDelay,jitterBufferEmittedCount:S.jitterBufferEmittedCount,lastPacketReceivedTimestamp:S.lastPacketReceivedTimestamp,ssrc:S.ssrc,mid:S.mid};if(S.mediaType==="video"||S.kind==="video"){if(S.decoderImplementation==="unknown")break;const $=S,x=V({frameHeight:$.frameHeight,frameWidth:$.frameWidth,framesDecoded:$.framesDecoded,framesDropped:$.framesDropped?$.framesDropped:$.droppedFrames,framesPerSecond:$.framesPerSecond?$.framesPerSecond:$.framerateMean,framesReceived:$.framesReceived,keyFramesDecoded:$.keyFramesDecoded,firCount:$.firCount,decoderImplementation:$.decoderImplementation,pliCount:$.pliCount,totalProcessingDelay:$.totalProcessingDelay},Le);x.score=sh({frameWidth:x.frameWidth||0,framesDecoded:(x.framesDecoded||0)-(((a=this.videoConsumerToStatsMap.get(P))==null?void 0:a.framesDecoded)||0),framesPerSecond:x.framesPerSecond||0,packetsLost:(x.packetsLost||0)-(((d=this.videoConsumerToStatsMap.get(P))==null?void 0:d.packetsLost)||0),packetsReceived:(x.packetsReceived||0)-(((h=this.videoConsumerToStatsMap.get(P))==null?void 0:h.packetsReceived)||0),jitter:x.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),H.set(P,x.score),this.videoConsumerToStatsMap.set(P,x),v.inboundVideoRtp.set(I.id,x),v.consumerStreamMap.get(P).inboundVideoRtpId.push(I.id),this.processInboundConsumerVideoStats(P,ce,x)}else if(S.mediaType==="audio"||S.kind==="audio"){const $=S,x=V({audioLevel:$.audioLevel,concealedSampels:$.concealedSampels,concealmentEvents:$.concealmentEvents,totalAudioEnergy:$.totalAudioEnergy,totalSamplesDuration:$.totalSamplesDuration,totalSamplesReceived:$.totalSamplesReceived},Le);x.score=ih({concealmentEvents:(x.concealmentEvents||0)-(((p=this.audioConsumerToStatsMap.get(P))==null?void 0:p.concealmentEvents)||0),packetsLost:(x.packetsLost||0)-(((f=this.audioConsumerToStatsMap.get(P))==null?void 0:f.packetsLost)||0),packetsReceived:(x.packetsReceived||0)-(((g=this.audioConsumerToStatsMap.get(P))==null?void 0:g.packetsReceived)||0),jitter:x.jitter||0}),H.set(P,x.score),this.audioConsumerToStatsMap.set(P,x),v.inboundAudioRtp.set(I.id,x),v.consumerStreamMap.get(P).inboundAudioRtpId.push(I.id),this.processInboundConsumerAudioStats(P,ce,x)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}}}if(v.producerStreamMap.forEach((I,S)=>{var P,N,ce,Le,$,x,Se,fn,pi,mi,ht;if(I.outboundVideoRtpId.length>0){const Qe=[];I.outboundVideoRtpId.forEach(fo=>{Qe.push(v.outboundVideoRtp.get(fo))});const Xe=this.getWorkingSimulcastVideoStats(Qe);Xe.score=rh({frameWidth:Xe.frameWidth||0,framesPerSecond:Xe.framesPerSecond||0,jitter:((P=Xe.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsSent:(Xe.packetsSent||0)-(((N=this.videoProducerToStatsMap.get(S))==null?void 0:N.packetsSent)||0),packetsLost:(((ce=Xe.remoteData)==null?void 0:ce.packetsLost)||0)-((($=(Le=this.videoProducerToStatsMap.get(S))==null?void 0:Le.remoteData)==null?void 0:$.packetsLost)||0),framesEncoded:(Xe.framesEncoded||0)-(((x=this.videoProducerToStatsMap.get(S))==null?void 0:x.framesEncoded)||0)}),W.set(S,Xe.score)}else if(I.outboundAudioRtpId.length>0){const Qe=v.outboundAudioRtp.get(I.outboundAudioRtpId[0]);Qe.score=th({packetsSent:(Qe.packetsSent||0)-(((Se=this.audioProducerToStatsMap.get(S))==null?void 0:Se.packetsSent)||0),packetsLost:(((fn=Qe.remoteData)==null?void 0:fn.packetsLost)||0)-(((mi=(pi=this.audioProducerToStatsMap.get(S))==null?void 0:pi.remoteData)==null?void 0:mi.packetsLost)||0),jitter:((ht=Qe.remoteData)==null?void 0:ht.jitter)||0}),W.set(S,Qe.score)}}),F.forEach(I=>{const S=A.find(N=>N.id===I.localCandidateId?(I.localCandidateId=N.id,N):null),P=L.find(N=>N.id===I.remoteCandidateId?(I.remoteCandidateId=N.id,N):null);S&&(I.localCandidateType=S.type,I.localCandidateAddress=S.address,I.localCandidatePort=S.port,I.localCandidateProtocol=S.protocol,I.localCandidateUrl=S.url,I.localCandidateNetworkType=S.networkType,I.localCandidateRelatedAddress=S.relatedAddress,I.localCandidateRelatedPort=S.relatedPort),P&&(I.remoteCandidateType=P.type,I.remoteCandidateAddress=P.address,I.remoteCandidatePort=P.port,I.remoteCandidateProtocol=P.protocol,I.remoteCandidateUrl=P.url)}),v.candidatePair&&(v.transport?(v.transport.bytesReceived=v.candidatePair.bytesReceived,v.transport.bytesSent=v.candidatePair.bytesSent,v.transport.totalRoundTripTime=v.candidatePair.totalRoundTripTime,v.transport.availableOutgoingBitrate=v.candidatePair.availableOutgoingBitrate,v.transport.roundTripTime=v.candidatePair.currentRoundTripTime):v.transport={bytesReceived:v.candidatePair.bytesReceived,bytesSent:v.candidatePair.bytesSent,totalRoundTripTime:v.candidatePair.totalRoundTripTime,availableOutgoingBitrate:v.candidatePair.availableOutgoingBitrate,roundTripTime:v.candidatePair.currentRoundTripTime}),v.transport&&(v.transport.candidatePairs=F),v.transport&&!v.transport.roundTripTime){let I=0,S=0;v.remoteInboundRtp.forEach((P,N)=>{P.roundTripTime&&P.roundTripTime>I&&(I=P.roundTripTime,S=P.totalRoundTripTime)}),v.transport.roundTripTime=I,v.transport.totalRoundTripTime=S}return H.size>0&&this.observer.safeEmit("consumer_score",H),W.size>0&&this.observer.safeEmit("producer_score",W),v}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((n,i)=>{const s=this.producerMap.get(i),o=s.track.getSettings(),a=n.outboundVideoRtpId.map(h=>{const p=e.outboundVideoRtp.get(h);return p.frameHeight||(p.frameHeight=o.height,p.frameWidth=o.width,p.framesPerSecond=o.frameRate),p}),d={producerId:i,appData:s.appData,videoStats:a,audioStats:n.outboundAudioRtpId.map(h=>e.outboundAudioRtp.get(h))};r.push(d)})}catch(n){console.error("getProducersReport: ",n,e)}return r}getConsumerStatsFromParsedConsumerStats(e,r,n){let i;try{const{peerId:s,producerId:o,appData:a}=this.consumerPeerIdMap.get(n),d=r==null?void 0:r.inboundVideoRtpId.map(h=>{const p=this.consumerMap.get(n).track.getSettings(),f=e.inboundVideoRtp.get(h);return f.frameHeight||(f.frameHeight=p.height,f.frameWidth=p.width,f.framesPerSecond=p.frameRate),f});i={consumerId:n,peerId:s,producerId:o,appData:a,videoStats:d,audioStats:r==null?void 0:r.inboundAudioRtpId.map(h=>e.inboundAudioRtp.get(h))}}catch(s){console.error("getConsumerStatsFromParsedConsumerStats: ",s,e)}return i}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((n,i)=>{r.push(this.getConsumerStatsFromParsedConsumerStats(e,n,i))})}catch(n){console.error("getConsumerStatsFromReport: ",n,e)}return r}}class Hy extends uh{}function Lo(t,e,r,n){if(t!=null&&t.logger&&t.logger.error("Callstats::handleError",{error:n}),typeof r=="function"&&n instanceof e)r.call(null,n,t);else throw n}function hh(t,e,r){const n=t.value;return t.value=function(...i){try{const s=n.apply(this,i);return s&&s instanceof Promise?s.catch(o=>{Lo(this,e,r,o)}):s}catch(s){Lo(this,e,r,s)}return null},t}const te=(t,e)=>(r,n,i)=>{const s=i.value;return i.value=function(...o){try{const a=s.apply(this,o);return a&&a instanceof Promise?a.catch(d=>{Lo(this,t,e,d)}):a}catch(a){Lo(this,t,e,a)}return null},i},Wy=(t,e)=>(r,n,i)=>{if(i)return hh(i,t,e);for(const s of Reflect.ownKeys(r.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(r.prototype,s);o.value instanceof Function&&Object.defineProperty(r.prototype,s,hh(o,t,e))}};var Z=globalThis&&globalThis.__decorate||function(t,e,r,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s};const ee=console;let Y=class extends Mo{constructor(t="https://api.testingv3.dyte.in",e="Blink",r=ls.PROD,n,i,s,o){switch(super(),m(this,"observer"),m(this,"eventHandler"),m(this,"measurements"),m(this,"producingTransport"),m(this,"consumingTransport"),m(this,"producers",new Map),m(this,"consumers",new Map),m(this,"iceServers"),m(this,"connectionInfoPromise"),m(this,"pingStatsTimeout"),m(this,"logger"),m(this,"env"),m(this,"apiHostnames"),m(this,"peerId"),m(this,"consumerSharedMediaStatesMap",new Map),m(this,"currentUserMediaStates",{}),this.env=r,this.apiHostnames=o,this.logger=i,this.peerId=s,this.eventHandler=new Iy({logger:i,peerId:s,apiHostnames:o}),this.logger.debug("callStats::engineName: ",{engineName:e}),e){case"Blink":this.measurements=new jy;break;case"Gecko":this.measurements=new uh;break;case"WebKit":this.measurements=new Hy;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 Mo,this.measurements.observer.on("consumer_score",a=>{i.debug(`callStats::consumer_score ${[...a.entries()]}`),this.eventHandler.emit("consumer_score",a)}),this.measurements.observer.on("producer_score",a=>{i.debug(`callStats::producer_score ${[...a.entries()]}`),this.eventHandler.emit("producer_score",a)})}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.observer.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.observer.on("close",this.deRegisterProducer.bind(this,t))}sendConsumerSharedMediaStateEvent(t,e){this.consumerSharedMediaStatesMap.has(t)||this.consumerSharedMediaStatesMap.set(t,{});const r=this.consumerSharedMediaStatesMap.get(t);this.consumerSharedMediaStatesMap.set(t,Object.assign(r,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(r=>{this.registerProducer(r)}),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(r=>{this.registerConsumer(r)}),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){this.connectionInfoPromise=this.measurements.getNetworkInfo(this.iceServers,t),this.eventHandler.callEvent({event:U.PRECALL_TEST_BEGIN,timestamp:new Date}),this.connectionInfoPromise&&this.connectionInfoPromise.then(e=>{this.eventHandler.callEvent({event:U.PRECALL_TEST_COMPLETE,metaData:{connectionInfo:e},timestamp:new Date})})}sendScreenShareToggleEvent(t,e){this.currentUserMediaStates.screen=t,this.eventHandler.callEvent({event:t?U.SCREENSHARE_STARTED:U.SCREENSHARE_STOPPED,metaData:{ssrc:e},timestamp:new Date})}sendScreenShareRequestedEvent(){this.eventHandler.callEvent({event:U.SCREENSHARE_START_REQUESTED,timestamp:new Date})}sendActiveSpeakerEvent(t){this.eventHandler.callEvent({event:U.DOMINANT_SPEAKER,metaData:{peerId:t},timestamp:new Date})}devices(t,e){this.eventHandler.callEvent({event:t===Vt.AUDIO&&U.AUDIO_DEVICES_UPDATES||t===Vt.VIDEO&&U.VIDEO_DEVICES_UPDATES||t===Vt.SPEAKER&&U.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:e},timestamp:new Date})}selectedDevice(t,e){this.eventHandler.callEvent({event:t===Vt.AUDIO&&U.SELECTED_MICROHPONE_UPDATE||t===Vt.VIDEO&&U.SELECTED_CAMERA_UPDATE||t===Vt.SPEAKER&&U.SELECTED_SPEAKER_UPDATE,metaData:{device:e},timestamp:new Date})}mediaPermission(t,e){this.eventHandler.callEvent({event:U.MEDIA_PERMISSION,metaData:{deviceType:t,permission:e},timestamp:new Date})}mediaPlaybackFailed(t){this.eventHandler.callEvent({event:t===Vt.AUDIO&&U.AUDIO_PLAY_FAILED||t===Vt.VIDEO&&U.VIDEO_PLAY_FAILED,metaData:{deviceType:t},timestamp:new Date})}mediaTrackMuted(t){this.eventHandler.callEvent({event:t===Vt.AUDIO&&U.AUDIO_TRACK_MUTED||t===Vt.VIDEO&&U.VIDEO_TRACK_MUTED,metaData:{deviceType:t},timestamp:new Date})}tabChanged(t){this.eventHandler.callEvent({event:U.TAB_CHANGE,metaData:{isMeetingsTabActive:t},timestamp:new Date})}browserBackgrounded(){this.eventHandler.callEvent({event:U.BROWSER_BACKGROUNDED,timestamp:new Date})}browserForegrounded(){this.eventHandler.callEvent({event:U.BROWSER_FOREGROUNDED,timestamp:new Date})}legacySwitch(t){this.eventHandler.callEvent({event:U.LEGACY_SWITCH,metadata:{on:t},timestamp:new Date})}getPreCallTestResults(){return u(this,null,function*(){return this.connectionInfoPromise})}sendCallJoinBeginEvent(t){t=ne(V({},t),{meetingEnv:this.env}),t.deviceInfo=ne(V({},t.deviceInfo),{userAgent:navigator.userAgent,cpus:navigator.hardwareConcurrency,memory:navigator.deviceMemory}),this.eventHandler.callEvent({event:U.CALL_JOIN_BEGIN,metaData:{peerMetaData:t},timestamp:new Date})}sendNetworkQualityTestBeginEvent(t){this.eventHandler.callEvent({event:U.NET_QUALITY_TEST_BEGIN,timestamp:new Date}),new Promise((e,r)=>u(this,null,function*(){const n=[];try{for(const i of t)try{if(i.iceServers&&i.iceServers.length>0){const s=yield this.measurements.getNetworkQuality(i.iceServers);n.push(ne(V({},i),{networkResults:s}))}}catch(s){console.warn("Error handling ",s)}e({regionData:n})}catch(i){console.warn("Error in callstats, ",i),r(i)}})).then(e=>{this.eventHandler.callEvent({event:U.NET_QUALITY_TEST_END,timestamp:new Date,metaData:e})})}sendWebSocketConnectedEvent(){this.eventHandler.callEvent({event:U.WEBSOCKET_CONNECTED,timestamp:new Date})}sendTransportConnectedEvent(){this.eventHandler.callEvent({event:U.TRANSPORT_CONNECTED,timestamp:new Date})}sendAudioToggleEvent(t){this.currentUserMediaStates.audio=t;let e;t?e=U.AUDIO_ON:e=U.AUDIO_OFF,this.eventHandler.callEvent({event:e,timestamp:new Date})}sendVideoToggleEvent(t){this.currentUserMediaStates.video=t;let e;t?e=U.VIDEO_ON:e=U.VIDEO_OFF,this.eventHandler.callEvent({event:e,timestamp:new Date})}sendParticipantRoleToggleEvent(t){this.eventHandler.callEvent({event:U.PARTICIPANT_ROLE,timestamp:new Date,metaData:t})}startPingStats(t=7e3){this.sendPingStatsEvent(!1),this.pingStatsTimeout=setInterval(this.sendPingStatsEvent.bind(this),t)}stopPingStats(){clearInterval(this.pingStatsTimeout)}sendPingStatsEvent(t=!0){return u(this,null,function*(){let e,r;if(this.producingTransport&&(e=yield this.measurements.getProcessedStats(this.producingTransport,!1,!0),!e||!(e!=null&&e.producerReport))){this.logger.debug("callStats::sendPingStatsEvent::staleProducingTransport",{disclaimer:"Stale producer? Regenerating Stream Maps!"});const i=yield this.measurements.getProducersReport([...this.producers.values()]);e&&i?e.producerReport=i:(e=yield this.measurements.getProcessedStats(this.producingTransport,!1,!0),(!e||!(e!=null&&e.producerReport))&&this.logger.debug("callStats::sendPingStatsEvent::noProducingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}if(this.consumingTransport&&(r=yield this.measurements.getProcessedStats(this.consumingTransport,!0,!1),!r||!r.consumerReport)){this.logger.debug("callStats::sendPingStatsEvent::staleConsumingTransport",{disclaimer:"Stale consumer? Regenerating Stream Maps!"});const i=yield this.measurements.getConsumersReport([...this.consumers.values()]);r&&i?r.consumerReport=i:(r=yield this.measurements.getProcessedStats(this.consumingTransport,!0,!1),(!r||!r.consumerReport)&&this.logger.debug("callStats::sendPingStatsEvent::noConsumingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}const n={producingTransportStats:e?e==null?void 0:e.transportReport:void 0,consumingTransportStats:r?r==null?void 0:r.transportReport:void 0,producerStats:[].concat((e==null?void 0:e.producerReport)||[]).concat((r==null?void 0:r.producerReport)||[]),consumerStats:[].concat((r==null?void 0:r.consumerReport)||[]).concat((e==null?void 0:e.consumerReport)||[])};if(t&&n.producerStats.length===0&&n.consumerStats.length===0){yield this.eventHandler.flush();return}this.eventHandler.callEvent({event:U.PING_STAT,metaData:n,timestamp:new Date})})}sendIVSPlayerRebufferEvent(){this.eventHandler.callEvent({event:U.IVS_PLAYER_REBUFFERING,timestamp:new Date})}sendIVSPlayerAudioBlockEvent(){this.eventHandler.callEvent({event:U.IVS_PLAYER_AUDIO_BLOCKED,timestamp:new Date})}sendIVSPlayerPlaybackBlockedEvent(){this.eventHandler.callEvent({event:U.IVS_PLAYER_PLAYBACK_BLOCKED,timestamp:new Date})}sendIVSPlayerNetworkUnavailableEvent(){this.eventHandler.callEvent({event:U.IVS_PLAYER_NETWORK_UNAVAILABLE,timestamp:new Date})}sendIVSPlayerInitializedEvent(){this.eventHandler.callEvent({event:U.IVS_PLAYER_INITIALIZED,timestamp:new Date})}sendIVSPlayerWorkerErrorEvent(){this.eventHandler.callEvent({event:U.IVS_PLAYER_WORKER_ERROR,timestamp:new Date})}sendIVSPlayerErrorEvent(t){this.eventHandler.callEvent({event:U.IVS_PLAYER_ERROR,timestamp:new Date,metaData:t})}sendIVSPlayerRecoverableErrorEvent(t){this.eventHandler.callEvent({event:U.IVS_PLAYER_RECOVERABLE_ERROR,timestamp:new Date,metaData:t})}sendIVSPlayerAnalyticsEvent(t){this.eventHandler.callEvent({event:U.IVS_PLAYER_ANALYTICS_EVENT,timestamp:new Date,metaData:t})}sendIVSPlayerPlaybackRateChangedEvent(t){this.eventHandler.callEvent({event:U.IVS_PLAYER_PLAYBACK_RATE_CHANGED,timestamp:new Date,metaData:{updatedPlaybackRate:t}})}sendIVSPlayerQualityChanged(t){this.eventHandler.callEvent({event:U.IVS_PLAYER_QUALITY_CHANGED,timestamp:new Date,metaData:t})}sendPlayerLiveLatency(t){this.eventHandler.callEvent({event:U.LIVESTREAM_LATENCY,timestamp:new Date,metaData:{latency:t}})}sendDisconnectEvent(){this.eventHandler.callEvent({event:U.DISCONNECT,timestamp:new Date})}sendReconnectEvent(){this.eventHandler.callEvent({event:U.RECONNECT_ATTEMPT,timestamp:new Date})}};Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"registerIceServers",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"registerConsumer",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"registerProducer",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendConsumerSharedMediaStateEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"registerProducingTransport",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"registerConsumingTransport",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"deRegisterConsumer",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"deRegisterProducer",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"disconnectConsumingTransport",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"disconnectProducingTransport",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendPreCallTestBeginEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendScreenShareToggleEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendScreenShareRequestedEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendActiveSpeakerEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"devices",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"selectedDevice",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"mediaPermission",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"mediaPlaybackFailed",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"mediaTrackMuted",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"tabChanged",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"browserBackgrounded",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"browserForegrounded",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"legacySwitch",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"getPreCallTestResults",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendCallJoinBeginEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendNetworkQualityTestBeginEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendWebSocketConnectedEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendTransportConnectedEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendAudioToggleEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendVideoToggleEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendParticipantRoleToggleEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"startPingStats",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"stopPingStats",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendPingStatsEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendIVSPlayerRebufferEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendIVSPlayerAudioBlockEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendIVSPlayerPlaybackBlockedEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendIVSPlayerNetworkUnavailableEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendIVSPlayerInitializedEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendIVSPlayerWorkerErrorEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendIVSPlayerErrorEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendIVSPlayerRecoverableErrorEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendIVSPlayerAnalyticsEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendIVSPlayerQualityChanged",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendPlayerLiveLatency",null),Y=Z([Wy(TypeError,(t,e)=>ee.error(e,t))],Y);const $y=Y;class Gy extends _t{constructor(){super(...arguments),m(this,"stats"),m(this,"roomURL"),m(this,"peerId"),m(this,"backend"),m(this,"iceServers"),m(this,"initialized",!1),m(this,"stalled",!1),m(this,"ipInformation"),m(this,"logger")}initialize(e){return u(this,arguments,function*({peerId:r,engineName:n,env:i=ls.PROD,iceServers:s,apiBase:o="https://api.cluster.dyte.in",flags:a,logger:d=console,apiHostnames:h,skipConnectivityChecks:p=!1}){var f,g,E;try{this.peerId=r,this.logger=d,this.ipInformation=yield Zc.getIPDetails({peerId:r,apiHostnames:h}),this.backend=new $y(o,n,i,a,d,r,h),this.iceServers=s,(f=this.backend)==null||f.registerIceServers(this.iceServers),this.initialized=!0,(E=(g=this.backend)==null?void 0:g.eventHandler)==null||E.emit("initialized",this.ipInformation),this.emit("initialized",this.ipInformation),this.startPreCallTest(p)}catch(v){this.logger.error("callStats::CallStatsIntegration: ",{error:v}),this.stallCallStats()}})}setRoomName(e){this.roomURL=e}configureSendTransport(e){var r;(r=this.backend)==null||r.registerProducingTransport(e)}configureRecvTransport(e){var r;(r=this.backend)==null||r.registerConsumingTransport(e)}candidateRegionalNetworkQualityTest(e){return u(this,null,function*(){var r;try{(r=this.backend)==null||r.sendNetworkQualityTestBeginEvent(e)}catch(n){this.logger.error("callStats::sendNetworkQualityTestBeginEvent",{error:{reason:n.reason}})}})}roomJoined(e){return u(this,null,function*(){var r,n;(r=this.backend)==null||r.sendCallJoinBeginEvent(e),this.backend,(n=this.backend)==null||n.startPingStats()})}audioOff(){var e;(e=this.backend)==null||e.sendAudioToggleEvent(!1)}audioOn(){var e;(e=this.backend)==null||e.sendAudioToggleEvent(!0)}videoOff(){var e;(e=this.backend)==null||e.sendVideoToggleEvent(!1)}videoOn(){var e;(e=this.backend)==null||e.sendVideoToggleEvent(!0)}callEnded(){var e,r;(e=this.backend)==null||e.stopPingStats(),(r=this.backend)==null||r.sendDisconnectEvent()}screenShareStart(e){var r;(r=this.backend)==null||r.sendScreenShareToggleEvent(!0,e)}consumerSharedMediaState(e,r){var n;(n=this.backend)==null||n.sendConsumerSharedMediaStateEvent(e,r)}screenShareStop(e){var r;(r=this.backend)==null||r.sendScreenShareToggleEvent(!1,e)}screenShareRequested(){var e;(e=this.backend)==null||e.sendScreenShareRequestedEvent()}activeSpeaker(e){var r;e===this.peerId&&((r=this.backend)==null||r.sendActiveSpeakerEvent(e))}devices(e,r){var n;(n=this.backend)==null||n.devices(e,r)}selectedDevice(e,r){var n;(n=this.backend)==null||n.selectedDevice(e,r)}mediaPermission(e,r){var n;(n=this.backend)==null||n.mediaPermission(e,r)}mediaPlaybackFailed(e){var r;(r=this.backend)==null||r.mediaPlaybackFailed(e)}mediaTrackMuted(e){var r;(r=this.backend)==null||r.mediaTrackMuted(e)}tabChanged(e=!1){var r;(r=this.backend)==null||r.tabChanged(e)}browserBackgrounded(){var e;(e=this.backend)==null||e.browserBackgrounded()}browserForegrounded(){var e;(e=this.backend)==null||e.browserForegrounded()}legacySwitch(e){var r;(r=this.backend)==null||r.legacySwitch(e)}startPreCallTest(e=!1){return u(this,null,function*(){var r;(r=this.backend)==null||r.sendPreCallTestBeginEvent(e)})}onPreCallTestResults(e){var r;return(r=this.backend)==null||r.eventHandler.once("precall_end",e),e}onReceivingConsumerAudioStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("consumer_audio_status",e)}onReceivingConsumerVideoStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("consumer_video_status",e)}onReceivingProducerAudioStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("producer_audio_status",e)}onReceivingProducerVideoStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("producer_video_status",e)}onReceivingProducingTransportStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("producing_transport_status",e)}onReceivingConsumingTransportStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("consuming_transport_status",e)}onProducerScore(e){var r;(r=this.backend)==null||r.eventHandler.on("producer_score",e)}onConsumerScore(e){var r;(r=this.backend)==null||r.eventHandler.on("consumer_score",e)}onSafeInitialization(e){if(this.initialized)e(this.ipInformation,!1);else if(!this.stalled){const r=n=>{e(n,!0)};return this.once("initialized",r),r}return()=>{}}removeInitializationListener(e){this.removeListener("initialized",e)}stallCallStats(){this.stalled=!0,this.removeAllListeners("initialized")}ivsPlayerEvent(e,r){var n,i,s,o,a,d,h,p,f,g,E;switch(e){case"PlayerRebuffering":(n=this.backend)==null||n.sendIVSPlayerRebufferEvent();break;case"PlayerAudioBlocked":(i=this.backend)==null||i.sendIVSPlayerAudioBlockEvent();break;case"PlayerPlaybackBlocked":(s=this.backend)==null||s.sendIVSPlayerPlaybackBlockedEvent();break;case"PlayerNetworkUnavailable":(o=this.backend)==null||o.sendIVSPlayerNetworkUnavailableEvent();break;case"PlayerInitialized":(a=this.backend)==null||a.sendIVSPlayerInitializedEvent();break;case"PlayerWorkerError":(d=this.backend)==null||d.sendIVSPlayerWorkerErrorEvent();break;case"PlayerError":(h=this.backend)==null||h.sendIVSPlayerErrorEvent(r);break;case"PlayerRecoverableError":(p=this.backend)==null||p.sendIVSPlayerRecoverableErrorEvent(r);break;case"PlayerAnalyticsEvent":(f=this.backend)==null||f.sendIVSPlayerAnalyticsEvent(r);break;case"PlayerPlaybackRateChanged":(g=this.backend)==null||g.sendIVSPlayerPlaybackRateChangedEvent(r);break;case"PlayerQualityChanged":(E=this.backend)==null||E.sendIVSPlayerQualityChanged(r);break}}livestreamLatency(e){var r;(r=this.backend)==null||r.sendPlayerLiveLatency(e)}}const B=new Gy;B.setMaxListeners(30);function Jy(t){const{length:e}=this,r=t>=0?t:e+t;return r<0||r>=e?void 0:this[r]}Array.prototype.at||Object.assign(Array.prototype,{at:Jy});function qy(t){const{length:e}=this,r=t>=0?t:e+t;return r<0||r>=e?void 0:this[r]}String.prototype.at||Object.assign(String.prototype,{at:qy});var We;(function(t){t.GroupCall="GROUP_CALL",t.Webinar="WEBINAR",t.AudioRoom="AUDIO_ROOM",t.Livestream="LIVESTREAM",t.Chat="CHAT"})(We||(We={}));var xo;(function(t){t.Skip="SKIP",t.OnPrivilegedUserEntry="ON_PRIVILEGED_USER_ENTRY",t.SkipOnAccept="SKIP_ON_ACCEPT"})(xo||(xo={}));var q;(function(t){t.Allowed="ALLOWED",t.NotAllowed="NOT_ALLOWED",t.CanRequest="CAN_REQUEST"})(q||(q={}));var Fo;(function(t){t.Allowed="ALLOWED",t.NotAllowed="NOT_ALLOWED"})(Fo||(Fo={}));var ph;(function(t){t.FULL_ACCESS="FULL_ACCESS",t.VIEW_ONLY="VIEW_ONLY"})(ph||(ph={}));var Uo;(function(t){t.skip="SKIP",t.onAccept="ON_ACCEPT",t.skipOnPrivilegedUserEntry="SKIP_ON_PRIVILEGED_USER_ENTRY",t.skipOnAccept="SKIP_ON_ACCEPT"})(Uo||(Uo={}));var vi;(function(t){t.none="NONE",t.recorder="RECORDER",t.livestreamer="LIVESTREAMER"})(vi||(vi={}));var ed;(function(t){t.groupCall="GROUP_CALL",t.webinar="WEBINAR",t.audioRoom="AUDIO_ROOM",t.livestream="LIVESTREAM",t.chat="CHAT"})(ed||(ed={}));var mh;(function(t){t.SKIP="skip",t.SKIP_ON_PRIVILEGED_USER_ENTRY="skipOnPrivilegedUserEntry",t.ON_ACCEPT="skipOnAccept",t.SKIP_ON_ACCEPT="skipOnAccept"})(mh||(mh={})),ed.groupCall,Uo.skipOnAccept,vi.none;var td={},Ky={get exports(){return td},set exports(t){td=t}},Vo={},zy={get exports(){return Vo},set exports(t){Vo=t}},fh=function(t,e){return function(){for(var r=new Array(arguments.length),n=0;n<r.length;n++)r[n]=arguments[n];return t.apply(e,r)}},Yy=fh,Vr=Object.prototype.toString;function rd(t){return Array.isArray(t)}function nd(t){return typeof t=="undefined"}function Qy(t){return t!==null&&!nd(t)&&t.constructor!==null&&!nd(t.constructor)&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t)}function gh(t){return Vr.call(t)==="[object ArrayBuffer]"}function Xy(t){return Vr.call(t)==="[object FormData]"}function Zy(t){var e;return typeof ArrayBuffer!="undefined"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&gh(t.buffer),e}function eE(t){return typeof t=="string"}function tE(t){return typeof t=="number"}function vh(t){return t!==null&&typeof t=="object"}function Bo(t){if(Vr.call(t)!=="[object Object]")return!1;var e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}function rE(t){return Vr.call(t)==="[object Date]"}function nE(t){return Vr.call(t)==="[object File]"}function iE(t){return Vr.call(t)==="[object Blob]"}function yh(t){return Vr.call(t)==="[object Function]"}function sE(t){return vh(t)&&yh(t.pipe)}function oE(t){return Vr.call(t)==="[object URLSearchParams]"}function aE(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function cE(){return typeof navigator!="undefined"&&(navigator.product==="ReactNative"||navigator.product==="NativeScript"||navigator.product==="NS")?!1:typeof window!="undefined"&&typeof document!="undefined"}function id(t,e){if(!(t===null||typeof t=="undefined"))if(typeof t!="object"&&(t=[t]),rd(t))for(var r=0,n=t.length;r<n;r++)e.call(null,t[r],r,t);else for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.call(null,t[i],i,t)}function sd(){var t={};function e(i,s){Bo(t[s])&&Bo(i)?t[s]=sd(t[s],i):Bo(i)?t[s]=sd({},i):rd(i)?t[s]=i.slice():t[s]=i}for(var r=0,n=arguments.length;r<n;r++)id(arguments[r],e);return t}function dE(t,e,r){return id(e,function(n,i){r&&typeof n=="function"?t[i]=Yy(n,r):t[i]=n}),t}function lE(t){return t.charCodeAt(0)===65279&&(t=t.slice(1)),t}var bt={isArray:rd,isArrayBuffer:gh,isBuffer:Qy,isFormData:Xy,isArrayBufferView:Zy,isString:eE,isNumber:tE,isObject:vh,isPlainObject:Bo,isUndefined:nd,isDate:rE,isFile:nE,isBlob:iE,isFunction:yh,isStream:sE,isURLSearchParams:oE,isStandardBrowserEnv:cE,forEach:id,merge:sd,extend:dE,trim:aE,stripBOM:lE},yi=bt;function Eh(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var Sh=function(t,e,r){if(!e)return t;var n;if(r)n=r(e);else if(yi.isURLSearchParams(e))n=e.toString();else{var i=[];yi.forEach(e,function(o,a){o===null||typeof o=="undefined"||(yi.isArray(o)?a=a+"[]":o=[o],yi.forEach(o,function(d){yi.isDate(d)?d=d.toISOString():yi.isObject(d)&&(d=JSON.stringify(d)),i.push(Eh(a)+"="+Eh(d))}))}),n=i.join("&")}if(n){var s=t.indexOf("#");s!==-1&&(t=t.slice(0,s)),t+=(t.indexOf("?")===-1?"?":"&")+n}return t},uE=bt;function jo(){this.handlers=[]}jo.prototype.use=function(t,e,r){return this.handlers.push({fulfilled:t,rejected:e,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1},jo.prototype.eject=function(t){this.handlers[t]&&(this.handlers[t]=null)},jo.prototype.forEach=function(t){uE.forEach(this.handlers,function(e){e!==null&&t(e)})};var hE=jo,pE=bt,mE=function(t,e){pE.forEach(t,function(r,n){n!==e&&n.toUpperCase()===e.toUpperCase()&&(t[e]=r,delete t[n])})},Th=function(t,e,r,n,i){return t.config=e,r&&(t.code=r),t.request=n,t.response=i,t.isAxiosError=!0,t.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}},t},od,kh;function _h(){if(kh)return od;kh=1;var t=Th;return od=function(e,r,n,i,s){var o=new Error(e);return t(o,r,n,i,s)},od}var ad,bh;function fE(){if(bh)return ad;bh=1;var t=_h();return ad=function(e,r,n){var i=n.config.validateStatus;!n.status||!i||i(n.status)?e(n):r(t("Request failed with status code "+n.status,n.config,null,n.request,n))},ad}var cd,wh;function gE(){if(wh)return cd;wh=1;var t=bt;return cd=t.isStandardBrowserEnv()?function(){return{write:function(e,r,n,i,s,o){var a=[];a.push(e+"="+encodeURIComponent(r)),t.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),t.isString(i)&&a.push("path="+i),t.isString(s)&&a.push("domain="+s),o===!0&&a.push("secure"),document.cookie=a.join("; ")},read:function(e){var r=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return r?decodeURIComponent(r[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}(),cd}var Ch,Ih;function vE(){return Ih||(Ih=1,Ch=function(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}),Ch}var Rh,Ph;function yE(){return Ph||(Ph=1,Rh=function(t,e){return e?t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):t}),Rh}var dd,Ah;function EE(){if(Ah)return dd;Ah=1;var t=vE(),e=yE();return dd=function(r,n){return r&&!t(n)?e(r,n):n},dd}var ld,Mh;function SE(){if(Mh)return ld;Mh=1;var t=bt,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 ld=function(r){var n={},i,s,o;return r&&t.forEach(r.split(`
13
- `),function(a){if(o=a.indexOf(":"),i=t.trim(a.substr(0,o)).toLowerCase(),s=t.trim(a.substr(o+1)),i){if(n[i]&&e.indexOf(i)>=0)return;i==="set-cookie"?n[i]=(n[i]?n[i]:[]).concat([s]):n[i]=n[i]?n[i]+", "+s:s}}),n},ld}var ud,Dh;function TE(){if(Dh)return ud;Dh=1;var t=bt;return ud=t.isStandardBrowserEnv()?function(){var e=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a"),n;function i(s){var o=s;return e&&(r.setAttribute("href",o),o=r.href),r.setAttribute("href",o),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return n=i(window.location.href),function(s){var o=t.isString(s)?i(s):s;return o.protocol===n.protocol&&o.host===n.host}}():function(){return function(){return!0}}(),ud}var hd,Oh;function Ho(){if(Oh)return hd;Oh=1;function t(e){this.message=e}return t.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},t.prototype.__CANCEL__=!0,hd=t,hd}var pd,Nh;function kE(){if(Nh)return pd;Nh=1;var t=bt,e=fE(),r=gE(),n=Sh,i=EE(),s=SE(),o=TE(),a=_h(),d=Wo(),h=Ho();return pd=function(p){return new Promise(function(f,g){var E=p.data,v=p.headers,R=p.responseType,A;function L(){p.cancelToken&&p.cancelToken.unsubscribe(A),p.signal&&p.signal.removeEventListener("abort",A)}t.isFormData(E)&&delete v["Content-Type"];var F=new XMLHttpRequest;if(p.auth){var W=p.auth.username||"",H=p.auth.password?unescape(encodeURIComponent(p.auth.password)):"";v.Authorization="Basic "+btoa(W+":"+H)}var I=i(p.baseURL,p.url);F.open(p.method.toUpperCase(),n(I,p.params,p.paramsSerializer),!0),F.timeout=p.timeout;function S(){if(F){var N="getAllResponseHeaders"in F?s(F.getAllResponseHeaders()):null,ce=!R||R==="text"||R==="json"?F.responseText:F.response,Le={data:ce,status:F.status,statusText:F.statusText,headers:N,config:p,request:F};e(function($){f($),L()},function($){g($),L()},Le),F=null}}if("onloadend"in F?F.onloadend=S:F.onreadystatechange=function(){!F||F.readyState!==4||F.status===0&&!(F.responseURL&&F.responseURL.indexOf("file:")===0)||setTimeout(S)},F.onabort=function(){F&&(g(a("Request aborted",p,"ECONNABORTED",F)),F=null)},F.onerror=function(){g(a("Network Error",p,null,F)),F=null},F.ontimeout=function(){var N=p.timeout?"timeout of "+p.timeout+"ms exceeded":"timeout exceeded",ce=p.transitional||d.transitional;p.timeoutErrorMessage&&(N=p.timeoutErrorMessage),g(a(N,p,ce.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",F)),F=null},t.isStandardBrowserEnv()){var P=(p.withCredentials||o(I))&&p.xsrfCookieName?r.read(p.xsrfCookieName):void 0;P&&(v[p.xsrfHeaderName]=P)}"setRequestHeader"in F&&t.forEach(v,function(N,ce){typeof E=="undefined"&&ce.toLowerCase()==="content-type"?delete v[ce]:F.setRequestHeader(ce,N)}),t.isUndefined(p.withCredentials)||(F.withCredentials=!!p.withCredentials),R&&R!=="json"&&(F.responseType=p.responseType),typeof p.onDownloadProgress=="function"&&F.addEventListener("progress",p.onDownloadProgress),typeof p.onUploadProgress=="function"&&F.upload&&F.upload.addEventListener("progress",p.onUploadProgress),(p.cancelToken||p.signal)&&(A=function(N){F&&(g(!N||N&&N.type?new h("canceled"):N),F.abort(),F=null)},p.cancelToken&&p.cancelToken.subscribe(A),p.signal&&(p.signal.aborted?A():p.signal.addEventListener("abort",A))),E||(E=null),F.send(E)})},pd}var md,Lh;function Wo(){if(Lh)return md;Lh=1;var t=bt,e=mE,r=Th,n={"Content-Type":"application/x-www-form-urlencoded"};function i(d,h){!t.isUndefined(d)&&t.isUndefined(d["Content-Type"])&&(d["Content-Type"]=h)}function s(){var d;return(typeof XMLHttpRequest!="undefined"||typeof process!="undefined"&&Object.prototype.toString.call(process)==="[object process]")&&(d=kE()),d}function o(d,h,p){if(t.isString(d))try{return(h||JSON.parse)(d),t.trim(d)}catch(f){if(f.name!=="SyntaxError")throw f}return(p||JSON.stringify)(d)}var a={transitional:{silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},adapter:s(),transformRequest:[function(d,h){return e(h,"Accept"),e(h,"Content-Type"),t.isFormData(d)||t.isArrayBuffer(d)||t.isBuffer(d)||t.isStream(d)||t.isFile(d)||t.isBlob(d)?d:t.isArrayBufferView(d)?d.buffer:t.isURLSearchParams(d)?(i(h,"application/x-www-form-urlencoded;charset=utf-8"),d.toString()):t.isObject(d)||h&&h["Content-Type"]==="application/json"?(i(h,"application/json"),o(d)):d}],transformResponse:[function(d){var h=this.transitional||a.transitional,p=h&&h.silentJSONParsing,f=h&&h.forcedJSONParsing,g=!p&&this.responseType==="json";if(g||f&&t.isString(d)&&d.length)try{return JSON.parse(d)}catch(E){if(g)throw E.name==="SyntaxError"?r(E,this,"E_JSON_PARSE"):E}return d}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(d){return d>=200&&d<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};return t.forEach(["delete","get","head"],function(d){a.headers[d]={}}),t.forEach(["post","put","patch"],function(d){a.headers[d]=t.merge(n)}),md=a,md}var _E=bt,bE=Wo(),wE=function(t,e,r){var n=this||bE;return _E.forEach(r,function(i){t=i.call(n,t,e)}),t},xh,Fh;function Uh(){return Fh||(Fh=1,xh=function(t){return!!(t&&t.__CANCEL__)}),xh}var Vh=bt,fd=wE,CE=Uh(),IE=Wo(),RE=Ho();function gd(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new RE("canceled")}var PE=function(t){gd(t),t.headers=t.headers||{},t.data=fd.call(t,t.data,t.headers,t.transformRequest),t.headers=Vh.merge(t.headers.common||{},t.headers[t.method]||{},t.headers),Vh.forEach(["delete","get","head","post","put","patch","common"],function(r){delete t.headers[r]});var e=t.adapter||IE.adapter;return e(t).then(function(r){return gd(t),r.data=fd.call(t,r.data,r.headers,t.transformResponse),r},function(r){return CE(r)||(gd(t),r&&r.response&&(r.response.data=fd.call(t,r.response.data,r.response.headers,t.transformResponse))),Promise.reject(r)})},At=bt,Bh=function(t,e){e=e||{};var r={};function n(h,p){return At.isPlainObject(h)&&At.isPlainObject(p)?At.merge(h,p):At.isPlainObject(p)?At.merge({},p):At.isArray(p)?p.slice():p}function i(h){if(At.isUndefined(e[h])){if(!At.isUndefined(t[h]))return n(void 0,t[h])}else return n(t[h],e[h])}function s(h){if(!At.isUndefined(e[h]))return n(void 0,e[h])}function o(h){if(At.isUndefined(e[h])){if(!At.isUndefined(t[h]))return n(void 0,t[h])}else return n(void 0,e[h])}function a(h){if(h in e)return n(t[h],e[h]);if(h in t)return n(void 0,t[h])}var d={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a};return At.forEach(Object.keys(t).concat(Object.keys(e)),function(h){var p=d[h]||i,f=p(h);At.isUndefined(f)&&p!==a||(r[h]=f)}),r},jh,Hh;function Wh(){return Hh||(Hh=1,jh={version:"0.25.0"}),jh}var AE=Wh().version,vd={};["object","boolean","number","function","string","symbol"].forEach(function(t,e){vd[t]=function(r){return typeof r===t||"a"+(e<1?"n ":" ")+t}});var $h={};vd.transitional=function(t,e,r){function n(i,s){return"[Axios v"+AE+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return function(i,s,o){if(t===!1)throw new Error(n(s," has been removed"+(e?" in "+e:"")));return e&&!$h[s]&&($h[s]=!0,console.warn(n(s," has been deprecated since v"+e+" and will be removed in the near future"))),t?t(i,s,o):!0}};function ME(t,e,r){if(typeof t!="object")throw new TypeError("options must be an object");for(var n=Object.keys(t),i=n.length;i-- >0;){var s=n[i],o=e[s];if(o){var a=t[s],d=a===void 0||o(a,s,t);if(d!==!0)throw new TypeError("option "+s+" must be "+d);continue}if(r!==!0)throw Error("Unknown option "+s)}}var DE={assertOptions:ME,validators:vd},Gh=bt,OE=Sh,Jh=hE,qh=PE,$o=Bh,Kh=DE,Ei=Kh.validators;function us(t){this.defaults=t,this.interceptors={request:new Jh,response:new Jh}}us.prototype.request=function(t,e){if(typeof t=="string"?(e=e||{},e.url=t):e=t||{},!e.url)throw new Error("Provided config url is not valid");e=$o(this.defaults,e),e.method?e.method=e.method.toLowerCase():this.defaults.method?e.method=this.defaults.method.toLowerCase():e.method="get";var r=e.transitional;r!==void 0&&Kh.assertOptions(r,{silentJSONParsing:Ei.transitional(Ei.boolean),forcedJSONParsing:Ei.transitional(Ei.boolean),clarifyTimeoutError:Ei.transitional(Ei.boolean)},!1);var n=[],i=!0;this.interceptors.request.forEach(function(f){typeof f.runWhen=="function"&&f.runWhen(e)===!1||(i=i&&f.synchronous,n.unshift(f.fulfilled,f.rejected))});var s=[];this.interceptors.response.forEach(function(f){s.push(f.fulfilled,f.rejected)});var o;if(!i){var a=[qh,void 0];for(Array.prototype.unshift.apply(a,n),a=a.concat(s),o=Promise.resolve(e);a.length;)o=o.then(a.shift(),a.shift());return o}for(var d=e;n.length;){var h=n.shift(),p=n.shift();try{d=h(d)}catch(f){p(f);break}}try{o=qh(d)}catch(f){return Promise.reject(f)}for(;s.length;)o=o.then(s.shift(),s.shift());return o},us.prototype.getUri=function(t){if(!t.url)throw new Error("Provided config url is not valid");return t=$o(this.defaults,t),OE(t.url,t.params,t.paramsSerializer).replace(/^\?/,"")},Gh.forEach(["delete","get","head","options"],function(t){us.prototype[t]=function(e,r){return this.request($o(r||{},{method:t,url:e,data:(r||{}).data}))}}),Gh.forEach(["post","put","patch"],function(t){us.prototype[t]=function(e,r,n){return this.request($o(n||{},{method:t,url:e,data:r}))}});var NE=us,yd,zh;function LE(){if(zh)return yd;zh=1;var t=Ho();function e(r){if(typeof r!="function")throw new TypeError("executor must be a function.");var n;this.promise=new Promise(function(s){n=s});var i=this;this.promise.then(function(s){if(i._listeners){var o,a=i._listeners.length;for(o=0;o<a;o++)i._listeners[o](s);i._listeners=null}}),this.promise.then=function(s){var o,a=new Promise(function(d){i.subscribe(d),o=d}).then(s);return a.cancel=function(){i.unsubscribe(o)},a},r(function(s){i.reason||(i.reason=new t(s),n(i.reason))})}return e.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},e.prototype.subscribe=function(r){if(this.reason){r(this.reason);return}this._listeners?this._listeners.push(r):this._listeners=[r]},e.prototype.unsubscribe=function(r){if(this._listeners){var n=this._listeners.indexOf(r);n!==-1&&this._listeners.splice(n,1)}},e.source=function(){var r,n=new e(function(i){r=i});return{token:n,cancel:r}},yd=e,yd}var Yh,Qh;function xE(){return Qh||(Qh=1,Yh=function(t){return function(e){return t.apply(null,e)}}),Yh}var Ed,Xh;function FE(){if(Xh)return Ed;Xh=1;var t=bt;return Ed=function(e){return t.isObject(e)&&e.isAxiosError===!0},Ed}var Zh=bt,UE=fh,Go=NE,VE=Bh,BE=Wo();function ep(t){var e=new Go(t),r=UE(Go.prototype.request,e);return Zh.extend(r,Go.prototype,e),Zh.extend(r,e),r.create=function(n){return ep(VE(t,n))},r}var ar=ep(BE);ar.Axios=Go,ar.Cancel=Ho(),ar.CancelToken=LE(),ar.isCancel=Uh(),ar.VERSION=Wh().version,ar.all=function(t){return Promise.all(t)},ar.spread=xE(),ar.isAxiosError=FE(),zy.exports=ar,Vo.default=ar,function(t){t.exports=Vo}(Ky);const Jo=uy(td);let tp="hXgU8Wc8pwuGNq9ms5q9Hh";var rp;typeof process!="undefined"&&(rp=process==null?void 0:process.env)!=null&&rp.FLAGSMITH_ENVIRONMENT_KEY&&(tp={}.FLAGSMITH_ENVIRONMENT_KEY);function jE(t=[]){const e={};return t.forEach(r=>{e[r.feature.name]={enabled:r.enabled,value:r.feature_state_value}}),e}class HE{constructor(e=tp){m(this,"flags",{}),m(this,"environmentKey",null),this.environmentKey=e,this.identify=this.identify.bind(this),this.getValue=this.getValue.bind(this),this.hasFeature=this.hasFeature.bind(this),this.getAllFlags=this.getAllFlags.bind(this)}identify(e){return u(this,arguments,function*(r,n={},i=!1,s=5e3,o="edge.api.flagsmith.com"){const a=JSON.parse(JSON.stringify(n)),d=Object.entries(a).map(h=>({trait_key:h[0],trait_value:h[1]}));try{const h="_"+(Math.random()+1).toString(36).substring(2),p=yield Jo.post(`https://${o}/api/v1/identities/`,{identifier:r+(i?h:""),traits:d},{headers:{"Content-Type":"application/json","X-Environment-Key":this.environmentKey},timeout:s});this.flags=jE(p.data.flags||[])}catch(h){}return this.flags})}getValue(e){return this.flags&&this.flags[e]&&this.flags[e].value}hasFeature(e){return this.flags&&this.flags[e]&&this.flags[e].enabled}getAllFlags(){return this.flags}}const K=new HE,np=[-2,-1,0,1,2],WE=[0,1,2,3,4];function $E(t){t=t.trim();let e="0",r="0",n="0";return t.length==4?(e="0x"+t[1]+t[1],r="0x"+t[2]+t[2],n="0x"+t[3]+t[3]):t.length>6&&(e="0x"+t[1]+t[2],r="0x"+t[3]+t[4],n="0x"+t[5]+t[6]),[+e,+r,+n]}const GE=(t,e,r)=>{let n,i,s;if(e==0)n=i=s=r;else{const o=(h,p,f)=>(f<0&&(f+=1),f>1&&(f-=1),f<.16666666666666666?h+(p-h)*6*f:f<.5?p:f<.6666666666666666?h+(p-h)*(.6666666666666666-f)*6:h),a=r<.5?r*(1+e):r+e-r*e,d=2*r-a;n=o(d,a,t+1/3),i=o(d,a,t),s=o(d,a,t-1/3)}return[Math.round(n*255),Math.round(i*255),Math.round(s*255)]},JE=(t,e,r)=>{t/=255,e/=255,r/=255;const n=Math.max(t,e,r),i=Math.min(t,e,r);let s,o;const a=(n+i)/2;if(n==i)s=o=0;else{const d=n-i;switch(o=a>.5?d/(2-n-i):d/(n+i),n){case t:s=(e-r)/d+(e<r?6:0);break;case e:s=(r-t)/d+2;break;case r:s=(t-e)/d+4;break}s/=6}return[s,o,a]},qE=(t,e,r)=>{const n=i=>i.toString(16).padStart(2,"0");return`#${n(t)}${n(e)}${n(r)}`},ip=(t,e=np,r=.4)=>{const n=[],[i,s,o]=$E(t),[a,d,h]=JE(i,s,o),p=Math.round(h*100);p>70?r=.8:p>60?r=.9:p<10?r=.075:p<42&&(r=.3);const f=e.findIndex(A=>A===0);if(f===-1)throw new Error("Invalid reducer provided, it must contain atleast one zero");const g=5-f,E=f+1,v=(100-p)/g,R=p/E;for(const A of e){let L;A<0?L=p+A*R*r:A>0?L=p+A*v*r:L=p;const[F,W,H]=GE(a,d,L/100);n.push(qE(F,W,H))}return n},sp={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"}},KE=t=>{const[e,r,n,i,s]=ip(t,np);return{300:e,400:r,500:n,600:i,700:s}},zE=t=>{if(t==="#FFFFFF")return sp.light.background;if(t==="#000000")return sp.dark.background;const[e,r,n,i,s]=ip(t,WE);return{1e3:e,900:r,800:n,700:i,600:s}};function YE(){this.__data__=[],this.size=0}function qo(t,e){return t===e||t!==t&&e!==e}function Ko(t,e){for(var r=t.length;r--;)if(qo(t[r][0],e))return r;return-1}var QE=Array.prototype,XE=QE.splice;function ZE(t){var e=this.__data__,r=Ko(e,t);if(r<0)return!1;var n=e.length-1;return r==n?e.pop():XE.call(e,r,1),--this.size,!0}function eS(t){var e=this.__data__,r=Ko(e,t);return r<0?void 0:e[r][1]}function tS(t){return Ko(this.__data__,t)>-1}function rS(t,e){var r=this.__data__,n=Ko(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}function Sr(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}Sr.prototype.clear=YE,Sr.prototype.delete=ZE,Sr.prototype.get=eS,Sr.prototype.has=tS,Sr.prototype.set=rS;function nS(){this.__data__=new Sr,this.size=0}function iS(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r}function sS(t){return this.__data__.get(t)}function oS(t){return this.__data__.has(t)}var aS=typeof global=="object"&&global&&global.Object===Object&&global;const op=aS;var cS=typeof self=="object"&&self&&self.Object===Object&&self,dS=op||cS||Function("return this")();const Jt=dS;var lS=Jt.Symbol;const Si=lS;var ap=Object.prototype,uS=ap.hasOwnProperty,hS=ap.toString,hs=Si?Si.toStringTag:void 0;function pS(t){var e=uS.call(t,hs),r=t[hs];try{t[hs]=void 0;var n=!0}catch(s){}var i=hS.call(t);return n&&(e?t[hs]=r:delete t[hs]),i}var mS=Object.prototype,fS=mS.toString;function gS(t){return fS.call(t)}var vS="[object Null]",yS="[object Undefined]",cp=Si?Si.toStringTag:void 0;function yn(t){return t==null?t===void 0?yS:vS:cp&&cp in Object(t)?pS(t):gS(t)}function qt(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var ES="[object AsyncFunction]",SS="[object Function]",TS="[object GeneratorFunction]",kS="[object Proxy]";function Sd(t){if(!qt(t))return!1;var e=yn(t);return e==SS||e==TS||e==ES||e==kS}var _S=Jt["__core-js_shared__"];const Td=_S;var dp=function(){var t=/[^.]+$/.exec(Td&&Td.keys&&Td.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();function bS(t){return!!dp&&dp in t}var wS=Function.prototype,CS=wS.toString;function En(t){if(t!=null){try{return CS.call(t)}catch(e){}try{return t+""}catch(e){}}return""}var IS=/[\\^$.*+?()[\]{}|]/g,RS=/^\[object .+?Constructor\]$/,PS=Function.prototype,AS=Object.prototype,MS=PS.toString,DS=AS.hasOwnProperty,OS=RegExp("^"+MS.call(DS).replace(IS,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function NS(t){if(!qt(t)||bS(t))return!1;var e=Sd(t)?OS:RS;return e.test(En(t))}function LS(t,e){return t==null?void 0:t[e]}function Sn(t,e){var r=LS(t,e);return NS(r)?r:void 0}var xS=Sn(Jt,"Map");const ps=xS;var FS=Sn(Object,"create");const ms=FS;function US(){this.__data__=ms?ms(null):{},this.size=0}function VS(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var BS="__lodash_hash_undefined__",jS=Object.prototype,HS=jS.hasOwnProperty;function WS(t){var e=this.__data__;if(ms){var r=e[t];return r===BS?void 0:r}return HS.call(e,t)?e[t]:void 0}var $S=Object.prototype,GS=$S.hasOwnProperty;function JS(t){var e=this.__data__;return ms?e[t]!==void 0:GS.call(e,t)}var qS="__lodash_hash_undefined__";function KS(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=ms&&e===void 0?qS:e,this}function Tn(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}Tn.prototype.clear=US,Tn.prototype.delete=VS,Tn.prototype.get=WS,Tn.prototype.has=JS,Tn.prototype.set=KS;function zS(){this.size=0,this.__data__={hash:new Tn,map:new(ps||Sr),string:new Tn}}function YS(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function zo(t,e){var r=t.__data__;return YS(e)?r[typeof e=="string"?"string":"hash"]:r.map}function QS(t){var e=zo(this,t).delete(t);return this.size-=e?1:0,e}function XS(t){return zo(this,t).get(t)}function ZS(t){return zo(this,t).has(t)}function eT(t,e){var r=zo(this,t),n=r.size;return r.set(t,e),this.size+=r.size==n?0:1,this}function Ti(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}Ti.prototype.clear=zS,Ti.prototype.delete=QS,Ti.prototype.get=XS,Ti.prototype.has=ZS,Ti.prototype.set=eT;var tT=200;function rT(t,e){var r=this.__data__;if(r instanceof Sr){var n=r.__data__;if(!ps||n.length<tT-1)return n.push([t,e]),this.size=++r.size,this;r=this.__data__=new Ti(n)}return r.set(t,e),this.size=r.size,this}function kn(t){var e=this.__data__=new Sr(t);this.size=e.size}kn.prototype.clear=nS,kn.prototype.delete=iS,kn.prototype.get=sS,kn.prototype.has=oS,kn.prototype.set=rT;function nT(t,e){for(var r=-1,n=t==null?0:t.length;++r<n&&e(t[r],r,t)!==!1;);return t}var iT=function(){try{var t=Sn(Object,"defineProperty");return t({},"",{}),t}catch(e){}}();const Yo=iT;function kd(t,e,r){e=="__proto__"&&Yo?Yo(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}var sT=Object.prototype,oT=sT.hasOwnProperty;function lp(t,e,r){var n=t[e];(!(oT.call(t,e)&&qo(n,r))||r===void 0&&!(e in t))&&kd(t,e,r)}function fs(t,e,r,n){var i=!r;r||(r={});for(var s=-1,o=e.length;++s<o;){var a=e[s],d=n?n(r[a],t[a],a,r,t):void 0;d===void 0&&(d=t[a]),i?kd(r,a,d):lp(r,a,d)}return r}function aT(t,e){for(var r=-1,n=Array(t);++r<t;)n[r]=e(r);return n}function Br(t){return t!=null&&typeof t=="object"}var cT="[object Arguments]";function up(t){return Br(t)&&yn(t)==cT}var hp=Object.prototype,dT=hp.hasOwnProperty,lT=hp.propertyIsEnumerable,uT=up(function(){return arguments}())?up:function(t){return Br(t)&&dT.call(t,"callee")&&!lT.call(t,"callee")};const Qo=uT;var hT=Array.isArray;const ki=hT;function pT(){return!1}var pp=typeof exports=="object"&&exports&&!exports.nodeType&&exports,mp=pp&&typeof module=="object"&&module&&!module.nodeType&&module,mT=mp&&mp.exports===pp,fp=mT?Jt.Buffer:void 0,fT=fp?fp.isBuffer:void 0,gT=fT||pT;const Xo=gT;var vT=9007199254740991,yT=/^(?:0|[1-9]\d*)$/;function gp(t,e){var r=typeof t;return e=e==null?vT:e,!!e&&(r=="number"||r!="symbol"&&yT.test(t))&&t>-1&&t%1==0&&t<e}var ET=9007199254740991;function vp(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=ET}var ST="[object Arguments]",TT="[object Array]",kT="[object Boolean]",_T="[object Date]",bT="[object Error]",wT="[object Function]",CT="[object Map]",IT="[object Number]",RT="[object Object]",PT="[object RegExp]",AT="[object Set]",MT="[object String]",DT="[object WeakMap]",OT="[object ArrayBuffer]",NT="[object DataView]",LT="[object Float32Array]",xT="[object Float64Array]",FT="[object Int8Array]",UT="[object Int16Array]",VT="[object Int32Array]",BT="[object Uint8Array]",jT="[object Uint8ClampedArray]",HT="[object Uint16Array]",WT="[object Uint32Array]",Ce={};Ce[LT]=Ce[xT]=Ce[FT]=Ce[UT]=Ce[VT]=Ce[BT]=Ce[jT]=Ce[HT]=Ce[WT]=!0,Ce[ST]=Ce[TT]=Ce[OT]=Ce[kT]=Ce[NT]=Ce[_T]=Ce[bT]=Ce[wT]=Ce[CT]=Ce[IT]=Ce[RT]=Ce[PT]=Ce[AT]=Ce[MT]=Ce[DT]=!1;function $T(t){return Br(t)&&vp(t.length)&&!!Ce[yn(t)]}function _d(t){return function(e){return t(e)}}var yp=typeof exports=="object"&&exports&&!exports.nodeType&&exports,gs=yp&&typeof module=="object"&&module&&!module.nodeType&&module,GT=gs&&gs.exports===yp,bd=GT&&op.process,JT=function(){try{var t=gs&&gs.require&&gs.require("util").types;return t||bd&&bd.binding&&bd.binding("util")}catch(e){}}();const _i=JT;var Ep=_i&&_i.isTypedArray,qT=Ep?_d(Ep):$T;const wd=qT;var KT=Object.prototype,zT=KT.hasOwnProperty;function Sp(t,e){var r=ki(t),n=!r&&Qo(t),i=!r&&!n&&Xo(t),s=!r&&!n&&!i&&wd(t),o=r||n||i||s,a=o?aT(t.length,String):[],d=a.length;for(var h in t)(e||zT.call(t,h))&&!(o&&(h=="length"||i&&(h=="offset"||h=="parent")||s&&(h=="buffer"||h=="byteLength"||h=="byteOffset")||gp(h,d)))&&a.push(h);return a}var YT=Object.prototype;function Zo(t){var e=t&&t.constructor,r=typeof e=="function"&&e.prototype||YT;return t===r}function Tp(t,e){return function(r){return t(e(r))}}var QT=Tp(Object.keys,Object);const XT=QT;var ZT=Object.prototype,ek=ZT.hasOwnProperty;function kp(t){if(!Zo(t))return XT(t);var e=[];for(var r in Object(t))ek.call(t,r)&&r!="constructor"&&e.push(r);return e}function vs(t){return t!=null&&vp(t.length)&&!Sd(t)}function Cd(t){return vs(t)?Sp(t):kp(t)}function tk(t,e){return t&&fs(e,Cd(e),t)}function rk(t){var e=[];if(t!=null)for(var r in Object(t))e.push(r);return e}var nk=Object.prototype,ik=nk.hasOwnProperty;function sk(t){if(!qt(t))return rk(t);var e=Zo(t),r=[];for(var n in t)n=="constructor"&&(e||!ik.call(t,n))||r.push(n);return r}function ys(t){return vs(t)?Sp(t,!0):sk(t)}function ok(t,e){return t&&fs(e,ys(e),t)}var _p=typeof exports=="object"&&exports&&!exports.nodeType&&exports,bp=_p&&typeof module=="object"&&module&&!module.nodeType&&module,ak=bp&&bp.exports===_p,wp=ak?Jt.Buffer:void 0,Cp=wp?wp.allocUnsafe:void 0;function Ip(t,e){if(e)return t.slice();var r=t.length,n=Cp?Cp(r):new t.constructor(r);return t.copy(n),n}function Rp(t,e){var r=-1,n=t.length;for(e||(e=Array(n));++r<n;)e[r]=t[r];return e}function ck(t,e){for(var r=-1,n=t==null?0:t.length,i=0,s=[];++r<n;){var o=t[r];e(o,r,t)&&(s[i++]=o)}return s}function Pp(){return[]}var dk=Object.prototype,lk=dk.propertyIsEnumerable,Ap=Object.getOwnPropertySymbols,uk=Ap?function(t){return t==null?[]:(t=Object(t),ck(Ap(t),function(e){return lk.call(t,e)}))}:Pp;const Id=uk;function hk(t,e){return fs(t,Id(t),e)}function Mp(t,e){for(var r=-1,n=e.length,i=t.length;++r<n;)t[i+r]=e[r];return t}var pk=Tp(Object.getPrototypeOf,Object);const Rd=pk;var mk=Object.getOwnPropertySymbols,fk=mk?function(t){for(var e=[];t;)Mp(e,Id(t)),t=Rd(t);return e}:Pp;const Dp=fk;function gk(t,e){return fs(t,Dp(t),e)}function Op(t,e,r){var n=e(t);return ki(t)?n:Mp(n,r(t))}function vk(t){return Op(t,Cd,Id)}function yk(t){return Op(t,ys,Dp)}var Ek=Sn(Jt,"DataView");const Pd=Ek;var Sk=Sn(Jt,"Promise");const Ad=Sk;var Tk=Sn(Jt,"Set");const Md=Tk;var kk=Sn(Jt,"WeakMap");const Dd=kk;var Np="[object Map]",_k="[object Object]",Lp="[object Promise]",xp="[object Set]",Fp="[object WeakMap]",Up="[object DataView]",bk=En(Pd),wk=En(ps),Ck=En(Ad),Ik=En(Md),Rk=En(Dd),_n=yn;(Pd&&_n(new Pd(new ArrayBuffer(1)))!=Up||ps&&_n(new ps)!=Np||Ad&&_n(Ad.resolve())!=Lp||Md&&_n(new Md)!=xp||Dd&&_n(new Dd)!=Fp)&&(_n=function(t){var e=yn(t),r=e==_k?t.constructor:void 0,n=r?En(r):"";if(n)switch(n){case bk:return Up;case wk:return Np;case Ck:return Lp;case Ik:return xp;case Rk:return Fp}return e});const ea=_n;var Pk=Object.prototype,Ak=Pk.hasOwnProperty;function Mk(t){var e=t.length,r=new t.constructor(e);return e&&typeof t[0]=="string"&&Ak.call(t,"index")&&(r.index=t.index,r.input=t.input),r}var Dk=Jt.Uint8Array;const Vp=Dk;function Od(t){var e=new t.constructor(t.byteLength);return new Vp(e).set(new Vp(t)),e}function Ok(t,e){var r=e?Od(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.byteLength)}var Nk=/\w*$/;function Lk(t){var e=new t.constructor(t.source,Nk.exec(t));return e.lastIndex=t.lastIndex,e}var Bp=Si?Si.prototype:void 0,jp=Bp?Bp.valueOf:void 0;function xk(t){return jp?Object(jp.call(t)):{}}function Hp(t,e){var r=e?Od(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.length)}var Fk="[object Boolean]",Uk="[object Date]",Vk="[object Map]",Bk="[object Number]",jk="[object RegExp]",Hk="[object Set]",Wk="[object String]",$k="[object Symbol]",Gk="[object ArrayBuffer]",Jk="[object DataView]",qk="[object Float32Array]",Kk="[object Float64Array]",zk="[object Int8Array]",Yk="[object Int16Array]",Qk="[object Int32Array]",Xk="[object Uint8Array]",Zk="[object Uint8ClampedArray]",e_="[object Uint16Array]",t_="[object Uint32Array]";function r_(t,e,r){var n=t.constructor;switch(e){case Gk:return Od(t);case Fk:case Uk:return new n(+t);case Jk:return Ok(t,r);case qk:case Kk:case zk:case Yk:case Qk:case Xk:case Zk:case e_:case t_:return Hp(t,r);case Vk:return new n;case Bk:case Wk:return new n(t);case jk:return Lk(t);case Hk:return new n;case $k:return xk(t)}}var Wp=Object.create,n_=function(){function t(){}return function(e){if(!qt(e))return{};if(Wp)return Wp(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();const i_=n_;function $p(t){return typeof t.constructor=="function"&&!Zo(t)?i_(Rd(t)):{}}var s_="[object Map]";function o_(t){return Br(t)&&ea(t)==s_}var Gp=_i&&_i.isMap,a_=Gp?_d(Gp):o_;const c_=a_;var d_="[object Set]";function l_(t){return Br(t)&&ea(t)==d_}var Jp=_i&&_i.isSet,u_=Jp?_d(Jp):l_;const h_=u_;var p_=1,m_=2,f_=4,qp="[object Arguments]",g_="[object Array]",v_="[object Boolean]",y_="[object Date]",E_="[object Error]",Kp="[object Function]",S_="[object GeneratorFunction]",T_="[object Map]",k_="[object Number]",zp="[object Object]",__="[object RegExp]",b_="[object Set]",w_="[object String]",C_="[object Symbol]",I_="[object WeakMap]",R_="[object ArrayBuffer]",P_="[object DataView]",A_="[object Float32Array]",M_="[object Float64Array]",D_="[object Int8Array]",O_="[object Int16Array]",N_="[object Int32Array]",L_="[object Uint8Array]",x_="[object Uint8ClampedArray]",F_="[object Uint16Array]",U_="[object Uint32Array]",be={};be[qp]=be[g_]=be[R_]=be[P_]=be[v_]=be[y_]=be[A_]=be[M_]=be[D_]=be[O_]=be[N_]=be[T_]=be[k_]=be[zp]=be[__]=be[b_]=be[w_]=be[C_]=be[L_]=be[x_]=be[F_]=be[U_]=!0,be[E_]=be[Kp]=be[I_]=!1;function ta(t,e,r,n,i,s){var o,a=e&p_,d=e&m_,h=e&f_;if(r&&(o=i?r(t,n,i,s):r(t)),o!==void 0)return o;if(!qt(t))return t;var p=ki(t);if(p){if(o=Mk(t),!a)return Rp(t,o)}else{var f=ea(t),g=f==Kp||f==S_;if(Xo(t))return Ip(t,a);if(f==zp||f==qp||g&&!i){if(o=d||g?{}:$p(t),!a)return d?gk(t,ok(o,t)):hk(t,tk(o,t))}else{if(!be[f])return i?t:{};o=r_(t,f,a)}}s||(s=new kn);var E=s.get(t);if(E)return E;s.set(t,o),h_(t)?t.forEach(function(A){o.add(ta(A,e,r,A,t,s))}):c_(t)&&t.forEach(function(A,L){o.set(L,ta(A,e,r,L,t,s))});var v=h?d?yk:vk:d?ys:Cd,R=p?void 0:v(t);return nT(R||t,function(A,L){R&&(L=A,A=t[L]),lp(o,L,ta(A,e,r,L,t,s))}),o}var V_=1,B_=4;function Nd(t){return ta(t,V_|B_)}var j_="[object Symbol]";function H_(t){return typeof t=="symbol"||Br(t)&&yn(t)==j_}const W_={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:KE("#2160FD"),background:zE("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function Yp(){return Nd(W_)}const $_={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:xo.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:q.Allowed,can_consume:Fo.Allowed},audio:{can_produce:q.Allowed},screenshare:{can_produce:q.Allowed,can_consume:Fo.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:vi.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:Yp(),config_diff:{}},config:{view_type:We.GroupCall,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},version:"hybrid"};function G_(){return Nd($_)}vi.none,Uo.skip;const J_={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:xo.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:q.Allowed},audio:{can_produce:q.Allowed},screenshare:{can_produce:q.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:vi.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:Yp(),config_diff:{}},config:{view_type:We.GroupCall,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},version:"2.0.0"};function Ld(){return Nd(J_)}var q_=/\s/;function K_(t){for(var e=t.length;e--&&q_.test(t.charAt(e)););return e}var z_=/^\s+/;function Y_(t){return t&&t.slice(0,K_(t)+1).replace(z_,"")}var Qp=0/0,Q_=/^[-+]0x[0-9a-f]+$/i,X_=/^0b[01]+$/i,Z_=/^0o[0-7]+$/i,eb=parseInt;function Xp(t){if(typeof t=="number")return t;if(H_(t))return Qp;if(qt(t)){var e=typeof t.valueOf=="function"?t.valueOf():t;t=qt(e)?e+"":e}if(typeof t!="string")return t===0?t:+t;t=Y_(t);var r=X_.test(t);return r||Z_.test(t)?eb(t.slice(2),r?2:8):Q_.test(t)?Qp:+t}function Zp(t){return t}function tb(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}var rb=800,nb=16,ib=Date.now;function sb(t){var e=0,r=0;return function(){var n=ib(),i=nb-(n-r);if(r=n,i>0){if(++e>=rb)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function ob(t){return function(){return t}}var ab=Yo?function(t,e){return Yo(t,"toString",{configurable:!0,enumerable:!1,value:ob(e),writable:!0})}:Zp,cb=sb(ab);const db=cb;var em=Math.max;function lb(t,e,r){return e=em(e===void 0?t.length-1:e,0),function(){for(var n=arguments,i=-1,s=em(n.length-e,0),o=Array(s);++i<s;)o[i]=n[e+i];i=-1;for(var a=Array(e+1);++i<e;)a[i]=n[i];return a[e]=r(o),tb(t,this,a)}}function ub(t,e){return db(lb(t,e,Zp),t+"")}function hb(t,e,r){if(!qt(r))return!1;var n=typeof e;return(n=="number"?vs(r)&&gp(e,r.length):n=="string"&&e in r)?qo(r[e],t):!1}function pb(t){return ub(function(e,r){var n=-1,i=r.length,s=i>1?r[i-1]:void 0,o=i>2?r[2]:void 0;for(s=t.length>3&&typeof s=="function"?(i--,s):void 0,o&&hb(r[0],r[1],o)&&(s=i<3?void 0:s,i=1),e=Object(e);++n<i;){var a=r[n];a&&t(e,a,n,s)}return e})}var mb="[object Object]",fb=Function.prototype,gb=Object.prototype,tm=fb.toString,vb=gb.hasOwnProperty,yb=tm.call(Object);function Eb(t){if(!Br(t)||yn(t)!=mb)return!1;var e=Rd(t);if(e===null)return!0;var r=vb.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&tm.call(r)==yb}function Sb(t){return function(e,r,n){for(var i=-1,s=Object(e),o=n(e),a=o.length;a--;){var d=o[t?a:++i];if(r(s[d],d,s)===!1)break}return e}}var Tb=Sb();const kb=Tb;var _b=function(){return Jt.Date.now()};const xd=_b;var bb="Expected a function",wb=Math.max,Cb=Math.min;function cr(t,e,r){var n,i,s,o,a,d,h=0,p=!1,f=!1,g=!0;if(typeof t!="function")throw new TypeError(bb);e=Xp(e)||0,qt(r)&&(p=!!r.leading,f="maxWait"in r,s=f?wb(Xp(r.maxWait)||0,e):s,g="trailing"in r?!!r.trailing:g);function E(S){var P=n,N=i;return n=i=void 0,h=S,o=t.apply(N,P),o}function v(S){return h=S,a=setTimeout(L,e),p?E(S):o}function R(S){var P=S-d,N=S-h,ce=e-P;return f?Cb(ce,s-N):ce}function A(S){var P=S-d,N=S-h;return d===void 0||P>=e||P<0||f&&N>=s}function L(){var S=xd();if(A(S))return F(S);a=setTimeout(L,R(S))}function F(S){return a=void 0,g&&n?E(S):(n=i=void 0,o)}function W(){a!==void 0&&clearTimeout(a),h=0,n=d=i=a=void 0}function H(){return a===void 0?o:F(xd())}function I(){var S=xd(),P=A(S);if(n=arguments,i=this,d=S,P){if(a===void 0)return v(d);if(f)return clearTimeout(a),a=setTimeout(L,e),E(d)}return a===void 0&&(a=setTimeout(L,e)),o}return I.cancel=W,I.flush=H,I}function Fd(t,e,r){(r!==void 0&&!qo(t[e],r)||r===void 0&&!(e in t))&&kd(t,e,r)}function Ib(t){return Br(t)&&vs(t)}function Ud(t,e){if(!(e==="constructor"&&typeof t[e]=="function")&&e!="__proto__")return t[e]}function Rb(t){return fs(t,ys(t))}function Pb(t,e,r,n,i,s,o){var a=Ud(t,r),d=Ud(e,r),h=o.get(d);if(h){Fd(t,r,h);return}var p=s?s(a,d,r+"",t,e,o):void 0,f=p===void 0;if(f){var g=ki(d),E=!g&&Xo(d),v=!g&&!E&&wd(d);p=d,g||E||v?ki(a)?p=a:Ib(a)?p=Rp(a):E?(f=!1,p=Ip(d,!0)):v?(f=!1,p=Hp(d,!0)):p=[]:Eb(d)||Qo(d)?(p=a,Qo(a)?p=Rb(a):(!qt(a)||Sd(a))&&(p=$p(d))):f=!1}f&&(o.set(d,p),i(p,d,n,s,o),o.delete(d)),Fd(t,r,p)}function rm(t,e,r,n,i){t!==e&&kb(e,function(s,o){if(i||(i=new kn),qt(s))Pb(t,e,o,r,rm,n,i);else{var a=n?n(Ud(t,o),s,o+"",t,e,i):void 0;a===void 0&&(a=s),Fd(t,o,a)}},ys)}var Ab="[object Map]",Mb="[object Set]",Db=Object.prototype,Ob=Db.hasOwnProperty;function Nb(t){if(t==null)return!0;if(vs(t)&&(ki(t)||typeof t=="string"||typeof t.splice=="function"||Xo(t)||wd(t)||Qo(t)))return!t.length;var e=ea(t);if(e==Ab||e==Mb)return!t.size;if(Zo(t))return!kp(t).length;for(var r in t)if(Ob.call(t,r))return!1;return!0}var Lb=pb(function(t,e,r){rm(t,e,r)});const jr=Lb;var Vd=(t=>(t.PARTICIPANT="PARTICIPANT",t.PEER="PEER",t.CLIENT="CLIENT",t))(Vd||{});const X={REFRESH_ID_ON_DISCONNECTION:"refresh_id_on_disconnection",INTERNAL_CALL_STATS:"internal_call_stats",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",CONNECTED_MEETINGS:"connected_meetings",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"};function ra(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 nm(t){var e,r,n,i;const s=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((e=window.location.host)==null?void 0:e.includes("devel"))&&((r=window.location.host)==null?void 0:r.includes("dyte.io")),o=!!((i=(n=t.getValue("modules"))==null?void 0:n.devTools)!=null&&i.logs);return s||o}function xb(t){if(K.hasFeature(X.LOG_LEVEL)){let e=K.getValue(X.LOG_LEVEL)||"all";if(e=e.toLowerCase().trim(),e==="off")return!1;if(e!=="all"){const r=["debug","log","info","warn","error"],n=r.indexOf(t),i=r.indexOf(e);if(n<i)return!1}}return!0}function im(t,e,r={}){return Object.getOwnPropertyNames(t).forEach(n=>{var i;if([null,void 0,NaN].includes(t[n])||e&&(((i=e.match(/\./g))==null?void 0:i.length)||0)>=10)return;const s=e?`${e}.${n}`:n;typeof t[n]=="object"?im(t[n],s,r):["number","string","boolean"].includes(typeof t[n])&&(r[s]=t[n])}),r}function sm(t,e,r={},n=""){const i={};try{const s=JSON.stringify(r),o=JSON.parse(s),a=im(o,n),d=JSON.stringify(a);if(d.length>5e3){const h=`Log named: "${e}" is trying to log an flattened object of size
14
- ${d.length} chars that is beyond permitted limit of 5000 chars. Please optimize.`;throw nm(t)&&console.error(h,{log:r,flattened:d}),new Error(h)}return JSON.parse(d)}catch(s){const o=ra(s);i[`${n}.error.message`]=o.message||"",i[`${n}.error.stack`]=o.stack||"",i[`${n}.error.reason`]=o.reason||"",i[`${n}.error.source`]="safelyFlattenObjForOpenTelemetry"}return i}const Es="chrome",om="opera",am="firefox",cm="iexplorer",dm="safari",lm="nwjs",um="electron",hm="react-native",Bd="unknown",na={Chrome:Es,Chromium:Es,Opera:om,Firefox:am,"Internet Explorer":cm,Safari:dm};function Fb(){const{userAgent:t}=navigator,e={name:Bd,version:void 0};if(t.match(/Chrome/)&&!t.match(/Edge/))if(t.match(/Edg(A?)/)){const r=t.match(/Chrome\/([\d.]+)/)[1];Number.parseInt(r,10)>72&&(e.name=Es,e.version=r)}else e.name=Es,e.version=t.match(/Chrome\/([\d.]+)/)[1];return e}function Ub(){const{userAgent:t}=navigator;if(t.match(/Electron/)){const e=t.match(/Electron\/([\d.]+)/)[1];return{name:um,version:e}}return null}function Vb(){const{userAgent:t}=navigator;if(t.match(/JitsiMeetNW/)){const e=t.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:lm,version:e}}}function Bb(){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:hm,version:e}}function jb(t){let e;const r=[Bb,Ub,Vb];for(let i=0;i<r.length;i+=1)if(e=r[i](),e)return e;const n=t.getBrowserName();return n in na?{name:na[n],version:t.getBrowserVersion()}:(e=Fb(),e||{name:Bd,version:void 0})}class Hb{constructor(){m(this,"_bowser"),m(this,"_name"),m(this,"_version"),m(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 r,n;if(this._bowser=lu.getParser(navigator.userAgent),typeof e=="undefined"){const i=jb(this._bowser);r=i.name,n=i.version}else e.name in na?(r=na[e.name],n=e.version):(r=Bd,n=void 0);this._name=r,this._version=n}getName(){return this._name}isChrome(){return this._name===Es}isOpera(){return this._name===om}isFirefox(){return this._name===am}isIExplorer(){return this._name===cm}isSafari(){return this._name===dm}isNWJS(){return this._name===lm}isElectron(){return this._name===um}isReactNative(){return this._name===hm||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 Wb extends Hb{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(r){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(process.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 ye=new Wb,jd={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},Ss={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"},$b={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 pm(t,e){const r=t.getValue("overrides");return r&&r[e]?r[e]:!1}function Gb({baseURI:t}){return t!=null&&t.includes("preprod.dyte")?ls.PREPROD:t!=null&&t.includes("devel.dyte")?ls.DEVEL:ls.PROD}function bi({servicePrefix:t,baseURI:e}){return`${t}.${e}`}function mm(t){const e=t.getValue("baseURI");return{location:bi({servicePrefix:"location",baseURI:e}),locationLegacy:bi({servicePrefix:"location-legacy",baseURI:e}),daCollector:bi({servicePrefix:"da-collector",baseURI:e})}}function Jb(t){const e=V({},t),r=new Map,n=(o,a)=>(r.has(o)||r.set(o,new Set),r.get(o).add(a),()=>{var d;return(d=r.get(o))==null?void 0:d.delete(a)}),i=(o,a)=>{var d;(d=r.get(o))==null||d.delete(a)},s=o=>{var a;(a=r.get(o))==null||a.forEach(d=>{try{d(e[o])}catch(h){l.error(`Error in notifying for "${o.toString()}"`,h)}})};return{subscribe:n,unsubscribe:i,notify:s,setValue:(o,a,d=!0)=>{e[o]=a,d&&s(o)},getValue:o=>e[o],getAllValues:()=>e}}class qb{constructor(){m(this,"contexts",new Map)}createContext(e,r){return this.contexts.has(e)?this.contexts.get(e):(this.contexts.set(e,Jb(r)),this.contexts.get(e))}remapContext(e,r){const n=r.getValue("peerId");n!==e&&(r.setValue("peerId",e),this.contexts.set(e,r),this.contexts.delete(n))}getContext(e){return this.contexts.get(e)}}const Ts=new qb,me=class{static get logsEndpoint(){const t=Ts.getContext(me.meetingMetadata.peerId);return`https://${bi({servicePrefix:"api-silos",baseURI:t.getValue("baseURI")})}/otel/logs`}static resetPeerId(t){me.meetingMetadata.peerId=t}static init(t,e){const r=t.getValue("peerId");me.tracingEnabled=e,me.meetingMetadata.peerId=r,me.meetingMetadata.sdkVersion=t.getValue("sdkVersion"),me.meetingMetadata.deviceInfo=ye.getDeviceInfo(),me.meetingMetadata.visitedUrl=!navigator.isReactNative&&typeof window!="undefined"&&window.location.href,navigator.isReactNative||document.addEventListener("visibilitychange",me.processCachedLogs),me.logsProcessorTimer=setInterval(me.processCachedLogs,me.logsProcessingInterval),e&&(me.initialized=!0)}static trace(t){return(e,r,n)=>{const i=n.value;return n.value=function(...s){if(!me.initialized||navigator.isReactNative||!me.tracingEnabled||K.hasFeature(X.SKIP_OTEL_TRACES))return i.apply(this,s);me.addLogInCurrentSpan("info",t);const o=performance.now(),a=i.apply(this,s);return Promise.resolve(a).then(()=>{const d=performance.now();d-o>10&&me.addLogInCurrentSpan("info",`${t}_timing`,{execTime:d-o})}).catch(()=>{const d=performance.now();me.addLogInCurrentSpan("info",`${t}_timing`,{execTime:d-o})}),a},n}}static injectContext(t){var e;const r=gn().replace(/-/g,"").substring(0,16),n=(e=me.meetingMetadata.peerId)==null?void 0:e.replace(/-/g,"");t.TRACEPARENT=`00-${n}-${r}-01`}static addLogInCurrentSpan(t,e,r={},n=!1){r!=null&&r.error&&Object.assign(r,{error:ra(r.error)});const i=Ts.getContext(me.meetingMetadata.peerId);if(nm(i)&&(Nb(r)?console[t]("DyteInternalLogs:: ",t,e):console[t]("DyteInternalLogs:: ",t,e,r)),!!xb(t))try{const s=sm(i,e,r,"metadata"),o=new Date,a=ne(V({message:e,level:t},s),{loggedAt:o.toISOString(),loggedAtTzOffset:o.getTimezoneOffset()});n?me.sendOtelLogsToNewRelic([a]):me.logsCache.push(a)}catch(s){me.addLogInCurrentSpan("error","opentelemetry::addLogInCurrentSpan_failed",{error:ra(s)})}}static sendOtelLogsToNewRelic(t){const e=Ts.getContext(me.meetingMetadata.peerId);Jo.post(me.logsEndpoint,{meetingMetadata:sm(e,"sendOtelLogsToNewRelic",me.meetingMetadata,"meetingMetadata"),serviceName:e.getValue("sdkName"),logs:t}).catch(r=>{me.addLogInCurrentSpan("error","opentelemetry::sendOtelLogToNewRelic_failed",{error:ra(r)}),me.logsCache.push(...t)})}static processCachedLogs(){const t=me.logsCache.splice(0,25);t!=null&&t.length&&me.sendOtelLogsToNewRelic(t)}static destruct(){clearInterval(me.logsProcessorTimer),me.processCachedLogs(),navigator.isReactNative||document.removeEventListener("visibilitychange",me.processCachedLogs)}};let y=me;m(y,"logsCache",[]),m(y,"logsProcessorTimer"),m(y,"tracingEnabled",!0),m(y,"initialized",!1),m(y,"logsProcessingInterval",7e3),m(y,"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"]),m(y,"meetingMetadata",{});class l{static info(e,r,n){y.addLogInCurrentSpan("info",e,r,n)}static error(e,r,n){y.addLogInCurrentSpan("error",e,r,n)}static debug(e,r,n){y.addLogInCurrentSpan("debug",e,r,n)}static log(e,r,n){y.addLogInCurrentSpan("log",e,r,n)}static warn(e,r,n){y.addLogInCurrentSpan("warn",e,r,n)}}const Kb=()=>{!navigator.isReactNative&&typeof window!="undefined"&&(window.addEventListener("error",t=>{var e;!((e=t.filename)!=null&&e.includes("localhost"))&&t.lineno!==0&&l.error("window::error",{error:t.error},!0)}),window.addEventListener("unhandledrejection",t=>{var e,r,n,i,s,o,a,d;l.error("window::unhandledrejection",{error:t==null?void 0:t.reason,networkCall:{url:(r=(e=t==null?void 0:t.reason)==null?void 0:e.config)==null?void 0:r.url,baseURL:(i=(n=t==null?void 0:t.reason)==null?void 0:n.config)==null?void 0:i.baseURL,method:(o=(s=t==null?void 0:t.reason)==null?void 0:s.config)==null?void 0:o.method,status:(a=t==null?void 0:t.reason)==null?void 0:a.status,statusText:(d=t==null?void 0:t.reason)==null?void 0:d.statusText}},!0)}),window.addEventListener("offline",()=>{l.info("window::offline")}),window.addEventListener("online",()=>{l.info("window::online")}))},zb={"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"},ia={"0000":"Internal exception.","0001":"Failed to initialize.","0002":"Failed to join room.","0003":"Failed to leave room.","0010":"Browser not supported","0011":"HTTP Network Error","0012":"Websocket Network Error","0100":"Internal exception","0200":"Internal exception.","0300":"Internal exception","0400":"Internal exception","0500":"Internal exception","0501":"Permission denied.","0502":"Invalid message body.","0510":"Invalid channel name.","0600":"Internal exception","0700":"Internal exception","0800":"Internal exception","0900":"Internal exception",1e3:"Internal exception",1100:"Internal exception",1200:"Internal exception",1300:"Internal exception",1400:"Internal exception",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",1701:"Crypto error",9900:"Internal exception"};Object.keys(ia).forEach(t=>{ia[t]=`{${zb[t.slice(0,2)]}} ${ia[t]}`});class C extends Error{constructor(e,r,n=!1){super(e),m(this,"code"),this.code=r,this.name="DyteError",this.message=`[ERR${this.code}]: ${ia[this.code]}
15
- ${this.message}`;try{let i=n;r&&r.endsWith("00")&&(i=!0),i&&l.error("DyteError",{error:{message:this.message,name:this.name,code:r}})}catch(i){}}}function sa(t,e,r,n){if(n instanceof C){if(navigator.isReactNative||typeof reportError!="function")throw n;reportError(n)}else if(n instanceof e){const i=new C(n.message,r);throw i.stack=n.stack,i}else throw n}function fm(t,e,r){if(!t.value){const i=t.get,s=t.set;return i&&(t.get=function(){try{return i.apply(this)}catch(o){sa(this,e,r,o)}}),s&&(t.set=function(o){try{return s.apply(this,[o])}catch(a){sa(this,e,r,a)}}),t}const n=t.value;return t.value=function(...i){try{const s=n.apply(this,i);return s&&s instanceof Promise?s.catch(o=>{sa(this,e,r,o)}):s}catch(s){sa(this,e,r,s)}},t}function Yb(t,e){return(r,n,i)=>{if(i)return fm(i,t,e);for(const s of Reflect.ownKeys(r.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(r.prototype,s);(o.value instanceof Function||o.get instanceof Function||o.set instanceof Function)&&Object.defineProperty(r.prototype,s,fm(o,t,e))}}}const dt=t=>Yb(Error,t);function Qb(t){let e=0,r,n;if(!t)return e;for(r=0;r<t.length;r+=1)n=t.charCodeAt(r),e=(e<<5)-e+n,e|=0;return Math.abs(e)%100+1}var Hr,Wr;const gm=class extends _t.EventEmitter{constructor(){super(),_(this,Hr,void 0),_(this,Wr,void 0),m(this,"asyncPromiseTimeout"),T(this,Hr,new Map),T(this,Wr,new Map),this.asyncPromiseTimeout=8e3}emitAsync(t,...e){return u(this,null,function*(){c(this,Hr).set(t,[]);const r=c(this,Wr).get(t).map(()=>new Promise(n=>{c(this,Hr).get(t).push(n)}));ly(gm.prototype,this,"emit").call(this,t,...e),yield Promise.race([Promise.all(r),new Promise((n,i)=>setTimeout(()=>i(new Error(`emitAsync failed to resolve for event ${t}.`)),this.asyncPromiseTimeout))]),c(this,Hr).delete(t)})}onAsync(t,e){const r=c(this,Hr),n=(...i)=>u(this,null,function*(){var s;try{yield e(...i)}catch(a){l.error("[onAsync]",{error:a})}const o=(s=r.get(t))==null?void 0:s.shift();o==null||o()});return c(this,Wr).get(t)||c(this,Wr).set(t,[]),c(this,Wr).get(t).push(n),super.on(t,n)}reset(){T(this,Hr,new Map),T(this,Wr,new Map),super.removeAllListeners()}};let Xb=gm;Hr=new WeakMap,Wr=new WeakMap;const b=new Xb;function Zb(){ye.isElectron()&&window.dyteElectronGetDisplayMediaSource&&(navigator.mediaDevices.getDisplayMedia=()=>u(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 r=e.find(i=>{var s;return(s=i.id)==null?void 0:s.includes("screen")});r=r!=null?r:e[0];const n={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:r.id}}};return yield navigator.mediaDevices.getUserMedia(n)}))}var Mt;(function(t){t[t.PUBLISHER=0]="PUBLISHER",t[t.SUBSCRIBER=1]="SUBSCRIBER"})(Mt||(Mt={}));var wt;(function(t){t[t.AUDIO=0]="AUDIO",t[t.VIDEO=1]="VIDEO"})(wt||(wt={}));class ew extends k{constructor(){super("media.Codec",[])}}new ew;class tw extends k{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new tw;class rw extends k{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",Mt]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const Kt=new rw;class nw extends k{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:()=>Kt}])}}const vm=new nw;class iw extends k{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Kt},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8}])}}const Hd=new iw;class sw extends k{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Kt}])}}const ym=new sw;class ow extends k{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Kt}])}}new ow;class aw extends k{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 cw=new aw;class dw extends k{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 lw=new dw;class uw extends k{constructor(){super("media.ProducerEntry",[{no:1,name:"producing_transport_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9}])}}new uw;class hw extends k{constructor(){super("media.ConsumerEntry",[{no:1,name:"consuming_transport_id",kind:"scalar",T:9},{no:2,name:"consumer_id",kind:"scalar",T:9}])}}new hw;class pw extends k{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",wt]},{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}])}}const ks=new pw;class mw extends k{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>ks},{no:3,name:"producer_track",kind:"message",T:()=>lw}])}}const fw=new mw;class gw extends k{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>fw}}])}}const Em=new gw;class vw extends k{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 yw=new vw;class Ew extends k{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:()=>yw}])}}const Sm=new Ew;class Sw extends k{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const Tm=new Sw;class Tw extends k{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const km=new Tw;class kw extends k{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 kw;class _w extends k{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}])}}const _m=new _w;class bw extends k{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:()=>Kt},{no:5,name:"msid",kind:"scalar",T:9},{no:6,name:"app_data",kind:"scalar",opt:!0,T:9}])}}const bm=new bw;class ww extends k{constructor(){super("media.edge.SelectedPeersRequest",[])}}new ww;class Cw extends k{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const wm=new Cw;class Iw extends k{constructor(){super("media.edge.ProducerToggleRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const $r=new Iw;class Rw extends k{constructor(){super("media.edge.ConsumerToggleRequest",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const oa=new Rw;class Pw extends k{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Kt}])}}const Cm=new Pw;class Aw extends k{constructor(){super("media.edge.ConsumerCloseRequest",[{no:1,name:"consumer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"description",kind:"message",T:()=>Kt}])}}const Im=new Aw;class Mw extends k{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Rm=new Mw;class Dw extends k{constructor(){super("media.edge.KickAllPeersRequest",[])}}const Pm=new Dw;class Ow extends k{constructor(){super("media.edge.PeerDisplayNameEditRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}const Am=new Ow;class Nw extends k{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 Mm=new Nw;class Lw extends k{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 Dm=new Lw;class xw extends k{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 Fw=new xw;class Uw extends k{constructor(){super("media.edge.ErrorResponse",[{no:1,name:"error_message",kind:"scalar",T:9},{no:2,name:"event_id",kind:"scalar",T:5}])}}const Vw=new Uw;class Bw extends k{constructor(){super("media.edge.EmptyResponse",[])}}new Bw;class jw extends k{constructor(){super("media.edge.RoomParticipants",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"producer_states",kind:"message",repeat:1,T:()=>ks},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"user_id",kind:"scalar",opt:!0,T:9}])}}const Om=new jw;class Hw extends k{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 Wd=new Hw;class Ww extends k{constructor(){super("media.edge.SelectedPeersDiffEntry",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"priority",kind:"scalar",T:5}])}}const $w=new Ww;class Gw extends k{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>$w}])}}const Nm=new Gw;class Jw extends k{constructor(){super("media.edge.PeerJoinResponse",[])}}new Jw;class qw extends k{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>Fw},{no:2,name:"participants",kind:"message",repeat:1,T:()=>Om},{no:3,name:"selected_peers",kind:"message",T:()=>Wd},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const aa=new qw;class Kw extends k{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const Lm=new Kw;class zw extends k{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Em}])}}new zw;class Yw extends k{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Em},{no:3,name:"description",kind:"message",T:()=>Kt}])}}const xm=new Yw;class Qw extends k{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:()=>Kt}])}}const Fm=new Qw;class Xw extends k{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>cw}])}}new Xw;class Zw extends k{constructor(){super("media.edge.ActiveSpeakerResponse",[{no:1,name:"responsepeer_id",kind:"scalar",T:9},{no:2,name:"volume",kind:"scalar",T:5}])}}new Zw;class e0 extends k{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new e0;class t0 extends k{constructor(){super("media.edge.ProducerToggleResponse",[])}}new t0;class r0 extends k{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new r0;class n0 extends k{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>Kt}])}}const Um=new n0;class i0 extends k{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>Kt}])}}new i0;class s0 extends k{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new s0;class o0 extends k{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Vm=new o0;class a0 extends k{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Bm=new a0;class c0 extends k{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const jm=new c0;class d0 extends k{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Hm=new d0;class l0 extends k{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Wm=new l0;class u0 extends k{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>Om}])}}const $m=new u0;class h0 extends k{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>Hd}])}}new h0;class p0 extends k{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>ks}])}}const Gm=new p0;class m0 extends k{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>ks}])}}const Jm=new m0;class f0 extends k{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>ks}])}}const qm=new f0;class g0 extends k{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const ca=new g0;class v0 extends k{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Km=new v0;class y0 extends k{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new y0;class E0 extends k{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new E0;class S0 extends k{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new S0;class T0 extends k{constructor(){super("media.edge.PeerDisplayNameEditBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}new T0;class k0 extends k{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new k0;class _0 extends k{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new _0;class b0 extends k{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 $d=new b0;class w0 extends k{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 w0;class C0 extends k{constructor(){super("socket.api.ErrorMessage",[{no:1,name:"code",kind:"scalar",opt:!0,T:5},{no:2,name:"message",kind:"scalar",T:9}])}}const I0=new C0;var da;(function(t){t[t.BROWSER=0]="BROWSER",t[t.TRACK=1]="TRACK",t[t.COMPOSITE=2]="COMPOSITE"})(da||(da={}));var Tr;(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"})(Tr||(Tr={}));var Gd;(function(t){t[t.NONE=0]="NONE",t[t.RECORDER=1]="RECORDER",t[t.LIVESTREAMER=2]="LIVESTREAMER"})(Gd||(Gd={}));var la;(function(t){t[t.HIVE=0]="HIVE",t[t.CHAT=1]="CHAT",t[t.PING=2]="PING"})(la||(la={}));class R0 extends k{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 P0=new R0;class A0 extends k{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",Tr,"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:()=>P0}])}}const ua=new A0;class M0 extends k{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>ua}])}}const wi=new M0;class D0 extends k{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",Tr,"STAGE_TYPE_"]}])}}const zm=new D0;class O0 extends k{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 N0=new O0;class L0 extends k{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>ua}])}}const Jd=new L0;class x0 extends k{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const Ym=new x0;class F0 extends k{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:()=>V0},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const Qm=new F0;class U0 extends k{constructor(){super("socket.room.ActiveRecording",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",da]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const V0=new U0;class B0 extends k{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>Qm}])}}const Xm=new B0;class j0 extends k{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const Zm=new j0;class H0 extends k{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 H0;class W0 extends k{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>ua},{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",la,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const $0=new W0;class G0 extends k{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>ua},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const J0=new G0;class q0 extends k{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>Qm}])}}new q0;class K0 extends k{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new K0;class z0 extends k{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 qd=new z0;class Y0 extends k{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 Q0=new Y0;class X0 extends k{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:()=>Q0}])}}const ef=new X0;class Z0 extends k{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>ef},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>ef}])}}const eC=new Z0;class tC extends k{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const rC=new tC;class nC extends k{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>rC}])}}const iC=new nC;class sC extends k{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:()=>qd}])}}const oC=new sC;class aC extends k{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>oC}])}}const tf=new aC;class cC extends k{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 dC=new cC;class lC extends k{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>dC}])}}new lC;class uC extends k{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const hC=new uC;class pC extends k{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>hC}])}}const mC=new pC;class fC extends k{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>yC}])}}const gC=new fC;class vC extends k{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:()=>qd}])}}const yC=new vC;class EC extends k{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 SC=new EC;class TC extends k{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:()=>SC}])}}const kC=new TC;class _C extends k{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:()=>qd}])}}const rf=new _C;class bC extends k{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>rf}])}}new bC;class wC extends k{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 CC=new wC;class IC extends k{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>AC}])}}const RC=new IC;class PC extends k{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 AC=new PC;class MC extends k{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const DC=new MC;class OC extends k{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:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const ha=new OC;class NC extends k{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const LC=new NC;class xC extends k{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const FC=new xC;class UC extends k{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}])}}const VC=new UC;class BC extends k{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>VC}])}}const nf=new BC;class jC extends k{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 sf=new jC;var Kd;(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"})(Kd||(Kd={}));var pa;(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"})(pa||(pa={}));class HC extends k{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 WC=new HC;class $C extends k{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 GC=new $C;class JC extends k{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 qC=new JC;class KC extends k{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 zC=new KC;class YC extends k{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>qC},{no:2,name:"private",kind:"message",T:()=>zC}])}}const QC=new YC;class XC extends k{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 ZC=new XC;class eI extends k{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",pa,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",pa,"STREAM_PERMISSION_TYPE_"]}])}}const zd=new eI;class tI extends k{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>zd},{no:2,name:"audio",kind:"message",T:()=>zd},{no:3,name:"screenshare",kind:"message",T:()=>zd}])}}const rI=new tI;class nI extends k{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>WC},{no:2,name:"plugins",kind:"message",T:()=>GC},{no:3,name:"chat",kind:"message",T:()=>QC},{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",Kd,"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",Gd,"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:()=>ZC},{no:23,name:"media",kind:"message",T:()=>rI}])}}const Yd=new nI;class iI extends k{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const sI=new iI;class oI extends k{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 aI=new oI;class cI extends k{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>aI}])}}const dI=new cI;class lI extends k{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>Yd}])}}const of=new lI;class uI extends k{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>of}])}}const hI=new uI;class pI extends k{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>of}])}}const af=new pI;class mI extends k{constructor(){super("socket.preset.PeerUserIDMap",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9}])}}const fI=new mI;class gI extends k{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>fI},{no:2,name:"patch",kind:"message",T:()=>Yd}])}}new gI;class vI extends k{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>Yd}])}}new vI;class yI extends k{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 bn=new yI;class EI extends k{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 SI=new EI;class TI extends k{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>bn},{no:2,name:"next",kind:"scalar",T:8}])}}const kI=new TI;class _I extends k{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>bn}])}}const cf=new _I;class bI extends k{constructor(){super("socket.chat.SendChatMessageToRoomRequest",[{no:1,name:"payload_type",kind:"scalar",T:5},{no:2,name:"payload",kind:"scalar",T:9}])}}const wI=new bI;class CI extends k{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>bn}])}}const Qd=new CI;class II extends k{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 RI=new II;class PI extends k{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>bn}])}}const Xd=new PI;class AI extends k{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 MI=new AI;class DI extends k{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>bn}])}}new DI;class OI extends k{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 NI=new OI;class LI extends k{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 xI=new LI;class FI extends k{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 ma=new FI;class UI extends k{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>bn}])}}const fa=new UI;class VI extends k{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 BI=new VI;class jI extends k{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 ga=new jI;class HI extends k{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 WI=new HI;class $I extends k{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 GI=new $I;class JI extends k{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}const qI=new JI;class KI extends k{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 zI=new KI;class YI extends k{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 QI=new YI;class XI extends k{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new XI;class ZI extends k{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}const eR=new ZI;class tR extends k{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>bn},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const rR=new tR;class nR extends k{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:()=>rR},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const iR=new nR;class sR extends k{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>iR}])}}const kr=new sR;class oR extends k{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 aR=new oR;class cR extends k{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>aR}])}}const dR=new cR;class lR extends k{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const uR=new lR;class hR extends k{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const pR=new hR;class mR extends k{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const fR=new mR;class gR extends k{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const vR=new gR;class yR extends k{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 ER=new yR;class SR extends k{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 TR=new SR;class kR extends k{constructor(){super("socket.plugin.PluginEventToRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const _R=new kR;class bR extends k{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 wR=new bR;class CR extends k{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 Zd=new CR;class IR extends k{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:()=>Zd}])}}const df=new IR;class RR extends k{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:()=>Zd}])}}const PR=new RR;class AR extends k{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:()=>Zd}])}}const MR=new AR;class DR extends k{constructor(){super("socket.plugin.PluginStoreDeleteRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9}])}}const OR=new DR;class NR extends k{constructor(){super("socket.plugin.EnablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"enabled_by",kind:"scalar",T:9}])}}const el=new NR;class LR extends k{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>el}])}}const xR=new LR;class FR extends k{constructor(){super("socket.plugin.DisablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"disabled_by",kind:"scalar",T:9}])}}const lf=new FR;class UR extends k{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 VR=new UR;class BR extends k{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:()=>VR}])}}const uf=new BR;class jR extends k{constructor(){super("socket.plugin.PluginEventResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const hf=new jR;class HR extends k{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}])}}const pf=new HR;class WR extends k{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const mf=new WR;class $R extends k{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 GR=new $R;class JR extends k{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>GR}])}}const tl=new JR;class qR extends k{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const KR=new qR;class zR extends k{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const YR=new zR;class QR extends k{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const ff=new QR;class XR extends k{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:()=>eP},{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 gf=new XR;class ZR extends k{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:()=>rP}])}}const eP=new ZR;class tP extends k{constructor(){super("socket.polls.PollVote",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])}}const rP=new tP;class nP extends k{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 iP=new nP;class sP extends k{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 oP=new sP;class aP extends k{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>gf}])}}const rl=new aP;class cP extends k{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>gf}])}}const dP=new cP;class lP extends k{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",da]}])}}const vf=new lP;class uP extends k{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(),r=Date.now();return e.seconds=_e.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}toDate(e){return new Date(_e.from(e.seconds).toNumber()*1e3+Math.ceil(e.nanos/1e6))}fromDate(e){const r=this.create(),n=e.getTime();return r.seconds=_e.from(Math.floor(n/1e3)).toBigInt(),r.nanos=n%1e3*1e6,r}internalJsonWrite(e,r){let n=_e.from(e.seconds).toNumber()*1e3;if(n<Date.parse("0001-01-01T00:00:00Z")||n>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 i="Z";if(e.nanos>0){let s=(e.nanos+1e9).toString().substring(1);s.substring(3)==="000000"?i="."+s.substring(0,3)+"Z":s.substring(6)==="000"?i="."+s.substring(0,6)+"Z":i="."+s+"Z"}return new Date(n).toISOString().replace(".000Z",i)}internalJsonRead(e,r,n){if(typeof e!="string")throw new Error("Unable to parse Timestamp from JSON "+Bc(e)+".");let i=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(!i)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let s=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(s))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(s<Date.parse("0001-01-01T00:00:00Z")||s>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 n||(n=this.create()),n.seconds=_e.from(s/1e3).toBigInt(),n.nanos=0,i[7]&&(n.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),n}}new uP;class Ci extends _t.EventEmitter{constructor(){super(),super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}on(e,r){try{const n=this.listenerCount(e);n>25&&n%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch(n){}return super.on(e,r)}addListener(e,r){try{const n=this.listenerCount(e);n>25&&n%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch(n){}return super.addListener(e,r)}off(e,r){return super.off(e,r)}once(e,r){return super.once(e,r)}prependListener(e,r){return super.prependListener(e,r)}prependOnceListener(e,r){return super.prependOnceListener(e,r)}removeListener(e,r){return super.removeListener(e,r)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}class Dt extends _t.EventEmitter{constructor(){super(),super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}on(e,r){try{const n=this.listenerCount(e);n>25&&n%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch(n){}return super.on(e,r)}addListener(e,r){try{const n=this.listenerCount(e);n>25&&n%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch(n){}return super.addListener(e,r)}off(e,r){return super.off(e,r)}once(e,r){return super.once(e,r)}prependListener(e,r){return super.prependListener(e,r)}prependOnceListener(e,r){return super.prependOnceListener(e,r)}removeListener(e,r){return super.removeListener(e,r)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}const hP=0,pP=1,mP=2,fP=3,gP=4,vP=5,yP={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,broadcastToPeers:39,recordingStarted:40,recordingStopped:41,recordingPaused:42,getRoomStageState:43},EP={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,sendMessageToChannel:6,searchChannelMessages:7,getAllChatChannels:8,markChannelIndexAsRead:9,pinMessage:10},SP={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},TP={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},yf={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},kP={createChatChannel:0,getChatChannel:1,deprecatedGetAllChatChannels:2,getChannelMembers:3,updateChatChannel:4},_P={getUserPresets:0,updateUserPreset:1};function Ii(t,e){return Object.keys(e).reduce((r,n)=>(r[n]=(t<<16)+e[n],r),{})}function Ef(t,e){return Object.keys(t).reduce((r,n)=>(r[n]=e|t[n],r),{})}const j=Ii(hP,yP),De=Ii(pP,EP),J=Ii(mP,SP),_r=Ii(fP,TP),wn=Ii(gP,kP),ie=Ef(yf,16777216),se=Ef(yf,50331648),va=Ii(vP,_P);var bP=Object.defineProperty,wP=Object.getOwnPropertyDescriptor,nl=(t,e,r,n)=>{for(var i=n>1?void 0:n?wP(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&bP(e,r,i),i},Cn,Sf;const il=(Sf=class{constructor(t){_(this,Cn,void 0),T(this,Cn,t)}createChannel(t,e,r,n="public",i=!1){return u(this,null,function*(){const s={displayName:t,targetUserIds:e,displayPictureUrl:r,visibility:n,isDirectMessage:i};i&&(s.visibility="private");const o=yield c(this,Cn).sendMessagePromise(wn.createChatChannel,zI.toBinary(s)),a=kr.fromBinary(o.payload).chatChannels;return il.formatChannel(a[0])})}updateChannel(t,e){return u(this,null,function*(){const r=yield c(this,Cn).sendMessagePromise(wn.updateChatChannel,QI.toBinary({chatChannelId:t,targetUserIds:e.memberIds,displayName:e.displayName,displayPictureUrl:e.displayPictureUrl,visibility:e.visibility})),n=kr.fromBinary(r.payload).chatChannels;return il.formatChannel(n[0])})}static formatChannel(t){var e;const{latestMessageAndUnreadCount:r}=t,n=ne(V({},t),{id:t.chatChannelId,memberIds:t.targetUserIds,unreadCount:(e=r==null?void 0:r.unreadCount)!=null?e:0});return r!=null&&r.message&&(n.latestMessage=wr.formatSocketServiceMessage(r.message)),delete n.chatChannelId,delete n.targetUserIds,delete n.latestMessageAndUnreadCount,n}getChannelMembers(t){return u(this,null,function*(){try{const e=yield c(this,Cn).sendMessagePromise(wn.getChannelMembers,eR.toBinary({chatChannelId:t}));return dR.fromBinary(e.payload).channelMembers.map(r=>{var n=r,{id:i}=n,s=Ro(n,["id"]);return ne(V({},s),{userId:i})})}catch(e){return[]}})}on(t,e){let r,n;switch(t){case wn.createChatChannel:{r=kr.fromBinary.bind(kr),n=kr.create();break}case wn.updateChatChannel:{r=kr.fromBinary.bind(kr),n=kr.create();break}}if(!r){l.warn(`ChatChannelSocketHandler::Event ${t} is not recognized`);return}c(this,Cn).on(t,({payload:i})=>{let s=n;try{s=r(i)}catch(o){l.error("ChatChannelSocketHandler::on::binary_decode_error",{error:o})}return e(s)})}},Cn=new WeakMap,Sf);let In=il;nl([y.trace("ChatChannelHandler.createChannel")],In.prototype,"createChannel",1),nl([y.trace("ChatChannelHandler.updateChannel")],In.prototype,"updateChannel",1),nl([y.trace("ChatChannelHandler.getChannelMembers")],In.prototype,"getChannelMembers",1);var CP=Object.defineProperty,IP=Object.getOwnPropertyDescriptor,zt=(t,e,r,n)=>{for(var i=n>1?void 0:n?IP(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&CP(e,r,i),i},mt=(t=>(t[t.TEXT=0]="TEXT",t[t.IMAGE=1]="IMAGE",t[t.FILE=2]="FILE",t[t.CUSTOM=3]="CUSTOM",t))(mt||{}),ft;class Bt{constructor(e){_(this,ft,void 0),T(this,ft,e)}getChatMessages(){return c(this,ft).sendMessagePromise(De.getMessages)}getChatMessagesPaginated(e,r,n,i=0,s=""){return u(this,null,function*(){const o={timeStamp:e,size:r,from:i,reversed:n,channelId:s},a=yield c(this,ft).sendMessagePromise(De.getPaginatedMessages,SI.toBinary(o));return a.payload?kI.fromBinary(a.payload):{messages:[],next:!1}})}sendMessageToRoom(e,r){const n={payloadType:r,payload:e};c(this,ft).sendMessage(De.sendMessageToRoom,wI.toBinary(n))}sendMessageToPeers(e,r,n){const i={payloadType:r,peerIds:n,payload:e};c(this,ft).sendMessage(De.sendMessageToPeers,RI.toBinary(i))}sendMessageToChannel(e,r,n){const i={payloadType:r,channelId:n,payload:e};c(this,ft).sendMessage(De.sendMessageToChannel,MI.toBinary(i))}sendMessage(e,r,n,i){if(i&&this.sendMessageToChannel(e,r,i),n&&n.length>0){this.sendMessageToPeers(e,r,n);return}this.sendMessageToRoom(e,r)}editMessage(e,r,n,i,s){return u(this,null,function*(){const o={chatId:e,payloadType:n,payload:r};i&&(o.channelId=i),s!==void 0&&(o.pinned=s);const a=yield c(this,ft).sendMessagePromise(De.editMessage,NI.toBinary(o));return fa.fromBinary(a.payload).message})}deleteMessage(e,r){return u(this,null,function*(){const n={chatId:e};r&&(n.channelId=r);const i=yield c(this,ft).sendMessagePromise(De.deleteMessage,BI.toBinary(n)),s=ga.fromBinary(i.payload);return V({id:s.chatId},s.channelId?{channelId:s.channelId}:{})})}searchMessages(e,r){return u(this,null,function*(){var n,i,s;const o={searchTerm:e,timeStamp:(n=r.timestamp)!=null?n:Date.now(),size:(i=r.size)!=null?i:75,from:0,reversed:(s=r.reversed)!=null?s:!0};r.channelId&&(o.channelId=r.channelId);try{const a=yield c(this,ft).sendMessagePromise(De.searchChannelMessages,WI.toBinary(o));return cf.fromBinary(a.payload).messages}catch(a){return[]}})}getAllChannels(){return u(this,null,function*(){try{const e=yield c(this,ft).sendMessagePromise(De.getAllChatChannels);return kr.fromBinary(e.payload).chatChannels.map(In.formatChannel)}catch(e){return[]}})}markLastReadMessage(e,r){return u(this,null,function*(){const n=yield c(this,ft).sendMessagePromise(De.markChannelIndexAsRead,GI.toBinary({channelId:e,userId:r.userId,channelIndex:r.channelIndex}));return qI.fromBinary(n.payload).channelIndex})}setPinState(e,r){return u(this,null,function*(){const n={chatId:e.id,pinned:r,channelId:e.channelId},i=yield c(this,ft).sendMessagePromise(De.pinMessage,xI.toBinary(n));return ma.fromBinary(i.payload)})}on(e,r){let n,i;switch(e){case De.sendMessageToRoom:{n=Qd.fromBinary.bind(Qd),i=Qd.create();break}case De.sendMessageToPeers:{n=Xd.fromBinary.bind(Xd),i=Xd.create();break}case De.editMessage:{n=fa.fromBinary.bind(fa),i=fa.create();break}case De.pinMessage:{n=ma.fromBinary.bind(ma),i=ma.create();break}case De.deleteMessage:{n=ga.fromBinary.bind(ga),i=ga.create();break}}if(!n){l.warn(`ChatSocketHandler::Event ${e} is not recognized`);return}c(this,ft).on(e,({payload:s})=>{let o=i;try{o=n(s)}catch(a){l.error("chatSocketHandler::on::binary_decode_error",{error:a})}return r(o)})}}ft=new WeakMap,zt([y.trace("SocketService.getChatMessages")],Bt.prototype,"getChatMessages",1),zt([y.trace("SocketService.getChatMessagesPaginated")],Bt.prototype,"getChatMessagesPaginated",1),zt([y.trace("SocketService.sendMessageToRoom")],Bt.prototype,"sendMessageToRoom",1),zt([y.trace("SocketService.sendMessageToPeers")],Bt.prototype,"sendMessageToPeers",1),zt([y.trace("SocketService.sendMessageToChannel")],Bt.prototype,"sendMessageToChannel",1),zt([y.trace("SocketService.sendMessage")],Bt.prototype,"sendMessage",1),zt([y.trace("SocketService.editMessage")],Bt.prototype,"editMessage",1),zt([y.trace("SocketService.deleteMessage")],Bt.prototype,"deleteMessage",1),zt([y.trace("SocketService.searchMessages")],Bt.prototype,"searchMessages",1),zt([y.trace("SocketService.getAllChannels")],Bt.prototype,"getAllChannels",1),zt([y.trace("SocketService.markLastReadMessage")],Bt.prototype,"markLastReadMessage",1);function RP(t){return t.replace(/([-_]\w)/g,e=>e[1].toUpperCase())}function dr(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>dr(r));const e={};return Object.keys(t).forEach(r=>{const n=Uc(r)?r:RP(r);e[n]=dr(t[r])}),e}function PP(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function Tf(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>Tf(r));const e={};return Object.keys(t).forEach(r=>{const n=Uc(r)?r:PP(r);e[n]=t[r]}),e}function ya(t,e={}){return t==null?{}:(Object.getOwnPropertyNames(t).forEach(r=>{if(typeof t[r]!="function"){if(typeof t[r]=="object"){ya(t[r],e[r]={});return}e[r]=t[r]}}),e)}const AP=3,MP=30,DP=8e3;class OP{constructor(e,r){m(this,"ipInfo"),m(this,"axios"),m(this,"requests"),m(this,"roomName"),m(this,"roomUUID"),m(this,"authToken"),m(this,"organizationId"),m(this,"iceServers"),m(this,"pluginInformation"),m(this,"userDetails"),m(this,"roomDetails"),m(this,"context"),this.context=e;const{timeout:n=DP,retry:i=AP,retryDelay:s=MP,baseURL:o="https://api.cluster.dyte.in",authToken:a,cachedUserDetails:d}=r||{};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=Jo.create({baseURL:o,responseType:"json",timeout:n,retry:i,retryDelay:s}),this.axios=Jo,this.setAuthToken(a,{bearer:!0}),this.requests.interceptors.request.use(h=>(y.injectContext(this.requests.defaults.headers.common),h),h=>u(this,null,function*(){l.error("xhr::axios",{debuggingHint:"otelRequestInterceptor failed.",error:h})})),this.requests.interceptors.response.use(h=>{try{h.config.url!==y.logsEndpoint&&l.debug("xhr::axios",{networkCall:{status:h.status,statusText:h.statusText,baseURL:h.config.baseURL,url:h.config.url,method:h.config.method}})}catch(p){console.error("xhr::dyte",{error:"responseInterceptorFailed",err:p,response:h})}return h},h=>u(this,null,function*(){var p;try{if(!h)return Promise.reject(new C("Unknown network error occurred","0011"));h&&h.config&&((p=h.config)==null?void 0:p.url)!==y.logsEndpoint&&l.error("xhr::axios",{error:h,networkCall:{status:h.status,statusText:h.statusText,baseURL:h.config.baseURL,url:h.config.url,retries:h.config.retry,method:h.config.method,isOnline:navigator.onLine?"online":"offline"}});const{config:f,message:g}=h;return f&&g&&f.retry!==void 0&&f.retry>0&&(g.includes("timeout")||g.includes("Network Error"))?(f.retry-=1,this.requests(f)):Promise.reject(new C(g,"0011"))}catch(f){return console.error("xhr::dyte",{error:"responseInterceptorFailed",err:f,responseError:h}),Promise.reject(new C(f.message,"0011"))}}))}get peerId(){return this.context.getValue("peerId")}setAuthToken(e,r){const{bearer:n}=r||{};this.authToken=e,this.requests.defaults.headers.common.Authorization=n?`Bearer ${e}`:e}setHeader(e,r){this.requests.defaults.headers.common[e]=r}setRoomName(e){this.roomName=e}setRoomUUID(e){this.roomUUID=e}setOrganizationId(e){this.organizationId=e}}var NP=Object.defineProperty,LP=Object.getOwnPropertyDescriptor,sl=(t,e,r,n)=>{for(var i=n>1?void 0:n?LP(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&NP(e,r,i),i};class Ea extends OP{constructor(e,r){super(e,r),this.setHeader("x-dyte-web-core-version",e.getValue("sdkVersion"))}getIPDetails(){return u(this,null,function*(){var e;const{peerId:r}=this;try{const n=yield Zc.getIPDetails({peerId:r,apiHostnames:mm(this.context)});if(l.log("ipInfo",{ipInfo:n}),((e=n.loc)==null?void 0:e.length)>5)return n;throw Error("Insufficient data")}catch(n){l.warn("ApiClient.getRoomNodeLinkAndTitleV1 Failed to get ip details",{error:{name:n.name,message:n.message}});return}})}getICEServers(){return u(this,null,function*(){if(this.iceServers)return this.iceServers;const{success:e,iceServers:r}=(yield this.requests.get("/iceservers")).data;if(e)return(r==null?void 0:r.length)>0&&(this.iceServers=r),r})}getPlugins(){return u(this,null,function*(){var e,r,n,i,s,o,a;if(this.pluginInformation)return this.pluginInformation;let{plugins:d}=(yield this.requests.get("/v2/plugins/user")).data.data;const h=((r=(e=K.getValue(X.V1_PLUGINS))==null?void 0:e.toString())==null?void 0:r.split(","))||[];return d=d.reduce((p,f)=>(p[h.includes(f.id)?"v1":"v2"].push(f),p),{v1:[],v2:[]}).v2,(s=(i=(n=this.context.getValue("modules"))==null?void 0:n.devTools)==null?void 0:i.plugins)!=null&&s.length&&((a=(o=this.context.getValue("modules"))==null?void 0:o.devTools)==null||a.plugins.forEach(p=>{var f,g,E;const v=ne(V({},Ss),{tags:[...Ss.tags]});v.baseURL=`http://localhost:${p.port}`,v.name=p.name,v.picture=(f=p.picture)!=null?f:Ss.picture,v.description=(g=p.description)!=null?g:Ss.description,v.staggered=(E=p.staggered)!=null?E:Ss.staggered,v.createdAt=new Date().toISOString(),v.updatedAt=new Date().toISOString(),v.id=p.id,v.organizationId=this.organizationId,d.push(v)})),d})}getPluginDetails(e){return u(this,null,function*(){const{plugin:r}=(yield this.requests.get(`/v2/plugins/view/${e}`)).data.data;return r})}getPluginConfig(e){return u(this,null,function*(){return(yield this.axios.get(`${e}/dyte-config.json`)).data})}authorizePlugin(e){return u(this,null,function*(){const r={peerId:this.peerId},{token:n}=(yield this.requests.post(`/v2/plugins/authorize/${e}`,r)).data.data;return n})}getPresignedUrls(e,r){return u(this,null,function*(){const n={roomUUID:this.roomUUID,filename:e};K.hasFeature(X.FEAT_CHAT_SDK)&&(n.viewType=r);const{getLocation:i,putLocation:s}=(yield this.requests.post("/v1/meetings/genPreSignedUploadUrl",n)).data.data;return{getLocation:i,putLocation:s}})}uploadFile(e,r){return u(this,null,function*(){if(navigator.isReactNative&&"uri"in e)try{yield fetch(r,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:{uri:e.uri,name:e.name}})}catch(n){l.error(`sendFileMessage::${n}`)}else yield this.axios.put(r,e,{headers:{"Content-Type":e.type}})})}}sl([y.trace("APIClient.getIPDetails")],Ea.prototype,"getIPDetails",1),sl([y.trace("APIClient.getICEServers")],Ea.prototype,"getICEServers",1),sl([y.trace("APIClient.getPlugins")],Ea.prototype,"getPlugins",1);var xP=Object.defineProperty,FP=Object.getOwnPropertyDescriptor,br=(t,e,r,n)=>{for(var i=n>1?void 0:n?FP(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&xP(e,r,i),i};class lr extends Ea{startLivestreaming(){return u(this,null,function*(){var e,r;return(r=(e=(yield this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/livestreams`)).data)==null?void 0:e.data)==null?void 0:r.playback_url})}stopLivestreaming(){return u(this,null,function*(){return this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream/stop`)})}getActiveLivestream(){return u(this,null,function*(){const{playbackUrl:e,status:r}=dr((yield this.requests.get(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream`)).data.data);return{status:r,playbackUrl:e}})}getUserDetails(){return u(this,null,function*(){if(this.userDetails)return this.userDetails;const e=(yield this.requests.get("v2/internals/participant-details")).data.data;return dr(e)})}startRecording(e,r){return u(this,null,function*(){return(yield this.requests.post("/v2/recordings",ne(V({},Tf(e)),{meeting_id:this.context.getValue("meetingId"),allow_multiple_recordings:!!r}))).data.data.id})}updateRecording(e,r){return u(this,null,function*(){return this.requests.put(`v2/recordings/${e}`,{action:r})})}getActiveRecording(){return u(this,null,function*(){const{status:e,id:r}=(yield this.requests.get(`v2/recordings/active-recording/${this.context.getValue("meetingId")}`)).data.data;return{status:e,id:r}})}getActiveTranscript(){return u(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.axios.get(e)).data}}catch(r){throw new C("Cant fetch transcript s3 url")}})}getRoomNodeData(){return u(this,null,function*(){if(this.roomDetails)return this.roomDetails;const e=yield this.getIPDetails();this.ipInfo=e;const{roomNodeLink:r,title:n,useHiveMedia:i,sfu:s}=dr((yield this.requests.post("v2/internals/rooms",{ip_information:e})).data.data);return{roomNodeUrl:r,meetingTitle:n,useHiveMedia:i!=null?i:!1,sfu:s}})}}br([y.trace("APIClient.startLivestreaming")],lr.prototype,"startLivestreaming",1),br([y.trace("APIClient.stopLivestreaming")],lr.prototype,"stopLivestreaming",1),br([y.trace("APIClient.getActiveLivestream")],lr.prototype,"getActiveLivestream",1),br([y.trace("APIClient.getUserDetails")],lr.prototype,"getUserDetails",1),br([y.trace("APIClient.startRecording")],lr.prototype,"startRecording",1),br([y.trace("APIClient.stopRecording")],lr.prototype,"updateRecording",1),br([y.trace("APIClient.getActiveRecording")],lr.prototype,"getActiveRecording",1),br([y.trace("APIClient.getActiveTranscript")],lr.prototype,"getActiveTranscript",1),br([y.trace("APIClient.getRoomNodeData")],lr.prototype,"getRoomNodeData",1);let ol;function UP(t,e){return ol=new lr(t,e),ol}function je(){return ol}function VP(t,e){return`<blockquote>${e.replace(/<blockquote>[.\s\S]*<\/blockquote>\n\n/m,"")}</blockquote>
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 u(this,null,function*(){const[e,r]=yield Promise.all([this.pc1.getStats(),this.pc2.getStats()]);let n,i;if(e.forEach(s=>{s.type==="candidate-pair"&&s.nominated===!0&&s.bytesSent>0&&(n=s)}),r.forEach(s=>{s.type==="candidate-pair"&&s.nominated===!0&&s.bytesReceived>0&&(i=s)}),n&&i)try{if(n.currentRoundTripTime&&i.currentRoundTripTime)return{rtt:n.currentRoundTripTime,backendRTT:i.currentRoundTripTime};const s=(i.lastPacketReceivedTimestamp-n.lastPacketSentTimestamp)/1e3;return{rtt:s,backendRTT:s}}catch(s){return}})}close(){this.pc1.close(),this.pc2.close()}}class qh extends ht{constructor(e){super(),f(this,"call"),f(this,"timeOut"),this.call=new Rr(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 TS=8,kS=1/1e3;class _S extends qh{constructor(e){super(e),f(this,"senderChannel"),f(this,"recieveChannel"),f(this,"startTime"),f(this,"lastBitrateMeasureTime"),f(this,"sentPayloadBytes",0),f(this,"recievedPayloadBytes",0),f(this,"lastReceivedPayloadBytes",0),f(this,"stopSending",!1),f(this,"testProgress",0),f(this,"samplePacket",""),f(this,"finalBitrateSum",0),f(this,"bitRateSampels",0),f(this,"maxNumberOfPacketsToSend",0),f(this,"bytesToKeepBuffered",0),f(this,"testDurationSeconds",5),this.call.setIceCandidateFilter(Rr.isNotHostCandidate),this.senderChannel=this.call.pc1.createDataChannel(null);for(let r=0;r<262144;r+=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 n=0;n!==this.maxNumberOfPacketsToSend&&!(this.senderChannel.bufferedAmount>=this.bytesToKeepBuffered);n+=1){this.sentPayloadBytes+=this.samplePacket.length;try{this.senderChannel.send(this.samplePacket)}catch(i){}}const r=e.getTime()-this.startTime.getTime();r>=1e3*this.testDurationSeconds?(this.stopSending=!0,this.testProgress=100):(this.testProgress=r/(10*this.testDurationSeconds),setTimeout(this.sendingStep.bind(this),1))}onMessageRecieved(e){this.recievedPayloadBytes+=e.data.length;const r=new Date,n=r.getTime()-this.lastBitrateMeasureTime.getTime();if(n>=1e3){const i=(this.recievedPayloadBytes-this.lastReceivedPayloadBytes)*TS/(n/1e3);this.finalBitrateSum+=i,this.bitRateSampels+=1,this.lastReceivedPayloadBytes=this.recievedPayloadBytes,this.lastBitrateMeasureTime=r}if(this.stopSending&&this.sentPayloadBytes===this.recievedPayloadBytes){const i=this.finalBitrateSum/this.bitRateSampels;this.testComplete({throughput:Math.round(i*kS)})}}testComplete(e){this.call.getRoundTripTime().then(({rtt:r,backendRTT:n})=>super.testComplete({RTT:r,backendRTT:n,throughput:e.throughput}))}onRecieverChannel(e){this.recieveChannel=e.channel,this.recieveChannel.addEventListener("message",this.onMessageRecieved.bind(this))}}class Nd extends qh{constructor(e,r=Rr.noFilter){super(e),f(this,"ch1"),f(this,"ch2"),this.call.setIceCandidateFilter(r);const n=this.call.pc1.createDataChannel(null);this.ch1=n,n.addEventListener("open",()=>{n.send("hello")}),n.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(r){}}dataChannelHandler(e){const r=e.channel;this.ch2=r,r.addEventListener("message",this.onCh2Recieve.bind(this))}hangup(e){this.testFailed(e)}}class bS extends Nd{constructor(e){super(e,Rr.isHost)}}class wS extends Nd{constructor(e){super(e,Rr.isRelay)}}class IS extends Nd{constructor(e){super(e,Rr.isReflexive)}}class CS{constructor(){f(this,"ipInformation",null)}getIPDetails(e){return u(this,arguments,function*({peerId:r,apiHostnames:n,logger:i}){var s,a,o;if(!this.ipInformation){try{const d=`https://${n.location}`,h=yield(yield fetch(d)).json();if(((s=h.loc)==null?void 0:s.length)>5)return this.ipInformation=h,(a=this.ipInformation)!=null&&a.ip&&(this.ipInformation.ip=nn(this.ipInformation.ip)),h;throw Error("Insufficient data")}catch(d){i.error("callstats::ipDetails:: failed to fetch ip using location service",{error:d})}try{const d=yield fetch(`https://${n.locationLegacy}/?token=3c493932b0624c&peerId=${r}`,{method:"POST"});this.ipInformation=yield d.json(),(o=this.ipInformation)!=null&&o.ip&&(this.ipInformation.ip=nn(this.ipInformation.ip))}catch(d){i.error("callstats::ipDetails:: failed to fetch ip using legacy location service",{error:d})}}return this.ipInformation})}resetCache(){this.ipInformation=null}}const Ld=new CS,zh=[{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 Kh(t){const[e,r]=t.split(",");return{coords:{latitude:Number(e),longitude:Number(r)}}}class Yh{constructor(){f(this,"transport"),f(this,"candidatePair"),f(this,"outboundVideoRtp",new Map),f(this,"inboundVideoRtp",new Map),f(this,"outboundAudioRtp",new Map),f(this,"inboundAudioRtp",new Map),f(this,"remoteInboundRtp",new Map),f(this,"producerStreamMap",new Map),f(this,"consumerStreamMap",new Map),f(this,"staleProducerStreamMap",!1),f(this,"staleConsumerStreamMap",!1)}}class Qh extends ht{constructor(){super(),f(this,"observer"),f(this,"outboundProducerMap",new Map),f(this,"inboundConsumerMap",new Map),f(this,"consumerPeerIdMap",new Map),f(this,"pausedConsumerMap",new Map),f(this,"pausedProducerMap",new Map),f(this,"overallProducingTransportsStatsMap",{}),f(this,"overallConsumingTransportsStatsMap",{}),f(this,"overallConsumersStatsMap",{}),f(this,"overallProducersStatsMap",{}),f(this,"videoProducerToStatsMap",new Map),f(this,"audioProducerToStatsMap",new Map),f(this,"videoConsumerToStatsMap",new Map),f(this,"audioConsumerToStatsMap",new Map),f(this,"consumerIdsWithFreezedVideo",new Set),f(this,"consumerIdsWithFreezedAudio",new Set),f(this,"producerIdsWithFreezedVideo",new Set),f(this,"producerIdsWithFreezedAudio",new Set),f(this,"freezedProducingTransportIds",new Set),f(this,"freezedConsumingTransportIds",new Set),f(this,"screenShareProducers",new Set),f(this,"screenShareConsumers",new Set),f(this,"ipDetails"),f(this,"callStatsInstance"),this.observer=new ht}registerProducer(e){return u(this,null,function*(){yield this.generateProducerStreamMap(e),e.observer.on("close",this.deregisterProducer.bind(this,e)),e.observer.on("pause",this.pauseProducer.bind(this,e.id)),e.observer.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,r,n){var i,s;const a=((s=(i=this==null?void 0:this.callStatsInstance)==null?void 0:i.consumerSharedMediaStatesMap)==null?void 0:s.get(e))||{};r.totalVideoPacketsReceived===n.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))):(r.totalVideoPacketsReceived=n.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,r,n){var i,s;const a=((s=(i=this==null?void 0:this.callStatsInstance)==null?void 0:i.consumerSharedMediaStatesMap)==null?void 0:s.get(e))||{};r.totalAudioPacketsReceived===n.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))):(r.totalAudioPacketsReceived=n.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,r,n){var i;const s=((i=this==null?void 0:this.callStatsInstance)==null?void 0:i.currentUserMediaStates)||{};r.totalVideoPacketsSent===n.packetsSent?(this.producerIdsWithFreezedVideo.add(e),this.callStatsInstance&&s.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","pause",e))):(r.totalVideoPacketsSent=n.packetsSent,this.producerIdsWithFreezedVideo.has(e)&&(this.producerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&s.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","resume",e))))}processOutboundProducerAudioStats(e,r,n){var i;const s=((i=this==null?void 0:this.callStatsInstance)==null?void 0:i.currentUserMediaStates)||{};r.totalAudioPacketsSent===n.packetsSent?(this.producerIdsWithFreezedAudio.add(e),this.callStatsInstance&&s.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","pause",e))):(r.totalAudioPacketsSent=n.packetsSent,this.producerIdsWithFreezedAudio.has(e)&&(this.producerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&s.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","resume",e))))}processProducingTransportStats(e,r,n){var i;const s=((i=this==null?void 0:this.callStatsInstance)==null?void 0:i.currentUserMediaStates)||{},{audio:a,video:o,screen:d}=s,h=a||o||d;r.totalPacketsSent===n.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))):(r.totalPacketsSent=n.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,r,n){var i,s;const a=!!Array.from(((s=(i=this==null?void 0:this.callStatsInstance)==null?void 0:i.consumerSharedMediaStatesMap)==null?void 0:s.values())||[]).reduce((o,d)=>o||d.audio||d.video||d.screen,!1);r.totalPacketsReceived===n.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))):(r.totalPacketsReceived=n.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 u(this,null,function*(){yield this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.observer.on("close",this.deregisterConsumer.bind(this,e)),e.observer.on("pause",this.pauseConsumer.bind(this,e.id)),e.observer.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,r=!1){return u(this,null,function*(){const n=yield e.getStats(),i=r?this.getProducerStatsFromReport(this.parseRTCReport(n,["outbound-rtp","remote-inbound-rtp"],!1,e.id))[0]:void 0;for(const s of n.values())switch(s.type){case"outbound-rtp":{this.outboundProducerMap.set(s.id,e.id);break}}return i})}generateConsumerStreamMap(e,r=!1){return u(this,null,function*(){const n=yield e.getStats(),i=r?this.getConsumerStatsFromReport(this.parseRTCReport(n,["inbound-rtp"],!1,e.id))[0]:void 0;for(const s of n.values())switch(s.type){case"inbound-rtp":{this.inboundConsumerMap.set(s.id,e.id);break}}return i})}deregisterProducer(e){this.outboundProducerMap.forEach((r,n)=>{r===e.id&&this.outboundProducerMap.delete(n)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.inboundConsumerMap.forEach((r,n)=>{r===e.id&&this.inboundConsumerMap.delete(n)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var r;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(r=e.relayProtocol)!=null?r:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}getWorkingSimulcastVideoStats(e){return e.find(r=>{const n=r.framesEncoded>0,i=r.packetsSent>0,s=r.frameWidth&&r.frameHeight;return n&&i&&!!s})||e[e.length-1]}parseRTCReport(e,r=[],n=!1,i=void 0,s=void 0){var a,o,d,h,p,m,g,v,I,A,P,D,N;const J=e,C=new Yh,G=r.length?new Set(r):void 0,W=[],de=[],ae=[],Le=new Map,Dt=new Map;for(const O of J.values()){if(G){if(G.size===0)break;if(G.has(O.type))n&&G.delete(O.type);else continue}switch(O.type){case"local-candidate":{W.push(this.getIceCandidateStats(O));break}case"remote-candidate":{de.push(this.getIceCandidateStats(O));break}case"candidate-pair":{const{nominated:k}=O,{selected:R}=O,H=O,De={nominated:k!=null?k:R,currentRoundTripTime:H.currentRoundTripTime,totalRoundTripTime:H.totalRoundTripTime,bytesReceived:H.bytesReceived,bytesSent:H.bytesSent,availableOutgoingBitrate:H.availableOutgoingBitrate,availableIncomingBitrate:H.availableIncomingBitrate,lastPacketReceivedTimestamp:H.lastPacketReceivedTimestamp,lastPacketSentTimestamp:H.lastPacketSentTimestamp,localCandidateId:H.localCandidateId,remoteCandidateId:H.remoteCandidateId,bytesDiscardedOnSend:H.bytesDiscardedOnSend,packetsSent:H.packetsSent,packetsReceived:H.packetsReceived,packetsDiscardedOnSend:H.packetsDiscardedOnSend};ae.push(De),(O.nominated===!0||O.selected===!0)&&(C.candidatePair=De);break}case"transport":{const k=O;s&&(s.producing&&(this.overallProducingTransportsStatsMap[s.id]||(this.overallProducingTransportsStatsMap[s.id]={totalPacketsSent:0})),s.consuming&&(this.overallConsumingTransportsStatsMap[s.id]||(this.overallConsumingTransportsStatsMap[s.id]={totalPacketsReceived:0})));const R={bytesReceived:k.bytesReceived,bytesSent:k.bytesSent,packetsSent:k.packetsSent,packetsReceived:k.packetsReceived,dtlsCipher:k.dtlsCipher,dtlsState:k.dtlsState,iceRole:k.iceRole};if(C.transport=R,s){if(s.producing){const H=this.overallProducingTransportsStatsMap[s.id];this.processProducingTransportStats(s.id,H,R)}if(s.consuming){const H=this.overallConsumingTransportsStatsMap[s.id];this.processConsumingTransportStats(s.id,H,R)}}break}case"remote-inbound-rtp":{const k=O,R={jitter:k.jitter,fractionLost:k.fractionLost,roundTripTime:k.roundTripTime,roundTripTimeMeasurements:k.roundTripTimeMeasurements,totalRoundTripTime:k.totalRoundTripTime,packetsLost:k.packetsLost};C.remoteInboundRtp.set(k.localId,R);break}case"outbound-rtp":{const k=O,R=i||this.outboundProducerMap.get(O.id),H=this.pausedProducerMap.get(R);if(H){if(H.lastReportCalculated===!0)break;this.pausedProducerMap.set(R,{lastReportCalculated:!0})}this.overallProducersStatsMap[R]||(this.overallProducersStatsMap[R]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const De=this.overallProducersStatsMap[R];if(["video","audio"].includes(k.mediaType)||["video","audio"].includes(k.kind)){if(!this.outboundProducerMap.has(O.id)){C.staleProducerStreamMap=!0;break}const rt=this.callStatsInstance.producers.get(R);if(((a=rt==null?void 0:rt.track)==null?void 0:a.readyState)==="ended")break;C.producerStreamMap.has(R)||C.producerStreamMap.set(R,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const B={bytesSent:k.bytesSent,packetsSent:k.packetsSent,nackCount:k.nackCount,ssrc:k.ssrc,mid:k.mid,active:k.active,codecId:k.codecId,headerBytesSent:k.headerBytesSent||0,totalPacketSendDelay:k.totalPacketSendDelay||0};if(k.mediaType==="video"||k.kind==="video"){const M=k,nt=U({frameHeight:M.frameHeight,frameWidth:M.frameWidth,framesEncoded:M.framesEncoded,framesDropped:M.framesDropped,framesPerSecond:M.framesPerSecond,framesSent:M.framesSent,keyFramesEncoded:M.keyFramesEncoded,firCount:M.firCount,encoderImplementation:M.encoderImplementation,hugeFramesSent:M.hugeFramesSent,pliCount:M.pliCount,qpSum:M.qpSum,qualityLimitationDurations:M.qualityLimitationDurations,qualityLimitationReason:M.qualityLimitationReason,qualityLimitationResolutionChanges:M.qualityLimitationResolutionChanges,totalEncodeTime:M.targetBitrate,totalPacketSendDelay:M.totalPacketSendDelay,retransmittedBytesSent:M.retransmittedBytesSent,retransmittedPacketsSent:M.retransmittedPacketsSent,scalabilityMode:M.scalabilityMode,powerEfficientEncoder:M.powerEfficientEncoder},B);C.outboundVideoRtp.set(O.id,nt),C.producerStreamMap.get(R).outboundVideoRtpId.push(O.id),this.processOutboundProducerVideoStats(R,De,nt)}else if(k.mediaType==="audio"||k.kind==="audio"){const M=k,nt=U({retransmittedBytesSent:M.retransmittedBytesSent,retransmittedPacketsSent:M.retransmittedPacketsSent},B);C.outboundAudioRtp.set(O.id,nt),C.producerStreamMap.get(R).outboundAudioRtpId.push(O.id),this.processOutboundProducerAudioStats(R,De,nt)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${k.mediaType} kind: ${k.kind}`);break}case"inbound-rtp":{const k=O,R=i||this.inboundConsumerMap.get(O.id),H=this.pausedConsumerMap.get(R);if(H){if(H.lastReportCalculated===!0)break;this.pausedConsumerMap.set(R,{lastReportCalculated:!0})}if(k.ssrc===1234)break;this.overallConsumersStatsMap[R]||(this.overallConsumersStatsMap[R]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const De=this.overallConsumersStatsMap[R];if(["video","audio"].includes(k.mediaType)||["video","audio"].includes(k.kind)){if(!this.inboundConsumerMap.has(O.id)){C.staleConsumerStreamMap=!0;break}C.consumerStreamMap.has(R)||C.consumerStreamMap.set(R,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const rt={bytesReceived:k.bytesReceived,packetsReceived:k.packetsReceived,packetsLost:k.packetsLost>=0?k.packetsLost:0,jitter:k.jitter,nackCount:k.nackCount,jitterBufferDelay:k.jitterBufferDelay,jitterBufferEmittedCount:k.jitterBufferEmittedCount,lastPacketReceivedTimestamp:k.lastPacketReceivedTimestamp,ssrc:k.ssrc,mid:k.mid,codecId:k.codecId,headerBytesReceived:k.headerBytesReceived||0,packetsDiscarded:k.packetsDiscarded||0,jitterBufferMinimumDelay:k.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:k.jitterBufferTargetDelay||0};if(k.mediaType==="video"||k.kind==="video"){const B=k,M=U({frameHeight:B.frameHeight,frameWidth:B.frameWidth,framesDecoded:B.framesDecoded,framesDropped:B.framesDropped,framesPerSecond:B.framesPerSecond,framesReceived:B.framesReceived,keyFramesDecoded:B.keyFramesDecoded,firCount:B.firCount,decoderImplementation:B.decoderImplementation,pliCount:B.pliCount,totalProcessingDelay:B.totalProcessingDelay,qpSum:B.qpSum||0,totalAssemblyTime:B.totalAssemblyTime||0,totalDecodeTime:B.totalDecodeTime||0,totalFreezesDuration:B.totalFreezesDuration||0,totalInterFrameDelay:B.totalInterFrameDelay||0,totalPausesDuration:B.totalPausesDuration||0,totalSquaredInterFrameDelay:B.totalSquaredInterFrameDelay||0,freezeCount:B.freezeCount||0,pauseCount:B.pauseCount||0,powerEfficientDecoder:B.powerEfficientDecoder},rt);M.score=Gh({frameWidth:M.frameWidth||0,framesDecoded:(M.framesDecoded||0)-(((o=this.videoConsumerToStatsMap.get(R))==null?void 0:o.framesDecoded)||0),framesPerSecond:M.framesPerSecond||0,packetsLost:(M.packetsLost||0)-(((d=this.videoConsumerToStatsMap.get(R))==null?void 0:d.packetsLost)||0),packetsReceived:(M.packetsReceived||0)-(((h=this.videoConsumerToStatsMap.get(R))==null?void 0:h.packetsReceived)||0),jitter:M.jitter||0,isScreenShare:this.screenShareConsumers.has(R)}),Dt.set(R,{score:+(M.score*10).toFixed(),frameWidth:M.frameWidth||0,frameHeight:M.frameHeight||0,framesPerSecond:M.framesPerSecond||0,packetsLostPercentage:vo({packetsLost:(M.packetsLost||0)-(((p=this.videoConsumerToStatsMap.get(R))==null?void 0:p.packetsLost)||0),packetsReceived:(M.packetsReceived||0)-(((m=this.videoConsumerToStatsMap.get(R))==null?void 0:m.packetsReceived)||0)}),jitter:M.jitter||0,isScreenShare:this.screenShareConsumers.has(R),bitrate:((M.bytesReceived||0)-(((g=this.videoConsumerToStatsMap.get(R))==null?void 0:g.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(R,M),C.inboundVideoRtp.set(O.id,M),C.consumerStreamMap.get(R).inboundVideoRtpId.push(O.id),this.processInboundConsumerVideoStats(R,De,M)}else if(k.mediaType==="audio"||k.kind==="audio"){const B=k,M=U({audioLevel:B.audioLevel,concealedSamples:B.concealedSamples,concealmentEvents:B.concealmentEvents,totalAudioEnergy:B.totalAudioEnergy,totalSamplesDuration:B.totalSamplesDuration,totalSamplesReceived:B.totalSamplesReceived,fecPacketsDiscarded:B.fecPacketsDiscarded||0,fecPacketsReceived:B.fecPacketsReceived||0,insertedSamplesForDeceleration:B.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:B.removedSamplesForAcceleration||0,silentConcealedSamples:B.silentConcealedSamples||0,playoutId:B.playoutId},rt);M.score=Jh({concealmentEvents:(M.concealmentEvents||0)-(((v=this.audioConsumerToStatsMap.get(R))==null?void 0:v.concealmentEvents)||0),packetsLost:(M.packetsLost||0)-(((I=this.audioConsumerToStatsMap.get(R))==null?void 0:I.packetsLost)||0),packetsReceived:(M.packetsReceived||0)-(((A=this.audioConsumerToStatsMap.get(R))==null?void 0:A.packetsReceived)||0),jitter:M.jitter||0}),Dt.set(R,{score:+(M.score*10).toFixed(),packetsLostPercentage:vo({packetsLost:(M.packetsLost||0)-(((P=this.audioConsumerToStatsMap.get(R))==null?void 0:P.packetsLost)||0),packetsReceived:(M.packetsReceived||0)-(((D=this.audioConsumerToStatsMap.get(R))==null?void 0:D.packetsReceived)||0)}),jitter:M.jitter||0,isScreenShare:this.screenShareConsumers.has(R),bitrate:((M.bytesReceived||0)-(((N=this.audioConsumerToStatsMap.get(R))==null?void 0:N.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(R,M),C.inboundAudioRtp.set(O.id,M),C.consumerStreamMap.get(R).inboundAudioRtpId.push(O.id),this.processInboundConsumerAudioStats(R,De,M)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${k.mediaType} kind: ${k.kind}`);break}}}if(C.producerStreamMap.forEach((O,k)=>{var R,H,De,rt,B,M,nt,tn,Ua,Ba,ja,Ha,Wa,$a,Ja,Ga,qa,za,Ka,Ya,Qa,Xa,Za;if(O.outboundVideoRtpId.length>0){const we=[];O.outboundVideoRtpId.forEach(Ku=>{we.push(C.outboundVideoRtp.get(Ku))});const he=this.getWorkingSimulcastVideoStats(we);he.score=Wh({frameWidth:he.frameWidth||0,framesPerSecond:he.framesPerSecond||0,jitter:((R=he.remoteData)==null?void 0:R.jitter)||0,isScreenShare:this.screenShareProducers.has(k),packetsSent:(he.packetsSent||0)-(((H=this.videoProducerToStatsMap.get(k))==null?void 0:H.packetsSent)||0),packetsLost:(((De=he.remoteData)==null?void 0:De.packetsLost)||0)-(((B=(rt=this.videoProducerToStatsMap.get(k))==null?void 0:rt.remoteData)==null?void 0:B.packetsLost)||0),framesEncoded:(he.framesEncoded||0)-(((M=this.videoProducerToStatsMap.get(k))==null?void 0:M.framesEncoded)||0)}),Le.set(k,{score:+(he.score*10).toFixed(),frameWidth:he.frameWidth||0,frameHeight:he.frameHeight||0,framesPerSecond:he.framesPerSecond||0,jitter:((nt=he.remoteData)==null?void 0:nt.jitter)||0,isScreenShare:this.screenShareProducers.has(k),packetsLostPercentage:go({packetsSent:(he.packetsSent||0)-(((tn=this.videoProducerToStatsMap.get(k))==null?void 0:tn.packetsSent)||0),packetsLost:(((Ua=he.remoteData)==null?void 0:Ua.packetsLost)||0)-(((ja=(Ba=this.videoProducerToStatsMap.get(k))==null?void 0:Ba.remoteData)==null?void 0:ja.packetsLost)||0)}),bitrate:((he.bytesSent||0)-(((Ha=this.videoProducerToStatsMap.get(k))==null?void 0:Ha.bytesSent)||0))*8/7,cpuLimitations:he.qualityLimitationReason==="cpu",bandwidthLimitations:he.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(k,he)}else if(O.outboundAudioRtpId.length>0){const we=C.outboundAudioRtp.get(O.outboundAudioRtpId[0]);we.score=Hh({packetsSent:(we.packetsSent||0)-(((Wa=this.audioProducerToStatsMap.get(k))==null?void 0:Wa.packetsSent)||0),packetsLost:((($a=we.remoteData)==null?void 0:$a.packetsLost)||0)-(((Ga=(Ja=this.audioProducerToStatsMap.get(k))==null?void 0:Ja.remoteData)==null?void 0:Ga.packetsLost)||0),jitter:((qa=we.remoteData)==null?void 0:qa.jitter)||0}),Le.set(k,{score:+(we.score*10).toFixed(),bitrate:((we.bytesSent||0)-(((za=this.audioProducerToStatsMap.get(k))==null?void 0:za.bytesSent)||0))*8/7,packetsLostPercentage:go({packetsSent:(we.packetsSent||0)-(((Ka=this.audioProducerToStatsMap.get(k))==null?void 0:Ka.packetsSent)||0),packetsLost:(((Ya=we.remoteData)==null?void 0:Ya.packetsLost)||0)-(((Xa=(Qa=this.audioProducerToStatsMap.get(k))==null?void 0:Qa.remoteData)==null?void 0:Xa.packetsLost)||0)}),jitter:((Za=we.remoteData)==null?void 0:Za.jitter)||0,isScreenShare:this.screenShareProducers.has(k)}),this.audioProducerToStatsMap.set(k,we)}}),ae.forEach(O=>{const k=W.find(H=>H.id===O.localCandidateId?(O.localCandidateId=H.id,H):null),R=de.find(H=>H.id===O.remoteCandidateId?(O.remoteCandidateId=H.id,H):null);k&&(O.localCandidateType=k.type,O.localCandidateAddress=nn(k.address),O.localCandidatePort=k.port,O.localCandidateProtocol=k.protocol,O.localCandidateUrl=k.url,O.localCandidateNetworkType=k.networkType,O.localCandidateRelatedAddress=nn(k.relatedAddress),O.localCandidateRelatedPort=k.relatedPort),R&&(O.remoteCandidateType=R.type,O.remoteCandidateAddress=nn(R.address),O.remoteCandidatePort=R.port,O.remoteCandidateProtocol=R.protocol,O.remoteCandidateUrl=R.url)}),C.candidatePair&&(C.transport?(C.transport.totalRoundTripTime=C.candidatePair.totalRoundTripTime,C.transport.availableOutgoingBitrate=C.candidatePair.availableOutgoingBitrate,C.transport.availableIncomingBitrate=C.candidatePair.availableIncomingBitrate,C.transport.roundTripTime=C.candidatePair.currentRoundTripTime):C.transport={bytesReceived:C.candidatePair.bytesReceived,bytesSent:C.candidatePair.bytesSent,totalRoundTripTime:C.candidatePair.totalRoundTripTime,availableOutgoingBitrate:C.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:C.candidatePair.availableIncomingBitrate,roundTripTime:C.candidatePair.currentRoundTripTime}),C.transport&&(C.transport.candidatePairs=ae),C.transport&&!C.transport.roundTripTime){let O=0,k=0;C.remoteInboundRtp.forEach((R,H)=>{R.roundTripTime&&R.roundTripTime>O&&(O=R.roundTripTime,k=R.totalRoundTripTime)}),C.transport.roundTripTime=O,C.transport.totalRoundTripTime=k}if(Dt.size>0)try{this.observer.emit("consumer_score",Dt)}catch(O){}if(Le.size>0)try{this.observer.emit("producer_score",Le)}catch(O){}return C}getProducersReport(e){return u(this,null,function*(){const r=e.map(n=>this.generateProducerStreamMap(n,!0));return r.length>0?Promise.all(r):void 0})}getConsumersReport(e){return u(this,null,function*(){const r=e.map(n=>this.generateConsumerStreamMap(n,!0));return r.length>0?Promise.all(r):void 0})}getTransportReport(e){return u(this,null,function*(){return e.getStats()})}getProcessedStats(e,r,n){return u(this,null,function*(){const i=yield this.getTransportReport(e),s={producing:n,consuming:r,id:e.id},a=i,o=this.parseRTCReport(a,["transport","candidate-pair","inbound-rtp","outbound-rtp","remote-inbound-rtp","local-candidate","remote-candidate"],!1,void 0,s);if(!o)return;const d={stats:o.transport,transportId:e.id,consuming:r,producing:n},h=o.staleProducerStreamMap?void 0:this.getProducerStatsFromReport(o),p=o.staleConsumerStreamMap?void 0:this.getConsumerStatsFromReport(o);return{transportReport:d,producerReport:h,consumerReport:p}})}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((n,i)=>{var s,a;r.push({producerId:i,videoStats:n.outboundVideoRtpId.map(o=>e.outboundVideoRtp.get(o)),audioStats:n.outboundAudioRtpId.map(o=>e.outboundAudioRtp.get(o)),appData:((a=(s=this.callStatsInstance.producers)==null?void 0:s.get(i))==null?void 0:a.appData)||null})})}catch(n){this.callStatsInstance.logger.error("callStats::measurements::getProducerStatsFromReport",{error:{reason:n.reason,message:n.message}})}return r}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((n,i)=>{const{peerId:s,producerId:a,appData:o}=this.consumerPeerIdMap.get(i);r.push({consumerId:i,peerId:s,producerId:a,appData:o,videoStats:n.inboundVideoRtpId.map(d=>e.inboundVideoRtp.get(d)),audioStats:n.inboundAudioRtpId.map(d=>e.inboundAudioRtp.get(d))})})}catch(n){console.error("getConsumersReport: ",n,e)}return r}getUserLocation(){return u(this,null,function*(){return new Promise((e,r)=>{try{navigator.geolocation?navigator.geolocation.getCurrentPosition(n=>{e(n)}):r()}catch(n){r(n)}})})}getConnectivity(e){return u(this,null,function*(){try{const r={iceServers:e||zh},n=new Promise((h,p)=>{try{const m=new bS(r);m.addListener("done",h),m.addListener("failed",()=>{h({connectivity:!1})}),m.start(2e3)}catch(m){p(m)}}),i=new Promise((h,p)=>{try{const m=new wS(r);m.addListener("done",h),m.addListener("failed",()=>{h({connectivity:!1})}),m.start(2e3)}catch(m){p(m)}}),s=new Promise((h,p)=>{try{const m=new IS(r);m.addListener("done",h),m.addListener("failed",()=>{h({connectivity:!1})}),m.start(2e3)}catch(m){p(m)}}),[a,o,d]=yield Promise.all([n,i,s]);return{host:a==null?void 0:a.connectivity,relay:o==null?void 0:o.connectivity,reflexive:d==null?void 0:d.connectivity}}catch(r){return{host:!1,relay:!1,reflexive:!1}}})}getThroughput(e){return u(this,null,function*(){try{const r=yield new Promise((n,i)=>{try{const s={iceServers:e||zh},a=new _S(s);a.addListener("done",n),a.addListener("failed",i),a.start(1e4)}catch(s){i(s)}});return{throughput:r.throughput,fractionalLoss:0,RTT:r.RTT,jitter:0,backendRTT:r.backendRTT}}catch(r){return}})}getIPDetails(){return u(this,null,function*(){var e,r;try{return this.ipDetails||(this.ipDetails=yield Ld.getIPDetails({peerId:(e=this.callStatsInstance)==null?void 0:e.peerId,apiHostnames:(r=this.callStatsInstance)==null?void 0:r.apiHostnames,logger:this.callStatsInstance.logger})),this.ipDetails}catch(n){return}})}getNetworkQuality(e){return u(this,null,function*(){const[r,n]=yield Promise.all([this.getConnectivity(e),this.getThroughput(e)]);return{connectivity:r,throughput:n==null?void 0:n.throughput,fractionalLoss:n==null?void 0:n.fractionalLoss,RTT:n==null?void 0:n.RTT,jitter:n==null?void 0:n.jitter,backendRTT:n==null?void 0:n.backendRTT}})}getNetworkInfo(e,r=!1){return u(this,null,function*(){var n,i;if(r){const d=yield this.getIPDetails();return{ipDetails:d,effectiveNetworkType:(n=navigator.connection)==null?void 0:n.effectiveType,location:d!=null&&d.loc?Kh(d==null?void 0:d.loc):void 0}}const[s,a,o]=yield Promise.all([this.getConnectivity(e),this.getThroughput(e),this.getIPDetails()]);return{ipDetails:o,effectiveNetworkType:(i=navigator.connection)==null?void 0:i.effectiveType,location:o!=null&&o.loc?Kh(o==null?void 0:o.loc):void 0,turnConnectivity:s?s.host||s.relay||s.reflexive:!1,connectivity:s,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 PS extends Qh{}class Xh extends Qh{constructor(){super(...arguments),f(this,"producerMap",new Map),f(this,"consumerMap",new Map)}registerProducer(e){return u(this,null,function*(){this.producerMap.set(e.id,e),yield this.generateProducerStreamMap(e),e.observer.on("close",this.deregisterProducer.bind(this,e)),e.observer.on("pause",this.pauseProducer.bind(this,e.id)),e.observer.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)})}registerConsumer(e){return u(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.observer.on("close",this.deregisterConsumer.bind(this,e)),e.observer.on("pause",this.pauseConsumer.bind(this,e.id)),e.observer.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)})}generateConsumerStreamMap(e,r=!1){return u(this,null,function*(){const n=yield e.getStats(),i=this.parseRTCReport(n,["inbound-rtp"],!1,e.id),s=[...i.consumerStreamMap.values()][0],a=r?this.getConsumerStatsFromParsedConsumerStats(i,s,e.id):void 0;for(const o of n.values())switch(o.type){case"inbound-rtp":{this.inboundConsumerMap.set(o.id,e.id);break}}return a})}deregisterProducer(e){this.producerMap.delete(e.id),this.outboundProducerMap.forEach((r,n)=>{r===e.id&&this.outboundProducerMap.delete(n)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.consumerMap.delete(e.id),this.inboundConsumerMap.forEach((r,n)=>{r===e.id&&this.inboundConsumerMap.delete(n)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var r;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(r=e.relayProtocol)!=null?r:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}parseRTCReport(e,r=[],n=!1,i=void 0,s=void 0){var a,o,d,h,p,m,g,v,I,A,P,D,N;const J=e,C=new Yh,G=r.length?new Set(r):void 0,W=[],de=[],ae=[],Le=new Map,Dt=new Map;for(const O of J.values()){if(G){if(G.size===0)break;if(G.has(O.type))n&&G.delete(O.type);else continue}switch(O.type){case"local-candidate":{W.push(this.getIceCandidateStats(O));break}case"remote-candidate":{de.push(this.getIceCandidateStats(O));break}case"candidate-pair":{const{nominated:k}=O,{selected:R}=O,H=O,De={nominated:k!=null?k:R,currentRoundTripTime:H.currentRoundTripTime,totalRoundTripTime:H.totalRoundTripTime,bytesReceived:H.bytesReceived,bytesSent:H.bytesSent,availableOutgoingBitrate:H.availableOutgoingBitrate,availableIncomingBitrate:H.availableIncomingBitrate,lastPacketReceivedTimestamp:H.lastPacketReceivedTimestamp,lastPacketSentTimestamp:H.lastPacketSentTimestamp,localCandidateId:H.localCandidateId,remoteCandidateId:H.remoteCandidateId,bytesDiscardedOnSend:H.bytesDiscardedOnSend,packetsSent:H.packetsSent,packetsReceived:H.packetsReceived,packetsDiscardedOnSend:H.packetsDiscardedOnSend};ae.push(De),(O.nominated===!0||O.selected===!0)&&(C.candidatePair=De);break}case"transport":{const k=O;s&&(s.producing&&(this.overallProducingTransportsStatsMap[s.id]||(this.overallProducingTransportsStatsMap[s.id]={totalPacketsSent:0})),s.consuming&&(this.overallConsumingTransportsStatsMap[s.id]||(this.overallConsumingTransportsStatsMap[s.id]={totalPacketsReceived:0})));const R={bytesReceived:k.bytesReceived,bytesSent:k.bytesSent,packetsSent:k.packetsSent,packetsReceived:k.packetsReceived,dtlsCipher:k.dtlsCipher,dtlsState:k.dtlsState,iceRole:k.iceRole};if(C.transport=R,s){if(s.producing){const H=this.overallProducingTransportsStatsMap[s.id];this.processProducingTransportStats(s.id,H,R)}if(s.consuming){const H=this.overallConsumingTransportsStatsMap[s.id];this.processConsumingTransportStats(s.id,H,R)}}break}case"remote-inbound-rtp":{const k=O,R={jitter:k.jitter,fractionLost:k.fractionLost,roundTripTime:k.roundTripTime,roundTripTimeMeasurements:k.roundTripTimeMeasurements,totalRoundTripTime:k.totalRoundTripTime,packetsLost:k.packetsLost};C.remoteInboundRtp.set(k.localId,R);break}case"outbound-rtp":{const k=O,R=i||this.outboundProducerMap.get(O.id),H=this.pausedProducerMap.get(R);if(H){if(H.lastReportCalculated===!0)break;this.pausedProducerMap.set(R,{lastReportCalculated:!0})}this.overallProducersStatsMap[R]||(this.overallProducersStatsMap[R]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const De=this.overallProducersStatsMap[R];if(["video","audio"].includes(k.mediaType)||["video","audio"].includes(k.kind)){if(!this.outboundProducerMap.has(O.id)){C.staleProducerStreamMap=!0;break}const rt=this.callStatsInstance.producers.get(R);if(((a=rt==null?void 0:rt.track)==null?void 0:a.readyState)==="ended")break;C.producerStreamMap.has(R)||C.producerStreamMap.set(R,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const B={bytesSent:k.bytesSent,packetsSent:k.packetsSent,nackCount:k.nackCount,ssrc:k.ssrc,mid:k.mid,active:k.active,codecId:k.codecId,headerBytesSent:k.headerBytesSent||0,totalPacketSendDelay:k.totalPacketSendDelay||0};if(k.mediaType==="video"||k.kind==="video"){const M=k,nt=U({frameHeight:M.frameHeight,frameWidth:M.frameWidth,framesEncoded:M.framesEncoded,framesDropped:M.framesDropped?M.framesDropped:M.droppedFrames,framesPerSecond:M.framesPerSecond?M.framesPerSecond:M.framerateMean,framesSent:M.framesSent,keyFramesEncoded:M.keyFramesEncoded,firCount:M.firCount,encoderImplementation:M.encoderImplementation,hugeFramesSent:M.hugeFramesSent,pliCount:M.pliCount,qpSum:M.qpSum,qualityLimitationReason:M.qualityLimitationReason,qualityLimitationDurations:M.qualityLimitationDurations,qualityLimitationResolutionChanges:M.qualityLimitationResolutionChanges,totalEncodeTime:M.totalEncodeTime,totalPacketSendDelay:M.totalEncodeTime,retransmittedBytesSent:M.retransmittedBytesSent,retransmittedPacketsSent:M.retransmittedPacketsSent,scalabilityMode:M.scalabilityMode,powerEfficientEncoder:M.powerEfficientEncoder},B);C.outboundVideoRtp.set(O.id,nt),C.producerStreamMap.get(R).outboundVideoRtpId.push(O.id),this.processOutboundProducerVideoStats(R,De,nt)}else if(k.mediaType==="audio"||k.kind==="audio"){const M=k,nt=U({retransmittedBytesSent:M.retransmittedBytesSent,retransmittedPacketsSent:M.retransmittedPacketsSent},B);C.outboundAudioRtp.set(O.id,nt),C.producerStreamMap.get(R).outboundAudioRtpId.push(O.id),this.processOutboundProducerAudioStats(R,De,nt)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${k.mediaType} kind: ${k.kind}`);break}case"inbound-rtp":{const k=O,R=i||this.inboundConsumerMap.get(O.id),H=this.pausedConsumerMap.get(R);if(H){if(H.lastReportCalculated===!0)break;this.pausedConsumerMap.set(R,{lastReportCalculated:!0})}if(k.ssrc===1234)break;this.overallConsumersStatsMap[R]||(this.overallConsumersStatsMap[R]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const De=this.overallConsumersStatsMap[R];if(["video","audio"].includes(k.mediaType)||["video","audio"].includes(k.kind)){if(!this.inboundConsumerMap.has(O.id)){C.staleConsumerStreamMap=!0;break}C.consumerStreamMap.has(R)||C.consumerStreamMap.set(R,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const rt={bytesReceived:k.bytesReceived,packetsReceived:k.packetsReceived,packetsLost:k.packetsLost>=0?k.packetsLost:0,jitter:k.jitter,nackCount:k.nackCount,jitterBufferDelay:k.jitterBufferDelay,jitterBufferEmittedCount:k.jitterBufferEmittedCount,lastPacketReceivedTimestamp:k.lastPacketReceivedTimestamp,ssrc:k.ssrc,mid:k.mid,codecId:k.codecId,headerBytesReceived:k.headerBytesReceived||0,packetsDiscarded:k.packetsDiscarded||0,jitterBufferMinimumDelay:k.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:k.jitterBufferTargetDelay||0};if(k.mediaType==="video"||k.kind==="video"){const B=k,M=U({frameHeight:B.frameHeight,frameWidth:B.frameWidth,framesDecoded:B.framesDecoded,framesDropped:B.framesDropped?B.framesDropped:B.droppedFrames,framesPerSecond:B.framesPerSecond?B.framesPerSecond:B.framerateMean,framesReceived:B.framesReceived,keyFramesDecoded:B.keyFramesDecoded,firCount:B.firCount,decoderImplementation:B.decoderImplementation,pliCount:B.pliCount,totalProcessingDelay:B.totalProcessingDelay,qpSum:B.qpSum||0,totalAssemblyTime:B.totalAssemblyTime||0,totalDecodeTime:B.totalDecodeTime||0,totalFreezesDuration:B.totalFreezesDuration||0,totalInterFrameDelay:B.totalInterFrameDelay||0,totalPausesDuration:B.totalPausesDuration||0,totalSquaredInterFrameDelay:B.totalSquaredInterFrameDelay||0,freezeCount:B.freezeCount||0,pauseCount:B.pauseCount||0,powerEfficientDecoder:B.powerEfficientDecoder},rt);M.score=Gh({frameWidth:M.frameWidth||0,framesDecoded:(M.framesDecoded||0)-(((o=this.videoConsumerToStatsMap.get(R))==null?void 0:o.framesDecoded)||0),framesPerSecond:M.framesPerSecond||0,packetsLost:(M.packetsLost||0)-(((d=this.videoConsumerToStatsMap.get(R))==null?void 0:d.packetsLost)||0),packetsReceived:(M.packetsReceived||0)-(((h=this.videoConsumerToStatsMap.get(R))==null?void 0:h.packetsReceived)||0),jitter:M.jitter||0,isScreenShare:this.screenShareConsumers.has(R)}),Dt.set(R,{score:+(M.score*10).toFixed(),frameWidth:M.frameWidth||0,frameHeight:M.frameHeight||0,framesPerSecond:M.framesPerSecond||0,packetsLostPercentage:vo({packetsLost:(M.packetsLost||0)-(((p=this.videoConsumerToStatsMap.get(R))==null?void 0:p.packetsLost)||0),packetsReceived:(M.packetsReceived||0)-(((m=this.videoConsumerToStatsMap.get(R))==null?void 0:m.packetsReceived)||0)}),jitter:M.jitter||0,isScreenShare:this.screenShareConsumers.has(R),bitrate:((M.bytesReceived||0)-(((g=this.videoConsumerToStatsMap.get(R))==null?void 0:g.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(R,M),C.inboundVideoRtp.set(O.id,M),C.consumerStreamMap.get(R).inboundVideoRtpId.push(O.id),this.processInboundConsumerVideoStats(R,De,M)}else if(k.mediaType==="audio"||k.kind==="audio"){const B=k,M=U({audioLevel:B.audioLevel,concealedSamples:B.concealedSamples,concealmentEvents:B.concealmentEvents,totalAudioEnergy:B.totalAudioEnergy,totalSamplesDuration:B.totalSamplesDuration,totalSamplesReceived:B.totalSamplesReceived,fecPacketsDiscarded:B.fecPacketsDiscarded||0,fecPacketsReceived:B.fecPacketsReceived||0,insertedSamplesForDeceleration:B.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:B.removedSamplesForAcceleration||0,silentConcealedSamples:B.silentConcealedSamples||0,playoutId:B.playoutId},rt);M.score=Jh({concealmentEvents:(M.concealmentEvents||0)-(((v=this.audioConsumerToStatsMap.get(R))==null?void 0:v.concealmentEvents)||0),packetsLost:(M.packetsLost||0)-(((I=this.audioConsumerToStatsMap.get(R))==null?void 0:I.packetsLost)||0),packetsReceived:(M.packetsReceived||0)-(((A=this.audioConsumerToStatsMap.get(R))==null?void 0:A.packetsReceived)||0),jitter:M.jitter||0}),Dt.set(R,{score:+(M.score*10).toFixed(),packetsLostPercentage:vo({packetsLost:(M.packetsLost||0)-(((P=this.audioConsumerToStatsMap.get(R))==null?void 0:P.packetsLost)||0),packetsReceived:(M.packetsReceived||0)-(((D=this.audioConsumerToStatsMap.get(R))==null?void 0:D.packetsReceived)||0)}),jitter:M.jitter||0,isScreenShare:this.screenShareConsumers.has(R),bitrate:((M.bytesReceived||0)-(((N=this.audioConsumerToStatsMap.get(R))==null?void 0:N.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(R,M),C.inboundAudioRtp.set(O.id,M),C.consumerStreamMap.get(R).inboundAudioRtpId.push(O.id),this.processInboundConsumerAudioStats(R,De,M)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${k.mediaType} kind: ${k.kind}`);break}}}if(C.producerStreamMap.forEach((O,k)=>{var R,H,De,rt,B,M,nt,tn,Ua,Ba,ja,Ha,Wa,$a,Ja,Ga,qa,za,Ka,Ya,Qa,Xa,Za;if(O.outboundVideoRtpId.length>0){const we=[];O.outboundVideoRtpId.forEach(Ku=>{we.push(C.outboundVideoRtp.get(Ku))});const he=this.getWorkingSimulcastVideoStats(we);he.score=Wh({frameWidth:he.frameWidth||0,framesPerSecond:he.framesPerSecond||0,jitter:((R=he.remoteData)==null?void 0:R.jitter)||0,isScreenShare:this.screenShareProducers.has(k),packetsSent:(he.packetsSent||0)-(((H=this.videoProducerToStatsMap.get(k))==null?void 0:H.packetsSent)||0),packetsLost:(((De=he.remoteData)==null?void 0:De.packetsLost)||0)-(((B=(rt=this.videoProducerToStatsMap.get(k))==null?void 0:rt.remoteData)==null?void 0:B.packetsLost)||0),framesEncoded:(he.framesEncoded||0)-(((M=this.videoProducerToStatsMap.get(k))==null?void 0:M.framesEncoded)||0)}),Le.set(k,{score:+(he.score*10).toFixed(),frameWidth:he.frameWidth||0,frameHeight:he.frameHeight||0,framesPerSecond:he.framesPerSecond||0,jitter:((nt=he.remoteData)==null?void 0:nt.jitter)||0,isScreenShare:this.screenShareProducers.has(k),packetsLostPercentage:go({packetsSent:(he.packetsSent||0)-(((tn=this.videoProducerToStatsMap.get(k))==null?void 0:tn.packetsSent)||0),packetsLost:(((Ua=he.remoteData)==null?void 0:Ua.packetsLost)||0)-(((ja=(Ba=this.videoProducerToStatsMap.get(k))==null?void 0:Ba.remoteData)==null?void 0:ja.packetsLost)||0)}),bitrate:((he.bytesSent||0)-(((Ha=this.videoProducerToStatsMap.get(k))==null?void 0:Ha.bytesSent)||0))*8/7,cpuLimitations:he.qualityLimitationReason==="cpu",bandwidthLimitations:he.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(k,he)}else if(O.outboundAudioRtpId.length>0){const we=C.outboundAudioRtp.get(O.outboundAudioRtpId[0]);we.score=Hh({packetsSent:(we.packetsSent||0)-(((Wa=this.audioProducerToStatsMap.get(k))==null?void 0:Wa.packetsSent)||0),packetsLost:((($a=we.remoteData)==null?void 0:$a.packetsLost)||0)-(((Ga=(Ja=this.audioProducerToStatsMap.get(k))==null?void 0:Ja.remoteData)==null?void 0:Ga.packetsLost)||0),jitter:((qa=we.remoteData)==null?void 0:qa.jitter)||0}),Le.set(k,{score:+(we.score*10).toFixed(),bitrate:((we.bytesSent||0)-(((za=this.audioProducerToStatsMap.get(k))==null?void 0:za.bytesSent)||0))*8/7,packetsLostPercentage:go({packetsSent:(we.packetsSent||0)-(((Ka=this.audioProducerToStatsMap.get(k))==null?void 0:Ka.packetsSent)||0),packetsLost:(((Ya=we.remoteData)==null?void 0:Ya.packetsLost)||0)-(((Xa=(Qa=this.audioProducerToStatsMap.get(k))==null?void 0:Qa.remoteData)==null?void 0:Xa.packetsLost)||0)}),jitter:((Za=we.remoteData)==null?void 0:Za.jitter)||0,isScreenShare:this.screenShareProducers.has(k)}),this.audioProducerToStatsMap.set(k,we)}}),ae.forEach(O=>{const k=W.find(H=>H.id===O.localCandidateId?(O.localCandidateId=H.id,H):null),R=de.find(H=>H.id===O.remoteCandidateId?(O.remoteCandidateId=H.id,H):null);k&&(O.localCandidateType=k.type,O.localCandidateAddress=nn(k.address),O.localCandidatePort=k.port,O.localCandidateProtocol=k.protocol,O.localCandidateUrl=k.url,O.localCandidateNetworkType=k.networkType,O.localCandidateRelatedAddress=nn(k.relatedAddress),O.localCandidateRelatedPort=k.relatedPort),R&&(O.remoteCandidateType=R.type,O.remoteCandidateAddress=nn(R.address),O.remoteCandidatePort=R.port,O.remoteCandidateProtocol=R.protocol,O.remoteCandidateUrl=R.url)}),C.candidatePair&&(C.transport?(C.transport.bytesReceived=C.candidatePair.bytesReceived,C.transport.bytesSent=C.candidatePair.bytesSent,C.transport.totalRoundTripTime=C.candidatePair.totalRoundTripTime,C.transport.availableOutgoingBitrate=C.candidatePair.availableOutgoingBitrate,C.transport.availableIncomingBitrate=C.candidatePair.availableIncomingBitrate,C.transport.roundTripTime=C.candidatePair.currentRoundTripTime):C.transport={bytesReceived:C.candidatePair.bytesReceived,bytesSent:C.candidatePair.bytesSent,totalRoundTripTime:C.candidatePair.totalRoundTripTime,availableOutgoingBitrate:C.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:C.candidatePair.availableIncomingBitrate,roundTripTime:C.candidatePair.currentRoundTripTime}),C.transport&&(C.transport.candidatePairs=ae),C.transport&&!C.transport.roundTripTime){let O=0,k=0;C.remoteInboundRtp.forEach((R,H)=>{R.roundTripTime&&R.roundTripTime>O&&(O=R.roundTripTime,k=R.totalRoundTripTime)}),C.transport.roundTripTime=O,C.transport.totalRoundTripTime=k}if(Dt.size>0)try{this.observer.emit("consumer_score",Dt)}catch(O){}if(Le.size>0)try{this.observer.emit("producer_score",Le)}catch(O){}return C}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((n,i)=>{const s=this.producerMap.get(i),a=s.track.getSettings(),o=n.outboundVideoRtpId.map(h=>{const p=e.outboundVideoRtp.get(h);return p.frameHeight||(p.frameHeight=a.height,p.frameWidth=a.width,p.framesPerSecond=a.frameRate),p}),d={producerId:i,appData:s.appData,videoStats:o,audioStats:n.outboundAudioRtpId.map(h=>e.outboundAudioRtp.get(h))};r.push(d)})}catch(n){console.error("getProducersReport: ",n,e)}return r}getConsumerStatsFromParsedConsumerStats(e,r,n){let i;try{const{peerId:s,producerId:a,appData:o}=this.consumerPeerIdMap.get(n),d=r==null?void 0:r.inboundVideoRtpId.map(h=>{const p=this.consumerMap.get(n).track.getSettings(),m=e.inboundVideoRtp.get(h);return m.frameHeight||(m.frameHeight=p.height,m.frameWidth=p.width,m.framesPerSecond=p.frameRate),m});i={consumerId:n,peerId:s,producerId:a,appData:o,videoStats:d,audioStats:r==null?void 0:r.inboundAudioRtpId.map(h=>e.inboundAudioRtp.get(h))}}catch(s){console.error("getConsumerStatsFromParsedConsumerStats: ",s,e)}return i}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((n,i)=>{r.push(this.getConsumerStatsFromParsedConsumerStats(e,n,i))})}catch(n){console.error("getConsumerStatsFromReport: ",n,e)}return r}}class RS extends Xh{}function To(t,e,r,n){if(t!=null&&t.logger&&t.logger.error("Callstats::handleError",{error:n}),typeof r=="function"&&n instanceof e)r.call(null,n,t);else throw n}function Zh(t,e,r){const n=t.value;return t.value=function(...i){try{const s=n.apply(this,i);return s&&s instanceof Promise?s.catch(a=>{To(this,e,r,a)}):s}catch(s){To(this,e,r,s)}return null},t}const re=(t,e)=>(r,n,i)=>{const s=i.value;return i.value=function(...a){try{const o=s.apply(this,a);return o&&o instanceof Promise?o.catch(d=>{To(this,t,e,d)}):o}catch(o){To(this,t,e,o)}return null},i},AS=(t,e)=>(r,n,i)=>{if(i)return Zh(i,t,e);for(const s of Reflect.ownKeys(r.prototype).filter(a=>a!=="constructor")){const a=Object.getOwnPropertyDescriptor(r.prototype,s);a.value instanceof Function&&Object.defineProperty(r.prototype,s,Zh(a,t,e))}};var ee=globalThis&&globalThis.__decorate||function(t,e,r,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var o=t.length-1;o>=0;o--)(a=t[o])&&(s=(i<3?a(s):i>3?a(e,r,s):a(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s};const te=console;let Y=class extends ht{constructor(t="https://api.testingv3.dyte.in",e="Blink",r=Ts.PROD,n,i,s,a){switch(super(),f(this,"observer"),f(this,"eventHandler"),f(this,"measurements"),f(this,"producingTransport"),f(this,"consumingTransport"),f(this,"producers",new Map),f(this,"consumers",new Map),f(this,"iceServers"),f(this,"connectionInfoPromise"),f(this,"pingStatsTimeout"),f(this,"logger"),f(this,"env"),f(this,"apiHostnames"),f(this,"peerId"),f(this,"consumerSharedMediaStatesMap",new Map),f(this,"currentUserMediaStates",{}),this.env=r,this.apiHostnames=a,this.logger=i,this.peerId=s,this.eventHandler=new mS({logger:i,peerId:s,apiHostnames:a}),this.logger.debug("callStats::engineName: ",{engineName:e}),e){case"Blink":this.measurements=new PS;break;case"Gecko":this.measurements=new Xh;break;case"WebKit":this.measurements=new RS;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 ht,this.measurements.observer.on("consumer_score",o=>{i.debug(`callStats::consumer_score ${[...o.entries()]}`),this.eventHandler.emit("consumer_score",o)}),this.measurements.observer.on("producer_score",o=>{i.debug(`callStats::producer_score ${[...o.entries()]}`),this.eventHandler.emit("producer_score",o)})}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.observer.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.observer.on("close",this.deRegisterProducer.bind(this,t))}sendConsumerSharedMediaStateEvent(t,e){this.consumerSharedMediaStatesMap.has(t)||this.consumerSharedMediaStatesMap.set(t,{});const r=this.consumerSharedMediaStatesMap.get(t);this.consumerSharedMediaStatesMap.set(t,Object.assign(r,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(r=>{this.registerProducer(r)}),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(r=>{this.registerConsumer(r)}),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:V.PRECALL_TEST_BEGIN,timestamp:e}),this.connectionInfoPromise&&this.connectionInfoPromise.then(r=>{this.eventHandler.callEvent({event:V.PRECALL_TEST_COMPLETE,metaData:{connectionInfo:r},timestamp:e})})}sendScreenShareToggleEvent(t,e=null,r){this.currentUserMediaStates.screen=t,this.eventHandler.callEvent({event:t?V.SCREENSHARE_STARTED:V.SCREENSHARE_STOPPED,metaData:{ssrc:e},timestamp:r})}sendScreenShareRequestedEvent(t){this.eventHandler.callEvent({event:V.SCREENSHARE_START_REQUESTED,timestamp:t})}sendActiveSpeakerEvent(t,e){this.eventHandler.callEvent({event:V.DOMINANT_SPEAKER,metaData:{peerId:t},timestamp:e})}devices(t,e,r){this.eventHandler.callEvent({event:t===Qt.AUDIO&&V.AUDIO_DEVICES_UPDATES||t===Qt.VIDEO&&V.VIDEO_DEVICES_UPDATES||t===Qt.SPEAKER&&V.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:e},timestamp:r})}selectedDevice(t,e,r){this.eventHandler.callEvent({event:t===Qt.AUDIO&&V.SELECTED_MICROHPONE_UPDATE||t===Qt.VIDEO&&V.SELECTED_CAMERA_UPDATE||t===Qt.SPEAKER&&V.SELECTED_SPEAKER_UPDATE,metaData:{device:e},timestamp:r})}mediaPermission(t,e,r){this.eventHandler.callEvent({event:V.MEDIA_PERMISSION,metaData:{deviceType:t,permission:e},timestamp:r})}mediaPlaybackFailed(t,e){this.eventHandler.callEvent({event:t===Qt.AUDIO&&V.AUDIO_PLAY_FAILED||t===Qt.VIDEO&&V.VIDEO_PLAY_FAILED,metaData:{deviceType:t},timestamp:e})}mediaTrackMuted(t,e){this.eventHandler.callEvent({event:t===Qt.AUDIO&&V.AUDIO_TRACK_MUTED||t===Qt.VIDEO&&V.VIDEO_TRACK_MUTED,metaData:{deviceType:t},timestamp:e})}tabChanged(t,e){this.eventHandler.callEvent({event:V.TAB_CHANGE,metaData:{isMeetingsTabActive:t},timestamp:e})}browserBackgrounded(t){this.eventHandler.callEvent({event:V.BROWSER_BACKGROUNDED,timestamp:t})}browserForegrounded(t){this.eventHandler.callEvent({event:V.BROWSER_FOREGROUNDED,timestamp:t})}legacySwitch(t,e){this.eventHandler.callEvent({event:V.LEGACY_SWITCH,metadata:{on:t},timestamp:e})}getPreCallTestResults(){return u(this,null,function*(){return this.connectionInfoPromise})}sendCallJoinBeginEvent(t,e){t=X(U({},t),{meetingEnv:this.env}),t.deviceInfo=X(U({},t.deviceInfo),{userAgent:navigator.userAgent,cpus:navigator.hardwareConcurrency,memory:navigator.deviceMemory}),this.eventHandler.callEvent({event:V.CALL_JOIN_BEGIN,metaData:{peerMetaData:t},timestamp:e})}sendNetworkQualityTestBeginEvent(t,e){this.eventHandler.callEvent({event:V.NET_QUALITY_TEST_BEGIN,timestamp:e}),new Promise((r,n)=>u(this,null,function*(){const i=[];try{for(const s of t)try{if(s.iceServers&&s.iceServers.length>0){const a=yield this.measurements.getNetworkQuality(s.iceServers);i.push(X(U({},s),{networkResults:a}))}}catch(a){console.warn("Error handling ",a)}r({regionData:i})}catch(s){console.warn("Error in callstats, ",s),n(s)}})).then(r=>{this.eventHandler.callEvent({event:V.NET_QUALITY_TEST_END,timestamp:e,metaData:r})})}sendWebSocketConnectedEvent(t){this.eventHandler.callEvent({event:V.WEBSOCKET_CONNECTED,timestamp:t})}sendTransportConnectedEvent(t){this.eventHandler.callEvent({event:V.TRANSPORT_CONNECTED,timestamp:t})}sendAudioToggleEvent(t,e){this.currentUserMediaStates.audio=t;let r;t?r=V.AUDIO_ON:r=V.AUDIO_OFF,this.eventHandler.callEvent({event:r,timestamp:e})}sendVideoToggleEvent(t,e){this.currentUserMediaStates.video=t;let r;t?r=V.VIDEO_ON:r=V.VIDEO_OFF,this.eventHandler.callEvent({event:r,timestamp:e})}sendParticipantRoleToggleEvent(t,e){this.eventHandler.callEvent({event:V.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 u(this,null,function*(){let r,n;if(this.producingTransport&&(r=yield this.measurements.getProcessedStats(this.producingTransport,!1,!0),!r||!(r!=null&&r.producerReport))){this.logger.debug("callStats::sendPingStatsEvent::staleProducingTransport",{disclaimer:"Stale producer? Regenerating Stream Maps!"});const s=yield this.measurements.getProducersReport([...this.producers.values()]);r&&s?r.producerReport=s:(r=yield this.measurements.getProcessedStats(this.producingTransport,!1,!0),(!r||!(r!=null&&r.producerReport))&&this.logger.debug("callStats::sendPingStatsEvent::noProducingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}if(this.consumingTransport&&(n=yield this.measurements.getProcessedStats(this.consumingTransport,!0,!1),!n||!n.consumerReport)){this.logger.debug("callStats::sendPingStatsEvent::staleConsumingTransport",{disclaimer:"Stale consumer? Regenerating Stream Maps!"});const s=yield this.measurements.getConsumersReport([...this.consumers.values()]);n&&s?n.consumerReport=s:(n=yield this.measurements.getProcessedStats(this.consumingTransport,!0,!1),(!n||!n.consumerReport)&&this.logger.debug("callStats::sendPingStatsEvent::noConsumingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}const i={producingTransportStats:r?r==null?void 0:r.transportReport:void 0,consumingTransportStats:n?n==null?void 0:n.transportReport:void 0,producerStats:[].concat((r==null?void 0:r.producerReport)||[]).concat((n==null?void 0:n.producerReport)||[]),consumerStats:[].concat((n==null?void 0:n.consumerReport)||[]).concat((r==null?void 0:r.consumerReport)||[])};if(t&&i.producerStats.length===0&&i.consumerStats.length===0){yield this.eventHandler.flush();return}this.eventHandler.callEvent({event:V.PING_STAT,metaData:i,timestamp:e})})}sendIVSPlayerRebufferEvent(t){this.eventHandler.callEvent({event:V.IVS_PLAYER_REBUFFERING,timestamp:t})}sendIVSPlayerAudioBlockEvent(t){this.eventHandler.callEvent({event:V.IVS_PLAYER_AUDIO_BLOCKED,timestamp:t})}sendIVSPlayerPlaybackBlockedEvent(t){this.eventHandler.callEvent({event:V.IVS_PLAYER_PLAYBACK_BLOCKED,timestamp:t})}sendIVSPlayerNetworkUnavailableEvent(t){this.eventHandler.callEvent({event:V.IVS_PLAYER_NETWORK_UNAVAILABLE,timestamp:t})}sendIVSPlayerInitializedEvent(t){this.eventHandler.callEvent({event:V.IVS_PLAYER_INITIALIZED,timestamp:t})}sendIVSPlayerWorkerErrorEvent(t){this.eventHandler.callEvent({event:V.IVS_PLAYER_WORKER_ERROR,timestamp:t})}sendIVSPlayerErrorEvent(t,e){this.eventHandler.callEvent({event:V.IVS_PLAYER_ERROR,timestamp:e,metaData:t})}sendIVSPlayerRecoverableErrorEvent(t,e){this.eventHandler.callEvent({event:V.IVS_PLAYER_RECOVERABLE_ERROR,timestamp:e,metaData:t})}sendIVSPlayerAnalyticsEvent(t,e){this.eventHandler.callEvent({event:V.IVS_PLAYER_ANALYTICS_EVENT,timestamp:e,metaData:t})}sendIVSPlayerPlaybackRateChangedEvent(t,e){this.eventHandler.callEvent({event:V.IVS_PLAYER_PLAYBACK_RATE_CHANGED,timestamp:e,metaData:{updatedPlaybackRate:t}})}sendIVSPlayerQualityChanged(t,e){this.eventHandler.callEvent({event:V.IVS_PLAYER_QUALITY_CHANGED,timestamp:e,metaData:t})}sendPlayerLiveLatency(t,e){this.eventHandler.callEvent({event:V.LIVESTREAM_LATENCY,timestamp:e,metaData:{latency:t}})}sendDisconnectEvent(t){this.eventHandler.callEvent({event:V.DISCONNECT,timestamp:t})}sendReconnectEvent(t){this.eventHandler.callEvent({event:V.RECONNECT_ATTEMPT,timestamp:t})}expectedVideoResolution(t,e,r){this.eventHandler.callEvent({event:V.EXPECTED_VIDEO_RESOLUTION,timestamp:r,metaData:{frameWidth:t,frameHeight:e}})}expectedScreenshareResolution(t,e,r){this.eventHandler.callEvent({event:V.EXPECTED_SCREENSHARE_RESOLUTION,timestamp:r,metaData:{frameWidth:t,frameHeight:e}})}};ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"registerIceServers",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"registerConsumer",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"registerProducer",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendConsumerSharedMediaStateEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"registerProducingTransport",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"registerConsumingTransport",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"deRegisterConsumer",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"deRegisterProducer",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"disconnectConsumingTransport",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"disconnectProducingTransport",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendPreCallTestBeginEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendScreenShareToggleEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendScreenShareRequestedEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendActiveSpeakerEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"devices",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"selectedDevice",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"mediaPermission",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"mediaPlaybackFailed",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"mediaTrackMuted",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"tabChanged",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"browserBackgrounded",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"browserForegrounded",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"legacySwitch",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"getPreCallTestResults",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendCallJoinBeginEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendNetworkQualityTestBeginEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendWebSocketConnectedEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendTransportConnectedEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendAudioToggleEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendVideoToggleEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendParticipantRoleToggleEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"startPingStats",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"stopPingStats",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendPingStatsEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendIVSPlayerRebufferEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendIVSPlayerAudioBlockEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendIVSPlayerPlaybackBlockedEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendIVSPlayerNetworkUnavailableEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendIVSPlayerInitializedEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendIVSPlayerWorkerErrorEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendIVSPlayerErrorEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendIVSPlayerRecoverableErrorEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendIVSPlayerAnalyticsEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendIVSPlayerQualityChanged",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendPlayerLiveLatency",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendDisconnectEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendReconnectEvent",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"expectedVideoResolution",null),ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"expectedScreenshareResolution",null),Y=ee([AS(TypeError,(t,e)=>te.error(e,t))],Y);const MS=Y;class DS extends ht{constructor(){super(...arguments),f(this,"stats"),f(this,"peerId"),f(this,"backend"),f(this,"iceServers"),f(this,"initialized",!1),f(this,"stalled",!1),f(this,"ipInformation"),f(this,"logger")}initialize(e){return u(this,arguments,function*({peerId:r,engineName:n,env:i=Ts.PROD,iceServers:s,apiBase:a="https://api.cluster.dyte.in",flags:o,logger:d=console,apiHostnames:h,skipConnectivityChecks:p=!1}){var m,g,v;try{this.peerId=r,this.logger=d,this.ipInformation=yield Ld.getIPDetails({peerId:r,apiHostnames:h,logger:d}),this.backend=new MS(a,n,i,o,d,r,h),this.iceServers=s,(m=this.backend)==null||m.registerIceServers(this.iceServers),this.initialized=!0,(v=(g=this.backend)==null?void 0:g.eventHandler)==null||v.emit("initialized",this.ipInformation),this.emit("initialized",this.ipInformation),this.startPreCallTest(p)}catch(I){this.logger.error("callStats::CallStatsIntegration: ",{error:I}),this.stallCallStats()}})}configureSendTransport(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.registerProducingTransport(e)})}configureRecvTransport(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.registerConsumingTransport(e)})}candidateRegionalNetworkQualityTest(e){return u(this,null,function*(){const r=new Date;this.onSafeInitialization(()=>{var n;try{(n=this.backend)==null||n.sendNetworkQualityTestBeginEvent(e,r)}catch(i){this.logger.error("callStats::sendNetworkQualityTestBeginEvent",{error:{reason:i.reason}})}})})}roomJoined(e){return u(this,null,function*(){const r=new Date;this.onSafeInitialization(()=>{var n,i;(n=this.backend)==null||n.sendCallJoinBeginEvent(e,r),this.backend,(i=this.backend)==null||i.startPingStats()})})}audioOff(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendAudioToggleEvent(!1,e)})}audioOn(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendAudioToggleEvent(!0,e)})}videoOff(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendVideoToggleEvent(!1,e)})}videoOn(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendVideoToggleEvent(!0,e)})}callEnded(){const e=new Date;this.onSafeInitialization(()=>{var r,n;(r=this.backend)==null||r.stopPingStats(),(n=this.backend)==null||n.sendDisconnectEvent(e)})}screenShareStart(e){const r=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendScreenShareToggleEvent(!0,e,r)})}consumerSharedMediaState(e,r){this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendConsumerSharedMediaStateEvent(e,r)})}screenShareStop(e){const r=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendScreenShareToggleEvent(!1,e,r)})}screenShareRequested(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendScreenShareRequestedEvent(e)})}activeSpeaker(e){if(e!==this.peerId)return;const r=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendActiveSpeakerEvent(e,r)})}devices(e,r){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.devices(e,r,n)})}selectedDevice(e,r){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.selectedDevice(e,r,n)})}mediaPermission(e,r){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.mediaPermission(e,r,n)})}mediaPlaybackFailed(e){const r=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.mediaPlaybackFailed(e,r)})}mediaTrackMuted(e){const r=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.mediaTrackMuted(e,r)})}tabChanged(e=!1){const r=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.tabChanged(e,r)})}browserBackgrounded(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.browserBackgrounded(e)})}browserForegrounded(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.browserForegrounded(e)})}legacySwitch(e){const r=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.legacySwitch(e,r)})}startPreCallTest(e=!1){return u(this,null,function*(){const r=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendPreCallTestBeginEvent(e,r)})})}onPreCallTestResults(e){return this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.once("precall_end",e)}),e}onReceivingConsumerAudioStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_audio_status",e)})}onReceivingConsumerVideoStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_video_status",e)})}onReceivingProducerAudioStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_audio_status",e)})}onReceivingProducerVideoStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_video_status",e)})}onReceivingProducingTransportStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producing_transport_status",e)})}onReceivingConsumingTransportStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consuming_transport_status",e)})}onProducerScore(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_score",e)})}onConsumerScore(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_score",e)})}onSafeInitialization(e){if(this.initialized)e(this.ipInformation,!1);else if(!this.stalled){const r=n=>{e(n,!0)};return this.once("initialized",r),r}return()=>{}}removeInitializationListener(e){this.removeListener("initialized",e)}stallCallStats(){this.stalled=!0,this.removeAllListeners("initialized")}ivsPlayerEvent(e,r){const n=new Date;this.onSafeInitialization(()=>{var i,s,a,o,d,h,p,m,g,v,I;switch(e){case"PlayerRebuffering":(i=this.backend)==null||i.sendIVSPlayerRebufferEvent(n);break;case"PlayerAudioBlocked":(s=this.backend)==null||s.sendIVSPlayerAudioBlockEvent(n);break;case"PlayerPlaybackBlocked":(a=this.backend)==null||a.sendIVSPlayerPlaybackBlockedEvent(n);break;case"PlayerNetworkUnavailable":(o=this.backend)==null||o.sendIVSPlayerNetworkUnavailableEvent(n);break;case"PlayerInitialized":(d=this.backend)==null||d.sendIVSPlayerInitializedEvent(n);break;case"PlayerWorkerError":(h=this.backend)==null||h.sendIVSPlayerWorkerErrorEvent(n);break;case"PlayerError":(p=this.backend)==null||p.sendIVSPlayerErrorEvent(r,n);break;case"PlayerRecoverableError":(m=this.backend)==null||m.sendIVSPlayerRecoverableErrorEvent(r,n);break;case"PlayerAnalyticsEvent":(g=this.backend)==null||g.sendIVSPlayerAnalyticsEvent(r,n);break;case"PlayerPlaybackRateChanged":(v=this.backend)==null||v.sendIVSPlayerPlaybackRateChangedEvent(r,n);break;case"PlayerQualityChanged":(I=this.backend)==null||I.sendIVSPlayerQualityChanged(r,n);break}})}livestreamLatency(e){const r=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendPlayerLiveLatency(e,r)})}expectedVideoResolution(e,r){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.expectedVideoResolution(e,r,n)})}expectedScreenshareResolution(e,r){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.expectedScreenshareResolution(e,r,n)})}}const $=new DS;$.setMaxListeners(30);function OS(t){const{length:e}=this,r=t>=0?t:e+t;return r<0||r>=e?void 0:this[r]}Array.prototype.at||Object.assign(Array.prototype,{at:OS});function NS(t){const{length:e}=this,r=t>=0?t:e+t;return r<0||r>=e?void 0:this[r]}String.prototype.at||Object.assign(String.prototype,{at:NS});var xd={},LS={get exports(){return xd},set exports(t){xd=t}},ko={},xS={get exports(){return ko},set exports(t){ko=t}},ep=function(t,e){return function(){for(var r=new Array(arguments.length),n=0;n<r.length;n++)r[n]=arguments[n];return t.apply(e,r)}},FS=ep,sn=Object.prototype.toString;function Fd(t){return Array.isArray(t)}function Vd(t){return typeof t=="undefined"}function VS(t){return t!==null&&!Vd(t)&&t.constructor!==null&&!Vd(t.constructor)&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t)}function tp(t){return sn.call(t)==="[object ArrayBuffer]"}function US(t){return sn.call(t)==="[object FormData]"}function BS(t){var e;return typeof ArrayBuffer!="undefined"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&tp(t.buffer),e}function jS(t){return typeof t=="string"}function HS(t){return typeof t=="number"}function rp(t){return t!==null&&typeof t=="object"}function _o(t){if(sn.call(t)!=="[object Object]")return!1;var e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}function WS(t){return sn.call(t)==="[object Date]"}function $S(t){return sn.call(t)==="[object File]"}function JS(t){return sn.call(t)==="[object Blob]"}function np(t){return sn.call(t)==="[object Function]"}function GS(t){return rp(t)&&np(t.pipe)}function qS(t){return sn.call(t)==="[object URLSearchParams]"}function zS(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function KS(){return typeof navigator!="undefined"&&(navigator.product==="ReactNative"||navigator.product==="NativeScript"||navigator.product==="NS")?!1:typeof window!="undefined"&&typeof document!="undefined"}function Ud(t,e){if(!(t===null||typeof t=="undefined"))if(typeof t!="object"&&(t=[t]),Fd(t))for(var r=0,n=t.length;r<n;r++)e.call(null,t[r],r,t);else for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.call(null,t[i],i,t)}function Bd(){var t={};function e(i,s){_o(t[s])&&_o(i)?t[s]=Bd(t[s],i):_o(i)?t[s]=Bd({},i):Fd(i)?t[s]=i.slice():t[s]=i}for(var r=0,n=arguments.length;r<n;r++)Ud(arguments[r],e);return t}function YS(t,e,r){return Ud(e,function(n,i){r&&typeof n=="function"?t[i]=FS(n,r):t[i]=n}),t}function QS(t){return t.charCodeAt(0)===65279&&(t=t.slice(1)),t}var Ot={isArray:Fd,isArrayBuffer:tp,isBuffer:VS,isFormData:US,isArrayBufferView:BS,isString:jS,isNumber:HS,isObject:rp,isPlainObject:_o,isUndefined:Vd,isDate:WS,isFile:$S,isBlob:JS,isFunction:np,isStream:GS,isURLSearchParams:qS,isStandardBrowserEnv:KS,forEach:Ud,merge:Bd,extend:YS,trim:zS,stripBOM:QS},Ai=Ot;function ip(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var sp=function(t,e,r){if(!e)return t;var n;if(r)n=r(e);else if(Ai.isURLSearchParams(e))n=e.toString();else{var i=[];Ai.forEach(e,function(a,o){a===null||typeof a=="undefined"||(Ai.isArray(a)?o=o+"[]":a=[a],Ai.forEach(a,function(d){Ai.isDate(d)?d=d.toISOString():Ai.isObject(d)&&(d=JSON.stringify(d)),i.push(ip(o)+"="+ip(d))}))}),n=i.join("&")}if(n){var s=t.indexOf("#");s!==-1&&(t=t.slice(0,s)),t+=(t.indexOf("?")===-1?"?":"&")+n}return t},XS=Ot;function bo(){this.handlers=[]}bo.prototype.use=function(t,e,r){return this.handlers.push({fulfilled:t,rejected:e,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1},bo.prototype.eject=function(t){this.handlers[t]&&(this.handlers[t]=null)},bo.prototype.forEach=function(t){XS.forEach(this.handlers,function(e){e!==null&&t(e)})};var ZS=bo,eE=Ot,tE=function(t,e){eE.forEach(t,function(r,n){n!==e&&n.toUpperCase()===e.toUpperCase()&&(t[e]=r,delete t[n])})},ap=function(t,e,r,n,i){return t.config=e,r&&(t.code=r),t.request=n,t.response=i,t.isAxiosError=!0,t.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}},t},jd,op;function cp(){if(op)return jd;op=1;var t=ap;return jd=function(e,r,n,i,s){var a=new Error(e);return t(a,r,n,i,s)},jd}var Hd,dp;function rE(){if(dp)return Hd;dp=1;var t=cp();return Hd=function(e,r,n){var i=n.config.validateStatus;!n.status||!i||i(n.status)?e(n):r(t("Request failed with status code "+n.status,n.config,null,n.request,n))},Hd}var Wd,lp;function nE(){if(lp)return Wd;lp=1;var t=Ot;return Wd=t.isStandardBrowserEnv()?function(){return{write:function(e,r,n,i,s,a){var o=[];o.push(e+"="+encodeURIComponent(r)),t.isNumber(n)&&o.push("expires="+new Date(n).toGMTString()),t.isString(i)&&o.push("path="+i),t.isString(s)&&o.push("domain="+s),a===!0&&o.push("secure"),document.cookie=o.join("; ")},read:function(e){var r=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return r?decodeURIComponent(r[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}(),Wd}var up,hp;function iE(){return hp||(hp=1,up=function(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}),up}var pp,mp;function sE(){return mp||(mp=1,pp=function(t,e){return e?t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):t}),pp}var $d,fp;function aE(){if(fp)return $d;fp=1;var t=iE(),e=sE();return $d=function(r,n){return r&&!t(n)?e(r,n):n},$d}var Jd,gp;function oE(){if(gp)return Jd;gp=1;var t=Ot,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 Jd=function(r){var n={},i,s,a;return r&&t.forEach(r.split(`
13
+ `),function(o){if(a=o.indexOf(":"),i=t.trim(o.substr(0,a)).toLowerCase(),s=t.trim(o.substr(a+1)),i){if(n[i]&&e.indexOf(i)>=0)return;i==="set-cookie"?n[i]=(n[i]?n[i]:[]).concat([s]):n[i]=n[i]?n[i]+", "+s:s}}),n},Jd}var Gd,vp;function cE(){if(vp)return Gd;vp=1;var t=Ot;return Gd=t.isStandardBrowserEnv()?function(){var e=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a"),n;function i(s){var a=s;return e&&(r.setAttribute("href",a),a=r.href),r.setAttribute("href",a),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return n=i(window.location.href),function(s){var a=t.isString(s)?i(s):s;return a.protocol===n.protocol&&a.host===n.host}}():function(){return function(){return!0}}(),Gd}var qd,yp;function wo(){if(yp)return qd;yp=1;function t(e){this.message=e}return t.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},t.prototype.__CANCEL__=!0,qd=t,qd}var zd,Sp;function dE(){if(Sp)return zd;Sp=1;var t=Ot,e=rE(),r=nE(),n=sp,i=aE(),s=oE(),a=cE(),o=cp(),d=Io(),h=wo();return zd=function(p){return new Promise(function(m,g){var v=p.data,I=p.headers,A=p.responseType,P;function D(){p.cancelToken&&p.cancelToken.unsubscribe(P),p.signal&&p.signal.removeEventListener("abort",P)}t.isFormData(v)&&delete I["Content-Type"];var N=new XMLHttpRequest;if(p.auth){var J=p.auth.username||"",C=p.auth.password?unescape(encodeURIComponent(p.auth.password)):"";I.Authorization="Basic "+btoa(J+":"+C)}var G=i(p.baseURL,p.url);N.open(p.method.toUpperCase(),n(G,p.params,p.paramsSerializer),!0),N.timeout=p.timeout;function W(){if(N){var ae="getAllResponseHeaders"in N?s(N.getAllResponseHeaders()):null,Le=!A||A==="text"||A==="json"?N.responseText:N.response,Dt={data:Le,status:N.status,statusText:N.statusText,headers:ae,config:p,request:N};e(function(O){m(O),D()},function(O){g(O),D()},Dt),N=null}}if("onloadend"in N?N.onloadend=W:N.onreadystatechange=function(){!N||N.readyState!==4||N.status===0&&!(N.responseURL&&N.responseURL.indexOf("file:")===0)||setTimeout(W)},N.onabort=function(){N&&(g(o("Request aborted",p,"ECONNABORTED",N)),N=null)},N.onerror=function(){g(o("Network Error",p,null,N)),N=null},N.ontimeout=function(){var ae=p.timeout?"timeout of "+p.timeout+"ms exceeded":"timeout exceeded",Le=p.transitional||d.transitional;p.timeoutErrorMessage&&(ae=p.timeoutErrorMessage),g(o(ae,p,Le.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",N)),N=null},t.isStandardBrowserEnv()){var de=(p.withCredentials||a(G))&&p.xsrfCookieName?r.read(p.xsrfCookieName):void 0;de&&(I[p.xsrfHeaderName]=de)}"setRequestHeader"in N&&t.forEach(I,function(ae,Le){typeof v=="undefined"&&Le.toLowerCase()==="content-type"?delete I[Le]:N.setRequestHeader(Le,ae)}),t.isUndefined(p.withCredentials)||(N.withCredentials=!!p.withCredentials),A&&A!=="json"&&(N.responseType=p.responseType),typeof p.onDownloadProgress=="function"&&N.addEventListener("progress",p.onDownloadProgress),typeof p.onUploadProgress=="function"&&N.upload&&N.upload.addEventListener("progress",p.onUploadProgress),(p.cancelToken||p.signal)&&(P=function(ae){N&&(g(!ae||ae&&ae.type?new h("canceled"):ae),N.abort(),N=null)},p.cancelToken&&p.cancelToken.subscribe(P),p.signal&&(p.signal.aborted?P():p.signal.addEventListener("abort",P))),v||(v=null),N.send(v)})},zd}var Kd,Ep;function Io(){if(Ep)return Kd;Ep=1;var t=Ot,e=tE,r=ap,n={"Content-Type":"application/x-www-form-urlencoded"};function i(d,h){!t.isUndefined(d)&&t.isUndefined(d["Content-Type"])&&(d["Content-Type"]=h)}function s(){var d;return(typeof XMLHttpRequest!="undefined"||typeof process!="undefined"&&Object.prototype.toString.call(process)==="[object process]")&&(d=dE()),d}function a(d,h,p){if(t.isString(d))try{return(h||JSON.parse)(d),t.trim(d)}catch(m){if(m.name!=="SyntaxError")throw m}return(p||JSON.stringify)(d)}var o={transitional:{silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},adapter:s(),transformRequest:[function(d,h){return e(h,"Accept"),e(h,"Content-Type"),t.isFormData(d)||t.isArrayBuffer(d)||t.isBuffer(d)||t.isStream(d)||t.isFile(d)||t.isBlob(d)?d:t.isArrayBufferView(d)?d.buffer:t.isURLSearchParams(d)?(i(h,"application/x-www-form-urlencoded;charset=utf-8"),d.toString()):t.isObject(d)||h&&h["Content-Type"]==="application/json"?(i(h,"application/json"),a(d)):d}],transformResponse:[function(d){var h=this.transitional||o.transitional,p=h&&h.silentJSONParsing,m=h&&h.forcedJSONParsing,g=!p&&this.responseType==="json";if(g||m&&t.isString(d)&&d.length)try{return JSON.parse(d)}catch(v){if(g)throw v.name==="SyntaxError"?r(v,this,"E_JSON_PARSE"):v}return d}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(d){return d>=200&&d<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};return t.forEach(["delete","get","head"],function(d){o.headers[d]={}}),t.forEach(["post","put","patch"],function(d){o.headers[d]=t.merge(n)}),Kd=o,Kd}var lE=Ot,uE=Io(),hE=function(t,e,r){var n=this||uE;return lE.forEach(r,function(i){t=i.call(n,t,e)}),t},Tp,kp;function _p(){return kp||(kp=1,Tp=function(t){return!!(t&&t.__CANCEL__)}),Tp}var bp=Ot,Yd=hE,pE=_p(),mE=Io(),fE=wo();function Qd(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new fE("canceled")}var gE=function(t){Qd(t),t.headers=t.headers||{},t.data=Yd.call(t,t.data,t.headers,t.transformRequest),t.headers=bp.merge(t.headers.common||{},t.headers[t.method]||{},t.headers),bp.forEach(["delete","get","head","post","put","patch","common"],function(r){delete t.headers[r]});var e=t.adapter||mE.adapter;return e(t).then(function(r){return Qd(t),r.data=Yd.call(t,r.data,r.headers,t.transformResponse),r},function(r){return pE(r)||(Qd(t),r&&r.response&&(r.response.data=Yd.call(t,r.response.data,r.response.headers,t.transformResponse))),Promise.reject(r)})},Bt=Ot,wp=function(t,e){e=e||{};var r={};function n(h,p){return Bt.isPlainObject(h)&&Bt.isPlainObject(p)?Bt.merge(h,p):Bt.isPlainObject(p)?Bt.merge({},p):Bt.isArray(p)?p.slice():p}function i(h){if(Bt.isUndefined(e[h])){if(!Bt.isUndefined(t[h]))return n(void 0,t[h])}else return n(t[h],e[h])}function s(h){if(!Bt.isUndefined(e[h]))return n(void 0,e[h])}function a(h){if(Bt.isUndefined(e[h])){if(!Bt.isUndefined(t[h]))return n(void 0,t[h])}else return n(void 0,e[h])}function o(h){if(h in e)return n(t[h],e[h]);if(h in t)return n(void 0,t[h])}var d={url:s,method:s,data:s,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:o};return Bt.forEach(Object.keys(t).concat(Object.keys(e)),function(h){var p=d[h]||i,m=p(h);Bt.isUndefined(m)&&p!==o||(r[h]=m)}),r},Ip,Cp;function Pp(){return Cp||(Cp=1,Ip={version:"0.25.0"}),Ip}var vE=Pp().version,Xd={};["object","boolean","number","function","string","symbol"].forEach(function(t,e){Xd[t]=function(r){return typeof r===t||"a"+(e<1?"n ":" ")+t}});var Rp={};Xd.transitional=function(t,e,r){function n(i,s){return"[Axios v"+vE+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return function(i,s,a){if(t===!1)throw new Error(n(s," has been removed"+(e?" in "+e:"")));return e&&!Rp[s]&&(Rp[s]=!0,console.warn(n(s," has been deprecated since v"+e+" and will be removed in the near future"))),t?t(i,s,a):!0}};function yE(t,e,r){if(typeof t!="object")throw new TypeError("options must be an object");for(var n=Object.keys(t),i=n.length;i-- >0;){var s=n[i],a=e[s];if(a){var o=t[s],d=o===void 0||a(o,s,t);if(d!==!0)throw new TypeError("option "+s+" must be "+d);continue}if(r!==!0)throw Error("Unknown option "+s)}}var SE={assertOptions:yE,validators:Xd},Ap=Ot,EE=sp,Mp=ZS,Dp=gE,Co=wp,Op=SE,Mi=Op.validators;function ks(t){this.defaults=t,this.interceptors={request:new Mp,response:new Mp}}ks.prototype.request=function(t,e){if(typeof t=="string"?(e=e||{},e.url=t):e=t||{},!e.url)throw new Error("Provided config url is not valid");e=Co(this.defaults,e),e.method?e.method=e.method.toLowerCase():this.defaults.method?e.method=this.defaults.method.toLowerCase():e.method="get";var r=e.transitional;r!==void 0&&Op.assertOptions(r,{silentJSONParsing:Mi.transitional(Mi.boolean),forcedJSONParsing:Mi.transitional(Mi.boolean),clarifyTimeoutError:Mi.transitional(Mi.boolean)},!1);var n=[],i=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(e)===!1||(i=i&&m.synchronous,n.unshift(m.fulfilled,m.rejected))});var s=[];this.interceptors.response.forEach(function(m){s.push(m.fulfilled,m.rejected)});var a;if(!i){var o=[Dp,void 0];for(Array.prototype.unshift.apply(o,n),o=o.concat(s),a=Promise.resolve(e);o.length;)a=a.then(o.shift(),o.shift());return a}for(var d=e;n.length;){var h=n.shift(),p=n.shift();try{d=h(d)}catch(m){p(m);break}}try{a=Dp(d)}catch(m){return Promise.reject(m)}for(;s.length;)a=a.then(s.shift(),s.shift());return a},ks.prototype.getUri=function(t){if(!t.url)throw new Error("Provided config url is not valid");return t=Co(this.defaults,t),EE(t.url,t.params,t.paramsSerializer).replace(/^\?/,"")},Ap.forEach(["delete","get","head","options"],function(t){ks.prototype[t]=function(e,r){return this.request(Co(r||{},{method:t,url:e,data:(r||{}).data}))}}),Ap.forEach(["post","put","patch"],function(t){ks.prototype[t]=function(e,r,n){return this.request(Co(n||{},{method:t,url:e,data:r}))}});var TE=ks,Zd,Np;function kE(){if(Np)return Zd;Np=1;var t=wo();function e(r){if(typeof r!="function")throw new TypeError("executor must be a function.");var n;this.promise=new Promise(function(s){n=s});var i=this;this.promise.then(function(s){if(i._listeners){var a,o=i._listeners.length;for(a=0;a<o;a++)i._listeners[a](s);i._listeners=null}}),this.promise.then=function(s){var a,o=new Promise(function(d){i.subscribe(d),a=d}).then(s);return o.cancel=function(){i.unsubscribe(a)},o},r(function(s){i.reason||(i.reason=new t(s),n(i.reason))})}return e.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},e.prototype.subscribe=function(r){if(this.reason){r(this.reason);return}this._listeners?this._listeners.push(r):this._listeners=[r]},e.prototype.unsubscribe=function(r){if(this._listeners){var n=this._listeners.indexOf(r);n!==-1&&this._listeners.splice(n,1)}},e.source=function(){var r,n=new e(function(i){r=i});return{token:n,cancel:r}},Zd=e,Zd}var Lp,xp;function _E(){return xp||(xp=1,Lp=function(t){return function(e){return t.apply(null,e)}}),Lp}var el,Fp;function bE(){if(Fp)return el;Fp=1;var t=Ot;return el=function(e){return t.isObject(e)&&e.isAxiosError===!0},el}var Vp=Ot,wE=ep,Po=TE,IE=wp,CE=Io();function Up(t){var e=new Po(t),r=wE(Po.prototype.request,e);return Vp.extend(r,Po.prototype,e),Vp.extend(r,e),r.create=function(n){return Up(IE(t,n))},r}var Sr=Up(CE);Sr.Axios=Po,Sr.Cancel=wo(),Sr.CancelToken=kE(),Sr.isCancel=_p(),Sr.VERSION=Pp().version,Sr.all=function(t){return Promise.all(t)},Sr.spread=_E(),Sr.isAxiosError=bE(),xS.exports=Sr,ko.default=Sr,function(t){t.exports=ko}(LS);const Ro=iS(xd);function PE(){this.__data__=[],this.size=0}function _s(t,e){return t===e||t!==t&&e!==e}function Ao(t,e){for(var r=t.length;r--;)if(_s(t[r][0],e))return r;return-1}var RE=Array.prototype,AE=RE.splice;function ME(t){var e=this.__data__,r=Ao(e,t);if(r<0)return!1;var n=e.length-1;return r==n?e.pop():AE.call(e,r,1),--this.size,!0}function DE(t){var e=this.__data__,r=Ao(e,t);return r<0?void 0:e[r][1]}function OE(t){return Ao(this.__data__,t)>-1}function NE(t,e){var r=this.__data__,n=Ao(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}function Ar(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}Ar.prototype.clear=PE,Ar.prototype.delete=ME,Ar.prototype.get=DE,Ar.prototype.has=OE,Ar.prototype.set=NE;function LE(){this.__data__=new Ar,this.size=0}function xE(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r}function FE(t){return this.__data__.get(t)}function VE(t){return this.__data__.has(t)}var UE=typeof global=="object"&&global&&global.Object===Object&&global;const Bp=UE;var BE=typeof self=="object"&&self&&self.Object===Object&&self,jE=Bp||BE||Function("return this")();const nr=jE;var HE=nr.Symbol;const an=HE;var jp=Object.prototype,WE=jp.hasOwnProperty,$E=jp.toString,bs=an?an.toStringTag:void 0;function JE(t){var e=WE.call(t,bs),r=t[bs];try{t[bs]=void 0;var n=!0}catch(s){}var i=$E.call(t);return n&&(e?t[bs]=r:delete t[bs]),i}var GE=Object.prototype,qE=GE.toString;function zE(t){return qE.call(t)}var KE="[object Null]",YE="[object Undefined]",Hp=an?an.toStringTag:void 0;function jn(t){return t==null?t===void 0?YE:KE:Hp&&Hp in Object(t)?JE(t):zE(t)}function ir(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var QE="[object AsyncFunction]",XE="[object Function]",ZE="[object GeneratorFunction]",eT="[object Proxy]";function tl(t){if(!ir(t))return!1;var e=jn(t);return e==XE||e==ZE||e==QE||e==eT}var tT=nr["__core-js_shared__"];const rl=tT;var Wp=function(){var t=/[^.]+$/.exec(rl&&rl.keys&&rl.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();function rT(t){return!!Wp&&Wp in t}var nT=Function.prototype,iT=nT.toString;function Hn(t){if(t!=null){try{return iT.call(t)}catch(e){}try{return t+""}catch(e){}}return""}var sT=/[\\^$.*+?()[\]{}|]/g,aT=/^\[object .+?Constructor\]$/,oT=Function.prototype,cT=Object.prototype,dT=oT.toString,lT=cT.hasOwnProperty,uT=RegExp("^"+dT.call(lT).replace(sT,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function hT(t){if(!ir(t)||rT(t))return!1;var e=tl(t)?uT:aT;return e.test(Hn(t))}function pT(t,e){return t==null?void 0:t[e]}function Wn(t,e){var r=pT(t,e);return hT(r)?r:void 0}var mT=Wn(nr,"Map");const ws=mT;var fT=Wn(Object,"create");const Is=fT;function gT(){this.__data__=Is?Is(null):{},this.size=0}function vT(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var yT="__lodash_hash_undefined__",ST=Object.prototype,ET=ST.hasOwnProperty;function TT(t){var e=this.__data__;if(Is){var r=e[t];return r===yT?void 0:r}return ET.call(e,t)?e[t]:void 0}var kT=Object.prototype,_T=kT.hasOwnProperty;function bT(t){var e=this.__data__;return Is?e[t]!==void 0:_T.call(e,t)}var wT="__lodash_hash_undefined__";function IT(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=Is&&e===void 0?wT:e,this}function $n(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}$n.prototype.clear=gT,$n.prototype.delete=vT,$n.prototype.get=TT,$n.prototype.has=bT,$n.prototype.set=IT;function CT(){this.size=0,this.__data__={hash:new $n,map:new(ws||Ar),string:new $n}}function PT(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function Mo(t,e){var r=t.__data__;return PT(e)?r[typeof e=="string"?"string":"hash"]:r.map}function RT(t){var e=Mo(this,t).delete(t);return this.size-=e?1:0,e}function AT(t){return Mo(this,t).get(t)}function MT(t){return Mo(this,t).has(t)}function DT(t,e){var r=Mo(this,t),n=r.size;return r.set(t,e),this.size+=r.size==n?0:1,this}function Jn(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}Jn.prototype.clear=CT,Jn.prototype.delete=RT,Jn.prototype.get=AT,Jn.prototype.has=MT,Jn.prototype.set=DT;var OT=200;function NT(t,e){var r=this.__data__;if(r instanceof Ar){var n=r.__data__;if(!ws||n.length<OT-1)return n.push([t,e]),this.size=++r.size,this;r=this.__data__=new Jn(n)}return r.set(t,e),this.size=r.size,this}function Er(t){var e=this.__data__=new Ar(t);this.size=e.size}Er.prototype.clear=LE,Er.prototype.delete=xE,Er.prototype.get=FE,Er.prototype.has=VE,Er.prototype.set=NT;function LT(t,e){for(var r=-1,n=t==null?0:t.length;++r<n&&e(t[r],r,t)!==!1;);return t}var xT=function(){try{var t=Wn(Object,"defineProperty");return t({},"",{}),t}catch(e){}}();const Do=xT;function nl(t,e,r){e=="__proto__"&&Do?Do(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}var FT=Object.prototype,VT=FT.hasOwnProperty;function $p(t,e,r){var n=t[e];(!(VT.call(t,e)&&_s(n,r))||r===void 0&&!(e in t))&&nl(t,e,r)}function Cs(t,e,r,n){var i=!r;r||(r={});for(var s=-1,a=e.length;++s<a;){var o=e[s],d=n?n(r[o],t[o],o,r,t):void 0;d===void 0&&(d=t[o]),i?nl(r,o,d):$p(r,o,d)}return r}function UT(t,e){for(var r=-1,n=Array(t);++r<t;)n[r]=e(r);return n}function Tr(t){return t!=null&&typeof t=="object"}var BT="[object Arguments]";function Jp(t){return Tr(t)&&jn(t)==BT}var Gp=Object.prototype,jT=Gp.hasOwnProperty,HT=Gp.propertyIsEnumerable,WT=Jp(function(){return arguments}())?Jp:function(t){return Tr(t)&&jT.call(t,"callee")&&!HT.call(t,"callee")};const Oo=WT;var $T=Array.isArray;const on=$T;function JT(){return!1}var qp=typeof exports=="object"&&exports&&!exports.nodeType&&exports,zp=qp&&typeof module=="object"&&module&&!module.nodeType&&module,GT=zp&&zp.exports===qp,Kp=GT?nr.Buffer:void 0,qT=Kp?Kp.isBuffer:void 0,zT=qT||JT;const Di=zT;var KT=9007199254740991,YT=/^(?:0|[1-9]\d*)$/;function Yp(t,e){var r=typeof t;return e=e==null?KT:e,!!e&&(r=="number"||r!="symbol"&&YT.test(t))&&t>-1&&t%1==0&&t<e}var QT=9007199254740991;function Qp(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=QT}var XT="[object Arguments]",ZT="[object Array]",ek="[object Boolean]",tk="[object Date]",rk="[object Error]",nk="[object Function]",ik="[object Map]",sk="[object Number]",ak="[object Object]",ok="[object RegExp]",ck="[object Set]",dk="[object String]",lk="[object WeakMap]",uk="[object ArrayBuffer]",hk="[object DataView]",pk="[object Float32Array]",mk="[object Float64Array]",fk="[object Int8Array]",gk="[object Int16Array]",vk="[object Int32Array]",yk="[object Uint8Array]",Sk="[object Uint8ClampedArray]",Ek="[object Uint16Array]",Tk="[object Uint32Array]",Re={};Re[pk]=Re[mk]=Re[fk]=Re[gk]=Re[vk]=Re[yk]=Re[Sk]=Re[Ek]=Re[Tk]=!0,Re[XT]=Re[ZT]=Re[uk]=Re[ek]=Re[hk]=Re[tk]=Re[rk]=Re[nk]=Re[ik]=Re[sk]=Re[ak]=Re[ok]=Re[ck]=Re[dk]=Re[lk]=!1;function kk(t){return Tr(t)&&Qp(t.length)&&!!Re[jn(t)]}function il(t){return function(e){return t(e)}}var Xp=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ps=Xp&&typeof module=="object"&&module&&!module.nodeType&&module,_k=Ps&&Ps.exports===Xp,sl=_k&&Bp.process,bk=function(){try{var t=Ps&&Ps.require&&Ps.require("util").types;return t||sl&&sl.binding&&sl.binding("util")}catch(e){}}();const Oi=bk;var Zp=Oi&&Oi.isTypedArray,wk=Zp?il(Zp):kk;const No=wk;var Ik=Object.prototype,Ck=Ik.hasOwnProperty;function em(t,e){var r=on(t),n=!r&&Oo(t),i=!r&&!n&&Di(t),s=!r&&!n&&!i&&No(t),a=r||n||i||s,o=a?UT(t.length,String):[],d=o.length;for(var h in t)(e||Ck.call(t,h))&&!(a&&(h=="length"||i&&(h=="offset"||h=="parent")||s&&(h=="buffer"||h=="byteLength"||h=="byteOffset")||Yp(h,d)))&&o.push(h);return o}var Pk=Object.prototype;function Lo(t){var e=t&&t.constructor,r=typeof e=="function"&&e.prototype||Pk;return t===r}function tm(t,e){return function(r){return t(e(r))}}var Rk=tm(Object.keys,Object);const Ak=Rk;var Mk=Object.prototype,Dk=Mk.hasOwnProperty;function rm(t){if(!Lo(t))return Ak(t);var e=[];for(var r in Object(t))Dk.call(t,r)&&r!="constructor"&&e.push(r);return e}function Rs(t){return t!=null&&Qp(t.length)&&!tl(t)}function al(t){return Rs(t)?em(t):rm(t)}function Ok(t,e){return t&&Cs(e,al(e),t)}function Nk(t){var e=[];if(t!=null)for(var r in Object(t))e.push(r);return e}var Lk=Object.prototype,xk=Lk.hasOwnProperty;function Fk(t){if(!ir(t))return Nk(t);var e=Lo(t),r=[];for(var n in t)n=="constructor"&&(e||!xk.call(t,n))||r.push(n);return r}function As(t){return Rs(t)?em(t,!0):Fk(t)}function Vk(t,e){return t&&Cs(e,As(e),t)}var nm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,im=nm&&typeof module=="object"&&module&&!module.nodeType&&module,Uk=im&&im.exports===nm,sm=Uk?nr.Buffer:void 0,am=sm?sm.allocUnsafe:void 0;function om(t,e){if(e)return t.slice();var r=t.length,n=am?am(r):new t.constructor(r);return t.copy(n),n}function cm(t,e){var r=-1,n=t.length;for(e||(e=Array(n));++r<n;)e[r]=t[r];return e}function Bk(t,e){for(var r=-1,n=t==null?0:t.length,i=0,s=[];++r<n;){var a=t[r];e(a,r,t)&&(s[i++]=a)}return s}function dm(){return[]}var jk=Object.prototype,Hk=jk.propertyIsEnumerable,lm=Object.getOwnPropertySymbols,Wk=lm?function(t){return t==null?[]:(t=Object(t),Bk(lm(t),function(e){return Hk.call(t,e)}))}:dm;const ol=Wk;function $k(t,e){return Cs(t,ol(t),e)}function um(t,e){for(var r=-1,n=e.length,i=t.length;++r<n;)t[i+r]=e[r];return t}var Jk=tm(Object.getPrototypeOf,Object);const cl=Jk;var Gk=Object.getOwnPropertySymbols,qk=Gk?function(t){for(var e=[];t;)um(e,ol(t)),t=cl(t);return e}:dm;const hm=qk;function zk(t,e){return Cs(t,hm(t),e)}function pm(t,e,r){var n=e(t);return on(t)?n:um(n,r(t))}function dl(t){return pm(t,al,ol)}function Kk(t){return pm(t,As,hm)}var Yk=Wn(nr,"DataView");const ll=Yk;var Qk=Wn(nr,"Promise");const ul=Qk;var Xk=Wn(nr,"Set");const hl=Xk;var Zk=Wn(nr,"WeakMap");const pl=Zk;var mm="[object Map]",e0="[object Object]",fm="[object Promise]",gm="[object Set]",vm="[object WeakMap]",ym="[object DataView]",t0=Hn(ll),r0=Hn(ws),n0=Hn(ul),i0=Hn(hl),s0=Hn(pl),Gn=jn;(ll&&Gn(new ll(new ArrayBuffer(1)))!=ym||ws&&Gn(new ws)!=mm||ul&&Gn(ul.resolve())!=fm||hl&&Gn(new hl)!=gm||pl&&Gn(new pl)!=vm)&&(Gn=function(t){var e=jn(t),r=e==e0?t.constructor:void 0,n=r?Hn(r):"";if(n)switch(n){case t0:return ym;case r0:return mm;case n0:return fm;case i0:return gm;case s0:return vm}return e});const Ni=Gn;var a0=Object.prototype,o0=a0.hasOwnProperty;function c0(t){var e=t.length,r=new t.constructor(e);return e&&typeof t[0]=="string"&&o0.call(t,"index")&&(r.index=t.index,r.input=t.input),r}var d0=nr.Uint8Array;const xo=d0;function ml(t){var e=new t.constructor(t.byteLength);return new xo(e).set(new xo(t)),e}function l0(t,e){var r=e?ml(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.byteLength)}var u0=/\w*$/;function h0(t){var e=new t.constructor(t.source,u0.exec(t));return e.lastIndex=t.lastIndex,e}var Sm=an?an.prototype:void 0,Em=Sm?Sm.valueOf:void 0;function p0(t){return Em?Object(Em.call(t)):{}}function Tm(t,e){var r=e?ml(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.length)}var m0="[object Boolean]",f0="[object Date]",g0="[object Map]",v0="[object Number]",y0="[object RegExp]",S0="[object Set]",E0="[object String]",T0="[object Symbol]",k0="[object ArrayBuffer]",_0="[object DataView]",b0="[object Float32Array]",w0="[object Float64Array]",I0="[object Int8Array]",C0="[object Int16Array]",P0="[object Int32Array]",R0="[object Uint8Array]",A0="[object Uint8ClampedArray]",M0="[object Uint16Array]",D0="[object Uint32Array]";function O0(t,e,r){var n=t.constructor;switch(e){case k0:return ml(t);case m0:case f0:return new n(+t);case _0:return l0(t,r);case b0:case w0:case I0:case C0:case P0:case R0:case A0:case M0:case D0:return Tm(t,r);case g0:return new n;case v0:case E0:return new n(t);case y0:return h0(t);case S0:return new n;case T0:return p0(t)}}var km=Object.create,N0=function(){function t(){}return function(e){if(!ir(e))return{};if(km)return km(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();const L0=N0;function _m(t){return typeof t.constructor=="function"&&!Lo(t)?L0(cl(t)):{}}var x0="[object Map]";function F0(t){return Tr(t)&&Ni(t)==x0}var bm=Oi&&Oi.isMap,V0=bm?il(bm):F0;const U0=V0;var B0="[object Set]";function j0(t){return Tr(t)&&Ni(t)==B0}var wm=Oi&&Oi.isSet,H0=wm?il(wm):j0;const W0=H0;var $0=1,J0=2,G0=4,Im="[object Arguments]",q0="[object Array]",z0="[object Boolean]",K0="[object Date]",Y0="[object Error]",Cm="[object Function]",Q0="[object GeneratorFunction]",X0="[object Map]",Z0="[object Number]",Pm="[object Object]",e_="[object RegExp]",t_="[object Set]",r_="[object String]",n_="[object Symbol]",i_="[object WeakMap]",s_="[object ArrayBuffer]",a_="[object DataView]",o_="[object Float32Array]",c_="[object Float64Array]",d_="[object Int8Array]",l_="[object Int16Array]",u_="[object Int32Array]",h_="[object Uint8Array]",p_="[object Uint8ClampedArray]",m_="[object Uint16Array]",f_="[object Uint32Array]",Ce={};Ce[Im]=Ce[q0]=Ce[s_]=Ce[a_]=Ce[z0]=Ce[K0]=Ce[o_]=Ce[c_]=Ce[d_]=Ce[l_]=Ce[u_]=Ce[X0]=Ce[Z0]=Ce[Pm]=Ce[e_]=Ce[t_]=Ce[r_]=Ce[n_]=Ce[h_]=Ce[p_]=Ce[m_]=Ce[f_]=!0,Ce[Y0]=Ce[Cm]=Ce[i_]=!1;function Fo(t,e,r,n,i,s){var a,o=e&$0,d=e&J0,h=e&G0;if(r&&(a=i?r(t,n,i,s):r(t)),a!==void 0)return a;if(!ir(t))return t;var p=on(t);if(p){if(a=c0(t),!o)return cm(t,a)}else{var m=Ni(t),g=m==Cm||m==Q0;if(Di(t))return om(t,o);if(m==Pm||m==Im||g&&!i){if(a=d||g?{}:_m(t),!o)return d?zk(t,Vk(a,t)):$k(t,Ok(a,t))}else{if(!Ce[m])return i?t:{};a=O0(t,m,o)}}s||(s=new Er);var v=s.get(t);if(v)return v;s.set(t,a),W0(t)?t.forEach(function(P){a.add(Fo(P,e,r,P,t,s))}):U0(t)&&t.forEach(function(P,D){a.set(D,Fo(P,e,r,D,t,s))});var I=h?d?Kk:dl:d?As:al,A=p?void 0:I(t);return LT(A||t,function(P,D){A&&(D=P,P=t[D]),$p(a,D,Fo(P,e,r,D,t,s))}),a}var g_=1,v_=4;function fl(t){return Fo(t,g_|v_)}var y_="[object Symbol]";function S_(t){return typeof t=="symbol"||Tr(t)&&jn(t)==y_}var E_=Object.defineProperty,T_=(t,e)=>{for(var r in e)E_(t,r,{get:e[r],enumerable:!0})},k_={};T_(k_,{permissions:()=>__,theme:()=>b_});var gt=(t=>(t.GroupCall="GROUP_CALL",t.Webinar="WEBINAR",t.AudioRoom="AUDIO_ROOM",t.Livestream="LIVESTREAM",t.Chat="CHAT",t))(gt||{}),K=(t=>(t.Allowed="ALLOWED",t.NotAllowed="NOT_ALLOWED",t.CanRequest="CAN_REQUEST",t))(K||{}),__={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},b_={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}},Rm="hXgU8Wc8pwuGNq9ms5q9Hh",Am;typeof process!="undefined"&&(Am=process==null?void 0:process.env)!=null&&Am.FLAGSMITH_ENVIRONMENT_KEY&&(Rm={}.FLAGSMITH_ENVIRONMENT_KEY);function w_(t=[]){const e={};return t.forEach(r=>{e[r.feature.name]={enabled:r.enabled,value:r.feature_state_value}}),e}var I_=class{constructor(t=Rm){f(this,"flags",{}),f(this,"environmentKey",null),this.environmentKey=t,this.identify=this.identify.bind(this),this.getValue=this.getValue.bind(this),this.hasFeature=this.hasFeature.bind(this),this.getAllFlags=this.getAllFlags.bind(this)}identify(t){return u(this,arguments,function*(e,r={},n=!1,i=5e3,s="edge.api.flagsmith.com"){const a=JSON.parse(JSON.stringify(r)),o=Object.entries(a).map(d=>({trait_key:d[0],trait_value:d[1]}));try{const d="_"+(Math.random()+1).toString(36).substring(2),h=yield Ro.post(`https://${s}/api/v1/identities/`,{identifier:e+(n?d:""),traits:o},{headers:{"Content-Type":"application/json","X-Environment-Key":this.environmentKey},timeout:i});this.flags=w_(h.data.flags||[])}catch(d){}return 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}},Q=new I_,Mm=[-2,-1,0,1,2],C_=[0,1,2,3,4];function P_(t){t=t.trim();let e="0",r="0",n="0";return t.length==4?(e="0x"+t[1]+t[1],r="0x"+t[2]+t[2],n="0x"+t[3]+t[3]):t.length>6&&(e="0x"+t[1]+t[2],r="0x"+t[3]+t[4],n="0x"+t[5]+t[6]),[+e,+r,+n]}var R_=(t,e,r)=>{let n,i,s;if(e==0)n=i=s=r;else{const a=(h,p,m)=>(m<0&&(m+=1),m>1&&(m-=1),m<.16666666666666666?h+(p-h)*6*m:m<.5?p:m<.6666666666666666?h+(p-h)*(.6666666666666666-m)*6:h),o=r<.5?r*(1+e):r+e-r*e,d=2*r-o;n=a(d,o,t+1/3),i=a(d,o,t),s=a(d,o,t-1/3)}return[Math.round(n*255),Math.round(i*255),Math.round(s*255)]},A_=(t,e,r)=>{t/=255,e/=255,r/=255;const n=Math.max(t,e,r),i=Math.min(t,e,r);let s,a;const o=(n+i)/2;if(n==i)s=a=0;else{const d=n-i;switch(a=o>.5?d/(2-n-i):d/(n+i),n){case t:s=(e-r)/d+(e<r?6:0);break;case e:s=(r-t)/d+2;break;case r:s=(t-e)/d+4;break}s/=6}return[s,a,o]},M_=(t,e,r)=>{const n=i=>i.toString(16).padStart(2,"0");return`#${n(t)}${n(e)}${n(r)}`},Dm=(t,e=Mm,r=.4)=>{const n=[],[i,s,a]=P_(t),[o,d,h]=A_(i,s,a),p=Math.round(h*100);p>70?r=.8:p>60?r=.9:p<10?r=.075:p<42&&(r=.3);const m=e.findIndex(P=>P===0);if(m===-1)throw new Error("Invalid reducer provided, it must contain atleast one zero");const g=5-m,v=m+1,I=(100-p)/g,A=p/v;for(const P of e){let D;P<0?D=p+P*A*r:P>0?D=p+P*I*r:D=p;const[N,J,C]=R_(o,d,D/100);n.push(M_(N,J,C))}return n},Om={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"}},D_=t=>{const[e,r,n,i,s]=Dm(t,Mm);return{300:e,400:r,500:n,600:i,700:s}},O_=t=>{if(t==="#FFFFFF")return Om.light.background;if(t==="#000000")return Om.dark.background;const[e,r,n,i,s]=Dm(t,C_);return{1e3:e,900:r,800:n,700:i,600:s}},N_={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:D_("#2160FD"),background:O_("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function Nm(){return fl(N_)}var L_={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:Nm(),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},version:"hybrid"};function x_(){return fl(L_)}var F_={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:Nm(),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},version:"2.0.0"};function gl(){return fl(F_)}var V_=/\s/;function U_(t){for(var e=t.length;e--&&V_.test(t.charAt(e)););return e}var B_=/^\s+/;function j_(t){return t&&t.slice(0,U_(t)+1).replace(B_,"")}var Lm=0/0,H_=/^[-+]0x[0-9a-f]+$/i,W_=/^0b[01]+$/i,$_=/^0o[0-7]+$/i,J_=parseInt;function xm(t){if(typeof t=="number")return t;if(S_(t))return Lm;if(ir(t)){var e=typeof t.valueOf=="function"?t.valueOf():t;t=ir(e)?e+"":e}if(typeof t!="string")return t===0?t:+t;t=j_(t);var r=W_.test(t);return r||$_.test(t)?J_(t.slice(2),r?2:8):H_.test(t)?Lm:+t}function Fm(t){return t}function G_(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}var q_=800,z_=16,K_=Date.now;function Y_(t){var e=0,r=0;return function(){var n=K_(),i=z_-(n-r);if(r=n,i>0){if(++e>=q_)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function Q_(t){return function(){return t}}var X_=Do?function(t,e){return Do(t,"toString",{configurable:!0,enumerable:!1,value:Q_(e),writable:!0})}:Fm,Z_=Y_(X_);const eb=Z_;var Vm=Math.max;function tb(t,e,r){return e=Vm(e===void 0?t.length-1:e,0),function(){for(var n=arguments,i=-1,s=Vm(n.length-e,0),a=Array(s);++i<s;)a[i]=n[e+i];i=-1;for(var o=Array(e+1);++i<e;)o[i]=n[i];return o[e]=r(a),G_(t,this,o)}}function rb(t,e){return eb(tb(t,e,Fm),t+"")}function nb(t,e,r){if(!ir(r))return!1;var n=typeof e;return(n=="number"?Rs(r)&&Yp(e,r.length):n=="string"&&e in r)?_s(r[e],t):!1}function ib(t){return rb(function(e,r){var n=-1,i=r.length,s=i>1?r[i-1]:void 0,a=i>2?r[2]:void 0;for(s=t.length>3&&typeof s=="function"?(i--,s):void 0,a&&nb(r[0],r[1],a)&&(s=i<3?void 0:s,i=1),e=Object(e);++n<i;){var o=r[n];o&&t(e,o,n,s)}return e})}var sb="[object Object]",ab=Function.prototype,ob=Object.prototype,Um=ab.toString,cb=ob.hasOwnProperty,db=Um.call(Object);function lb(t){if(!Tr(t)||jn(t)!=sb)return!1;var e=cl(t);if(e===null)return!0;var r=cb.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&Um.call(r)==db}var ub="__lodash_hash_undefined__";function hb(t){return this.__data__.set(t,ub),this}function pb(t){return this.__data__.has(t)}function Vo(t){var e=-1,r=t==null?0:t.length;for(this.__data__=new Jn;++e<r;)this.add(t[e])}Vo.prototype.add=Vo.prototype.push=hb,Vo.prototype.has=pb;function mb(t,e){for(var r=-1,n=t==null?0:t.length;++r<n;)if(e(t[r],r,t))return!0;return!1}function fb(t,e){return t.has(e)}var gb=1,vb=2;function Bm(t,e,r,n,i,s){var a=r&gb,o=t.length,d=e.length;if(o!=d&&!(a&&d>o))return!1;var h=s.get(t),p=s.get(e);if(h&&p)return h==e&&p==t;var m=-1,g=!0,v=r&vb?new Vo:void 0;for(s.set(t,e),s.set(e,t);++m<o;){var I=t[m],A=e[m];if(n)var P=a?n(A,I,m,e,t,s):n(I,A,m,t,e,s);if(P!==void 0){if(P)continue;g=!1;break}if(v){if(!mb(e,function(D,N){if(!fb(v,N)&&(I===D||i(I,D,r,n,s)))return v.push(N)})){g=!1;break}}else if(!(I===A||i(I,A,r,n,s))){g=!1;break}}return s.delete(t),s.delete(e),g}function yb(t){var e=-1,r=Array(t.size);return t.forEach(function(n,i){r[++e]=[i,n]}),r}function Sb(t){var e=-1,r=Array(t.size);return t.forEach(function(n){r[++e]=n}),r}var Eb=1,Tb=2,kb="[object Boolean]",_b="[object Date]",bb="[object Error]",wb="[object Map]",Ib="[object Number]",Cb="[object RegExp]",Pb="[object Set]",Rb="[object String]",Ab="[object Symbol]",Mb="[object ArrayBuffer]",Db="[object DataView]",jm=an?an.prototype:void 0,vl=jm?jm.valueOf:void 0;function Ob(t,e,r,n,i,s,a){switch(r){case Db:if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case Mb:return!(t.byteLength!=e.byteLength||!s(new xo(t),new xo(e)));case kb:case _b:case Ib:return _s(+t,+e);case bb:return t.name==e.name&&t.message==e.message;case Cb:case Rb:return t==e+"";case wb:var o=yb;case Pb:var d=n&Eb;if(o||(o=Sb),t.size!=e.size&&!d)return!1;var h=a.get(t);if(h)return h==e;n|=Tb,a.set(t,e);var p=Bm(o(t),o(e),n,i,s,a);return a.delete(t),p;case Ab:if(vl)return vl.call(t)==vl.call(e)}return!1}var Nb=1,Lb=Object.prototype,xb=Lb.hasOwnProperty;function Fb(t,e,r,n,i,s){var a=r&Nb,o=dl(t),d=o.length,h=dl(e),p=h.length;if(d!=p&&!a)return!1;for(var m=d;m--;){var g=o[m];if(!(a?g in e:xb.call(e,g)))return!1}var v=s.get(t),I=s.get(e);if(v&&I)return v==e&&I==t;var A=!0;s.set(t,e),s.set(e,t);for(var P=a;++m<d;){g=o[m];var D=t[g],N=e[g];if(n)var J=a?n(N,D,g,e,t,s):n(D,N,g,t,e,s);if(!(J===void 0?D===N||i(D,N,r,n,s):J)){A=!1;break}P||(P=g=="constructor")}if(A&&!P){var C=t.constructor,G=e.constructor;C!=G&&"constructor"in t&&"constructor"in e&&!(typeof C=="function"&&C instanceof C&&typeof G=="function"&&G instanceof G)&&(A=!1)}return s.delete(t),s.delete(e),A}var Vb=1,Hm="[object Arguments]",Wm="[object Array]",Uo="[object Object]",Ub=Object.prototype,$m=Ub.hasOwnProperty;function Bb(t,e,r,n,i,s){var a=on(t),o=on(e),d=a?Wm:Ni(t),h=o?Wm:Ni(e);d=d==Hm?Uo:d,h=h==Hm?Uo:h;var p=d==Uo,m=h==Uo,g=d==h;if(g&&Di(t)){if(!Di(e))return!1;a=!0,p=!1}if(g&&!p)return s||(s=new Er),a||No(t)?Bm(t,e,r,n,i,s):Ob(t,e,d,r,n,i,s);if(!(r&Vb)){var v=p&&$m.call(t,"__wrapped__"),I=m&&$m.call(e,"__wrapped__");if(v||I){var A=v?t.value():t,P=I?e.value():e;return s||(s=new Er),i(A,P,r,n,s)}}return g?(s||(s=new Er),Fb(t,e,r,n,i,s)):!1}function Jm(t,e,r,n,i){return t===e?!0:t==null||e==null||!Tr(t)&&!Tr(e)?t!==t&&e!==e:Bb(t,e,r,n,Jm,i)}function jb(t){return function(e,r,n){for(var i=-1,s=Object(e),a=n(e),o=a.length;o--;){var d=a[t?o:++i];if(r(s[d],d,s)===!1)break}return e}}var Hb=jb();const Wb=Hb;var $b=function(){return nr.Date.now()};const yl=$b;var Jb="Expected a function",Gb=Math.max,qb=Math.min;function Mr(t,e,r){var n,i,s,a,o,d,h=0,p=!1,m=!1,g=!0;if(typeof t!="function")throw new TypeError(Jb);e=xm(e)||0,ir(r)&&(p=!!r.leading,m="maxWait"in r,s=m?Gb(xm(r.maxWait)||0,e):s,g="trailing"in r?!!r.trailing:g);function v(W){var de=n,ae=i;return n=i=void 0,h=W,a=t.apply(ae,de),a}function I(W){return h=W,o=setTimeout(D,e),p?v(W):a}function A(W){var de=W-d,ae=W-h,Le=e-de;return m?qb(Le,s-ae):Le}function P(W){var de=W-d,ae=W-h;return d===void 0||de>=e||de<0||m&&ae>=s}function D(){var W=yl();if(P(W))return N(W);o=setTimeout(D,A(W))}function N(W){return o=void 0,g&&n?v(W):(n=i=void 0,a)}function J(){o!==void 0&&clearTimeout(o),h=0,n=d=i=o=void 0}function C(){return o===void 0?a:N(yl())}function G(){var W=yl(),de=P(W);if(n=arguments,i=this,d=W,de){if(o===void 0)return I(d);if(m)return clearTimeout(o),o=setTimeout(D,e),v(d)}return o===void 0&&(o=setTimeout(D,e)),a}return G.cancel=J,G.flush=C,G}function Sl(t,e,r){(r!==void 0&&!_s(t[e],r)||r===void 0&&!(e in t))&&nl(t,e,r)}function zb(t){return Tr(t)&&Rs(t)}function El(t,e){if(!(e==="constructor"&&typeof t[e]=="function")&&e!="__proto__")return t[e]}function Kb(t){return Cs(t,As(t))}function Yb(t,e,r,n,i,s,a){var o=El(t,r),d=El(e,r),h=a.get(d);if(h){Sl(t,r,h);return}var p=s?s(o,d,r+"",t,e,a):void 0,m=p===void 0;if(m){var g=on(d),v=!g&&Di(d),I=!g&&!v&&No(d);p=d,g||v||I?on(o)?p=o:zb(o)?p=cm(o):v?(m=!1,p=om(d,!0)):I?(m=!1,p=Tm(d,!0)):p=[]:lb(d)||Oo(d)?(p=o,Oo(o)?p=Kb(o):(!ir(o)||tl(o))&&(p=_m(d))):m=!1}m&&(a.set(d,p),i(p,d,n,s,a),a.delete(d)),Sl(t,r,p)}function Gm(t,e,r,n,i){t!==e&&Wb(e,function(s,a){if(i||(i=new Er),ir(s))Yb(t,e,a,r,Gm,n,i);else{var o=n?n(El(t,a),s,a+"",t,e,i):void 0;o===void 0&&(o=s),Sl(t,a,o)}},As)}var Qb="[object Map]",Xb="[object Set]",Zb=Object.prototype,ew=Zb.hasOwnProperty;function tw(t){if(t==null)return!0;if(Rs(t)&&(on(t)||typeof t=="string"||typeof t.splice=="function"||Di(t)||No(t)||Oo(t)))return!t.length;var e=Ni(t);if(e==Qb||e==Xb)return!t.size;if(Lo(t))return!rm(t).length;for(var r in t)if(ew.call(t,r))return!1;return!0}function rw(t,e){return Jm(t,e)}var nw=ib(function(t,e,r){Gm(t,e,r)});const cn=nw;var Tl=(t=>(t.PARTICIPANT="PARTICIPANT",t.PEER="PEER",t.CLIENT="CLIENT",t))(Tl||{});const ie={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"};function Bo(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 qm(t){var e,r,n,i;const s=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((e=window.location.host)==null?void 0:e.includes("devel"))&&((r=window.location.host)==null?void 0:r.includes("dyte.io")),a=!!((i=(n=t==null?void 0:t.getValue("modules"))==null?void 0:n.devTools)!=null&&i.logs);return s||a}function iw(t){if(Q.hasFeature(ie.LOG_LEVEL)){let e=Q.getValue(ie.LOG_LEVEL)||"all";if(e=e.toLowerCase().trim(),e==="off")return!1;if(e!=="all"){const r=["debug","log","info","warn","error"],n=r.indexOf(t),i=r.indexOf(e);if(n<i)return!1}}return!0}function zm(t,e,r={}){return Object.getOwnPropertyNames(t).forEach(n=>{var i;if([null,void 0,NaN].includes(t[n])||e&&(((i=e.match(/\./g))==null?void 0:i.length)||0)>=10)return;const s=e?`${e}.${n}`:n;typeof t[n]=="object"?zm(t[n],s,r):["number","string","boolean"].includes(typeof t[n])&&(r[s]=t[n])}),r}function Km(t,e,r={},n=""){const i={};try{const s=JSON.stringify(r),a=JSON.parse(s),o=zm(a,n),d=JSON.stringify(o);if(d.length>5e3){const h=`Log named: "${e}" is trying to log an flattened object of size
14
+ ${d.length} chars that is beyond permitted limit of 5000 chars. Please optimize.`;throw qm(t)&&console.error(h,{log:r,flattened:d}),new Error(h)}return JSON.parse(d)}catch(s){const a=Bo(s);i[`${n}.error.message`]=a.message||"",i[`${n}.error.stack`]=a.stack||"",i[`${n}.error.reason`]=a.reason||"",i[`${n}.error.source`]="safelyFlattenObjForOpenTelemetry"}return i}const Ms="chrome",Ym="opera",Qm="firefox",Xm="iexplorer",Zm="safari",ef="nwjs",tf="electron",rf="react-native",kl="unknown",jo={Chrome:Ms,Chromium:Ms,Opera:Ym,Firefox:Qm,"Internet Explorer":Xm,Safari:Zm};function sw(){const{userAgent:t}=navigator,e={name:kl,version:void 0};if(t.match(/Chrome/)&&!t.match(/Edge/))if(t.match(/Edg(A?)/)){const r=t.match(/Chrome\/([\d.]+)/)[1];Number.parseInt(r,10)>72&&(e.name=Ms,e.version=r)}else e.name=Ms,e.version=t.match(/Chrome\/([\d.]+)/)[1];return e}function aw(){const{userAgent:t}=navigator;if(t.match(/Electron/)){const e=t.match(/Electron\/([\d.]+)/)[1];return{name:tf,version:e}}return null}function ow(){const{userAgent:t}=navigator;if(t.match(/JitsiMeetNW/)){const e=t.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:ef,version:e}}}function cw(){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:rf,version:e}}function dw(t){let e;const r=[cw,aw,ow];for(let i=0;i<r.length;i+=1)if(e=r[i](),e)return e;const n=t.getBrowserName();return n in jo?{name:jo[n],version:t.getBrowserVersion()}:(e=sw(),e||{name:kl,version:void 0})}class lw{constructor(){f(this,"_bowser"),f(this,"_name"),f(this,"_version"),f(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 r,n;if(this._bowser=Xu.getParser(navigator.userAgent),typeof e=="undefined"){const i=dw(this._bowser);r=i.name,n=i.version}else e.name in jo?(r=jo[e.name],n=e.version):(r=kl,n=void 0);this._name=r,this._version=n}getName(){return this._name}isChrome(){return this._name===Ms}isOpera(){return this._name===Ym}isFirefox(){return this._name===Qm}isIExplorer(){return this._name===Xm}isSafari(){return this._name===Zm}isNWJS(){return this._name===ef}isElectron(){return this._name===tf}isReactNative(){return this._name===rf||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 uw extends lw{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(r){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(process.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 Te=new uw,hw={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},Ds={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"},pw={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 Ho(t,e){const r=t.getValue("overrides");return r&&r[e]?r[e]:!1}function mw({baseURI:t}){return t!=null&&t.includes("preprod.dyte")?Ts.PREPROD:t!=null&&t.includes("devel.dyte")?Ts.DEVEL:Ts.PROD}function Li({servicePrefix:t,baseURI:e}){return`${t}.${e}`}function nf(t){const e=t.getValue("baseURI");return{location:Li({servicePrefix:"location",baseURI:e}),locationLegacy:Li({servicePrefix:"location-legacy",baseURI:e}),daCollector:Li({servicePrefix:"da-collector",baseURI:e})}}const fw='<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>',gw='<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>',Wo=t=>{if(!t)return;if(!t.startsWith("<svg"))return new Promise(i=>{i(t)});const e=new Blob([t],{type:"image/svg+xml"}),r=new Image,n=window.URL.createObjectURL(e);return new Promise((i,s)=>{r.onload=()=>{i(r),window.URL.revokeObjectURL(n)},r.onerror=()=>{s(),window.URL.revokeObjectURL(n)},r.src=n})};function vw(t){const e=U({},t),r=new Map,n=(a,o)=>(r.has(a)||r.set(a,new Set),r.get(a).add(o),()=>{var d;return(d=r.get(a))==null?void 0:d.delete(o)}),i=(a,o)=>{var d;(d=r.get(a))==null||d.delete(o)},s=a=>{var o;(o=r.get(a))==null||o.forEach(d=>{try{d(e[a])}catch(h){l.error(`Error in notifying for "${a.toString()}"`,h)}})};return{subscribe:n,unsubscribe:i,notify:s,setValue:(a,o,d=!0)=>{e[a]=o,d&&s(a)},getValue:a=>e[a],getAllValues:()=>e}}class yw{constructor(){f(this,"contexts",new Map),f(this,"mostRecentPeerId",null)}createContext(e,r){return this.contexts.has(e)?this.contexts.get(e):(this.contexts.set(e,vw(r)),this.mostRecentPeerId=e,this.contexts.get(e))}remapContext(e,r){const n=r.getValue("peerId");n!==e&&(r.setValue("peerId",e),this.mostRecentPeerId=e,this.contexts.set(e,r),this.contexts.delete(n))}getContext(e){return this.contexts.get(e)}getMostRecentPeerId(){return this.mostRecentPeerId}}const qn=new yw,fe=class{static get logsEndpoint(){const t=qn.getContext(fe.meetingMetadata.peerId);return`https://${Li({servicePrefix:"api-silos",baseURI:t.getValue("baseURI")})}/otel/logs`}static resetPeerId(t){fe.meetingMetadata.peerId=t}static init(t,e){const r=t.getValue("peerId");fe.tracingEnabled=e,fe.meetingMetadata.peerId=r,fe.meetingMetadata.sdkVersion=t.getValue("sdkVersion"),fe.meetingMetadata.deviceInfo=Te.getDeviceInfo(),fe.meetingMetadata.visitedUrl=!navigator.isReactNative&&typeof window!="undefined"&&window.location.href,navigator.isReactNative||document.addEventListener("visibilitychange",fe.processCachedLogs),fe.logsProcessorTimer=setInterval(fe.processCachedLogs,fe.logsProcessingInterval),e&&(fe.initialized=!0)}static trace(t,e=void 0){return(r,n,i)=>{const s=i.value;return i.value=function(...a){if(!fe.initialized||navigator.isReactNative||!fe.tracingEnabled||Q.hasFeature(ie.SKIP_OTEL_TRACES))return s.apply(this,a);fe.addLogInCurrentSpan("info",t,e);const o=performance.now(),d=s.apply(this,a);return Promise.resolve(d).then(()=>{const h=performance.now();h-o>10&&fe.addLogInCurrentSpan("info",`${t}_timing`,{execTime:h-o,country:fe.location.country})}).catch(()=>{const h=performance.now();fe.addLogInCurrentSpan("info",`${t}_timing`,{execTime:h-o})}),d},i}}static injectContext(t){var e;const r=Un().replace(/-/g,"").substring(0,16),n=(e=fe.meetingMetadata.peerId)==null?void 0:e.replace(/-/g,"");t.TRACEPARENT=`00-${n}-${r}-01`}static addLogInCurrentSpan(t,e,r={},n=!1){r!=null&&r.error&&Object.assign(r,{error:Bo(r.error)});const i=qn.getContext(fe.meetingMetadata.peerId);if(qm(i)&&(tw(r)?console[t]("DyteInternalLogs:: ",t,e):console[t]("DyteInternalLogs:: ",t,e,r)),!!iw(t))try{const s=Km(i,e,r,"metadata"),a=new Date,o=X(U({message:e,level:t},s),{loggedAt:a.toISOString(),loggedAtTzOffset:a.getTimezoneOffset()});n?fe.sendOtelLogsToNewRelic([o]):fe.logsCache.push(o)}catch(s){fe.addLogInCurrentSpan("error","opentelemetry::addLogInCurrentSpan_failed",{error:Bo(s)})}}static sendOtelLogsToNewRelic(t){const e=qn.getContext(fe.meetingMetadata.peerId);Ro.post(fe.logsEndpoint,{meetingMetadata:Km(e,"sendOtelLogsToNewRelic",fe.meetingMetadata,"meetingMetadata"),serviceName:e.getValue("sdkName"),logs:t}).catch(r=>{fe.addLogInCurrentSpan("error","opentelemetry::sendOtelLogToNewRelic_failed",{error:Bo(r)}),fe.logsCache.push(...t)})}static processCachedLogs(){const t=fe.logsCache.splice(0,25);t!=null&&t.length&&fe.sendOtelLogsToNewRelic(t)}static destruct(){clearInterval(fe.logsProcessorTimer),fe.processCachedLogs(),navigator.isReactNative||document.removeEventListener("visibilitychange",fe.processCachedLogs)}};let y=fe;f(y,"logsCache",[]),f(y,"logsProcessorTimer"),f(y,"location",{country:void 0}),f(y,"tracingEnabled",!0),f(y,"initialized",!1),f(y,"logsProcessingInterval",7e3),f(y,"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"]),f(y,"meetingMetadata",{});class l{static info(e,r,n){y.addLogInCurrentSpan("info",e,r,n)}static error(e,r,n){y.addLogInCurrentSpan("error",e,r,n)}static debug(e,r,n){y.addLogInCurrentSpan("debug",e,r,n)}static log(e,r,n){y.addLogInCurrentSpan("log",e,r,n)}static warn(e,r,n){y.addLogInCurrentSpan("warn",e,r,n)}}const Sw=()=>{!navigator.isReactNative&&typeof window!="undefined"&&(window.addEventListener("error",t=>{var e;!((e=t.filename)!=null&&e.includes("localhost"))&&t.lineno!==0&&l.error("window::error",{error:t.error},!0)}),window.addEventListener("unhandledrejection",t=>{var e,r,n,i,s,a,o,d;l.error("window::unhandledrejection",{error:t==null?void 0:t.reason,networkCall:{url:(r=(e=t==null?void 0:t.reason)==null?void 0:e.config)==null?void 0:r.url,baseURL:(i=(n=t==null?void 0:t.reason)==null?void 0:n.config)==null?void 0:i.baseURL,method:(a=(s=t==null?void 0:t.reason)==null?void 0:s.config)==null?void 0:a.method,status:(o=t==null?void 0:t.reason)==null?void 0:o.status,statusText:(d=t==null?void 0:t.reason)==null?void 0:d.statusText}},!0)}),window.addEventListener("offline",()=>{l.info("window::offline")}),window.addEventListener("online",()=>{l.info("window::online")}))},Ew={"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"},$o={"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($o).forEach(t=>{$o[t]=`{${Ew[t.slice(0,2)]}} ${$o[t]}`});class _ extends Error{constructor(e,r,n=!1){super(e),f(this,"code"),this.code=r,this.name="DyteError",this.message=`[ERR${this.code}]: ${$o[this.code]}
15
+ ${this.message}`;try{let i=n;r&&r.endsWith("00")&&(i=!0),i&&l.error("DyteError",{error:{message:this.message,name:this.name,code:r}});const s=qn.getContext(qn.getMostRecentPeerId());if(s){const a=s.getValue("onError");try{a(this)}catch(o){}}}catch(i){}}}function Jo(t,e,r,n){if(n instanceof _)throw n;if(n instanceof e){const i=new _(n.message,r);throw i.stack=n.stack,i}else throw n}function sf(t,e,r){if(!t.value){const i=t.get,s=t.set;return i&&(t.get=function(){try{return i.apply(this)}catch(a){Jo(this,e,r,a)}}),s&&(t.set=function(a){try{return s.apply(this,[a])}catch(o){Jo(this,e,r,o)}}),t}const n=t.value;return t.value=function(...i){try{const s=n.apply(this,i);return s&&s instanceof Promise?s.catch(a=>{Jo(this,e,r,a)}):s}catch(s){Jo(this,e,r,s)}},t}function Tw(t,e){return(r,n,i)=>{if(i)return sf(i,t,e);for(const s of Reflect.ownKeys(r.prototype).filter(a=>a!=="constructor")){const a=Object.getOwnPropertyDescriptor(r.prototype,s);(a.value instanceof Function||a.get instanceof Function||a.set instanceof Function)&&Object.defineProperty(r.prototype,s,sf(a,t,e))}}}const vt=t=>Tw(Error,t);function kw(t){let e=0,r,n;if(!t)return e;for(r=0;r<t.length;r+=1)n=t.charCodeAt(r),e=(e<<5)-e+n,e|=0;return Math.abs(e)%100+1}var dn,ln;const af=class extends ht.EventEmitter{constructor(){super(),T(this,dn,void 0),T(this,ln,void 0),f(this,"asyncPromiseTimeout"),S(this,dn,new Map),S(this,ln,new Map),this.asyncPromiseTimeout=8e3}emitAsync(t,...e){return u(this,null,function*(){c(this,dn).set(t,[]);const r=c(this,ln).get(t).map(()=>new Promise(n=>{c(this,dn).get(t).push(n)}));nS(af.prototype,this,"emit").call(this,t,...e),yield Promise.race([Promise.all(r),new Promise((n,i)=>setTimeout(()=>i(new Error(`emitAsync failed to resolve for event ${t}.`)),this.asyncPromiseTimeout))]),c(this,dn).delete(t)})}onAsync(t,e){const r=c(this,dn),n=(...i)=>u(this,null,function*(){var s;try{yield e(...i)}catch(o){l.error("[onAsync]",{error:o})}const a=(s=r.get(t))==null?void 0:s.shift();a==null||a()});return c(this,ln).get(t)||c(this,ln).set(t,[]),c(this,ln).get(t).push(n),super.on(t,n)}reset(){S(this,dn,new Map),S(this,ln,new Map),super.removeAllListeners()}};let _w=af;dn=new WeakMap,ln=new WeakMap;const b=new _w;function bw(){Te.isElectron()&&window.dyteElectronGetDisplayMediaSource&&(navigator.mediaDevices.getDisplayMedia=()=>u(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 r=e.find(i=>{var s;return(s=i.id)==null?void 0:s.includes("screen")});r=r!=null?r:e[0];const n={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:r.id}}};return yield navigator.mediaDevices.getUserMedia(n)}))}var w=(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))(w||{});class xi extends ht.EventEmitter{constructor(){super(),super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}on(e,r){try{const n=this.listenerCount(e);n>25&&n%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch(n){}return super.on(e,r)}addListener(e,r){try{const n=this.listenerCount(e);n>25&&n%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch(n){}return super.addListener(e,r)}off(e,r){return super.off(e,r)}once(e,r){return super.once(e,r)}prependListener(e,r){return super.prependListener(e,r)}prependOnceListener(e,r){return super.prependOnceListener(e,r)}removeListener(e,r){return super.removeListener(e,r)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}class jt extends ht.EventEmitter{constructor(){super(),super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}on(e,r){try{const n=this.listenerCount(e);n>25&&n%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch(n){}return super.on(e,r)}addListener(e,r){try{const n=this.listenerCount(e);n>25&&n%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch(n){}return super.addListener(e,r)}off(e,r){return super.off(e,r)}once(e,r){return super.once(e,r)}prependListener(e,r){return super.prependListener(e,r)}prependOnceListener(e,r){return super.prependOnceListener(e,r)}removeListener(e,r){return super.removeListener(e,r)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}function ww(t,e=2){return t.replace(/[^\u00BF-\u1FFF\u2C00-\uD7FF\w\s]/g,"").trim().split(/\s+/).slice(0,e).map(r=>r.charAt(0)).join("").toUpperCase()}const of=1080,cf=1920,Iw=(t,e,r,n,i,s)=>{let a=.5,o=.5;const d=i,h=s,p=Math.min(r/d,n/h);let m=d*p,g=h*p,v,I,A,P,D=1;return m<r&&(D=r/m),Math.abs(D-1)<1e-14&&g<n&&(D=n/g),m*=D,g*=D,A=d/(m/r),P=h/(g/n),v=(d-A)*a,I=(h-P)*o,v<0&&(v=0),I<0&&(I=0),A>d&&(A=d),P>h&&(P=h),[v,I,A,P,t,e,r,n]};var sr,Os,Tt,ar,Ge,kr,un,Nt,Xe,Ns,Ls,hn,xs;const df=class extends jt{constructor(t,e,r,n){super(),T(this,sr,void 0),T(this,Os,void 0),T(this,Tt,void 0),T(this,ar,void 0),T(this,Ge,{height:of,width:cf}),T(this,kr,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"}),T(this,un,void 0),T(this,Nt,{}),T(this,Xe,void 0),T(this,Ns,void 0),T(this,Ls,void 0),T(this,hn,void 0),T(this,xs,!1),f(this,"cleanupEventListeners",()=>{c(this,Os).unsubscribe("stageStatus",this.handlePipMediaControls),c(this,Xe).removeListener("videoUpdate",this.onSelfVideoUpdateListener),c(this,Xe).removeListener("audioUpdate",this.onSelfAudioUpdateListener),c(this,Xe).removeListener("roomLeft",()=>this.disable())}),f(this,"enablePipMediaControls",()=>{this.mountAudioEvents(),this.mountVideoEvents()}),f(this,"onSelfVideoUpdateListener",({videoEnabled:i})=>{this.updateMediaSession("CAMERA",i)}),f(this,"onSelfAudioUpdateListener",({audioEnabled:i})=>{this.updateMediaSession("MIC",i)}),f(this,"handlePipMediaControls",i=>{i==="ON_STAGE"?this.enablePipMediaControls():this.unmountEvents()}),f(this,"eventCallback",i=>{i==="CAMERA"&&(c(this,Xe).videoEnabled?c(this,Xe).disableVideo():c(this,Xe).enableVideo(),this.emit("cameraToggled")),i==="MIC"&&(c(this,Xe).audioEnabled?c(this,Xe).disableAudio():c(this,Xe).enableAudio(),this.emit("micToggled")),i==="END"&&(b.emit(w.PIP_HANGUP),this.cleanupEventListeners(),this.emit("hangup"),this.cleanup())}),f(this,"unmountEvents",()=>{navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("togglemicrophone",void 0),navigator.mediaSession.setActionHandler("togglecamera",void 0))}),f(this,"animate",()=>{if(!this.isActive&&c(this,hn)==="active"){this.disable(!0);return}c(this,Nt)!==void 0&&this.paintCanvas(),c(this,un)!==void 0&&S(this,un,requestAnimationFrame(()=>this.animate()))}),f(this,"disable",(i=!1)=>{S(this,hn,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(c(this,un)),i!==!0&&document.body.removeChild(c(this,Tt)),S(this,un,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()}),S(this,Os,t),S(this,hn,"idle"),S(this,Xe,e),S(this,kr,{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}),r&&this.setupIcon("pin",r),n&&this.setupIcon("handRaise",n)}static _init(t,e){return u(this,null,function*(){let r,n;try{r=yield Wo(fw),n=yield Wo(gw)}catch(i){}return new df(t,e,r,n)})}setupIcon(t,e){return u(this,null,function*(){switch(t){case"handRaise":S(this,Ls,e);break;case"pin":S(this,Ns,e);break}})}overrideIcon(t,e){return u(this,null,function*(){switch(t){case"handRaise":S(this,Ls,yield Wo(e));break;case"pin":S(this,Ns,yield Wo(e));break}})}constructImage(t){const e=new Image,r=new Blob([t],{type:"image/svg+xml"}),n=window.URL.createObjectURL(r);return new Promise(i=>{e.onload=()=>{i(e),window.URL.revokeObjectURL(n)},e.src=n})}createVideoContainer(){S(this,Tt,document.createElement("div")),c(this,Tt).style.width="0.1px",c(this,Tt).style.height="0.1px",c(this,Tt).style.overflow="hidden",c(this,Tt).style.position="absolute",c(this,Tt).style.bottom="0",c(this,Tt).style.right="0",c(this,Tt).style.opacity="0",c(this,Tt).appendChild(c(this,ar))}setupEventListeners(){c(this,Os).subscribe("stageStatus",this.handlePipMediaControls),c(this,Xe).addListener("videoUpdate",this.onSelfVideoUpdateListener),c(this,Xe).addListener("audioUpdate",this.onSelfAudioUpdateListener),c(this,Xe).addListener("roomLeft",()=>this.disable())}createCanvas(){const t=document.createElement("canvas");t.height=c(this,Ge).height,t.width=c(this,Ge).width,S(this,sr,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||c(this,Xe).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||c(this,Xe).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const t=Object.values(c(this,Nt)).reduce((e,r)=>(e[r.pinned?"pinned":"regular"].push(r),e),{pinned:[],regular:[]});return[...t.pinned,...t.regular]}drawEmptyTile(t,e,r,n){if(c(this,sr)===void 0)return;const i=c(this,sr).getContext("2d"),s=c(this,sr).width,a=0,o=0,d=e-a*2,h=r-a*2,p=Math.floor(s/d),m=Math.floor(t/p),g=t%p*(d+a)+a,v=m*(h+a)+a,{displayText:I,image:A}=n!=null?n:{};i.fillStyle=I||A?c(this,kr).videoBackground:c(this,kr).background,i.strokeStyle=c(this,kr).brand,i.beginPath(),i.moveTo(g+o,v),i.arcTo(g+d,v,g+d,v+o,o),i.arcTo(g+d,v+h,g+d-o,v+h,o),i.arcTo(g,v+h,g,v+h-o,o),i.arcTo(g,v,g+o,v,o),i.closePath(),i.fill(),i.stroke();const P=d/6,D=d/2+g,N=h/2+v;i.save(),(I||A)&&(i.beginPath(),i.arc(D,N,P,0,Math.PI*2),i.fillStyle=c(this,kr).brand,i.fill(),A?(i.clip(),i.drawImage(A,D-P,N-P,P*2,P*2),i.restore()):I&&(i.fillStyle=c(this,kr).textOnBrand,i.font=`${P/2}px sans-serif`,i.textAlign="center",i.textBaseline="middle",i.fillText(I,D,N)),this.drawIcons(n,g,v,Math.max(d,h)))}drawIcons(t,e,r,n){const i=Math.min(Math.max(n*.15,100),200),s=i*.2,a=i*.2;let o=e+s;const d=r+s,h=p=>{const m=c(this,sr).getContext("2d");m.save(),m.fillStyle=c(this,kr).background,m.beginPath(),m.moveTo(o+a,d),m.arcTo(o+i,d,o+i,d+a,a),m.arcTo(o+i,d+i,o+i-a,d+i,a),m.arcTo(o,d+i,o,d+i-a,a),m.arcTo(o,d,o+a,d,a),m.closePath(),m.fill(),typeof p=="string"?(m.font=`${i/1.5}px sans-serif`,m.fillStyle=c(this,kr).text,m.textAlign="center",m.textBaseline="top",m.fillText(p,i/2+o,d+s)):m.drawImage(p,o+s,d+s,i-s*2,i-s*2),o+=i+s,m.restore()};t.pinned&&h(c(this,Ns)),t.handRaised&&h(c(this,Ls))}drawTile(t,e,r){var n,i;if(c(this,sr)===void 0)return;const s=c(this,sr).getContext("2d"),a=this.getSources();let o=0,d=0;for(;o<c(this,Ge).height-5;){let h=0;for(;h<c(this,Ge).width-5&&d<r;){if((n=a[d])!=null&&n.enabled){const p=a[d].element,[m,g,v,I,A,P,D,N]=Iw(h,o,t,e,p.videoWidth,p.videoHeight);(i=p==null?void 0:p.classList)!=null&&i.contains("mirror")?(s.save(),s.scale(-1,1),s.drawImage(p,m,g,v,I,-1*A,P,-1*D,N),s.restore()):s.drawImage(p,m,g,v,I,A,P,D,N),this.drawIcons(a[d],A,P,Math.max(D,N))}else this.drawEmptyTile(d,t,e,a[d]);d+=1,h+=t}o+=e}}calcGridElemSize(t){switch(t){case 0:case 1:return[c(this,Ge).width,c(this,Ge).height];case 2:return[Math.floor(c(this,Ge).width/2),c(this,Ge).height];case 3:case 4:return[Math.floor(c(this,Ge).width/2),Math.floor(c(this,Ge).height/2)];case 5:case 6:return[Math.floor(c(this,Ge).width/3),Math.floor(c(this,Ge).height/2)];case 7:case 8:case 9:return[Math.floor(c(this,Ge).width/3),Math.floor(c(this,Ge).height/3)];default:return[Math.floor(c(this,Ge).width/3),Math.floor(c(this,Ge).height/2)]}}paintCanvas(){let t=this.getSources().length;t!==1&&(t=t%2>0?t+1:t);const[e,r]=this.calcGridElemSize(t);this.drawTile(e,r,t)}isSupported(){return!!window.chrome&&document.pictureInPictureEnabled}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(S(this,xs,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),c(this,Tt))try{document.body.removeChild(c(this,Tt))}catch(t){}this.removeAllSources(),S(this,sr,void 0),S(this,ar,void 0),S(this,un,void 0)}init({height:t,width:e}={}){if(c(this,xs))return;S(this,xs,!0),this.createCanvas(),this.setupMediaSessionEvents();const r=document.createElement("video");S(this,Ge,{height:t!=null?t:of,width:e!=null?e:cf}),r.height=c(this,Ge).height,r.width=c(this,Ge).width,r.autoplay=!0,r.muted=!0,r.srcObject=c(this,sr).captureStream(24),S(this,ar,r),c(this,ar).onloadedmetadata=()=>{try{this.emit("pipStarted"),c(this,ar).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch(n){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){c(this,Nt)[t]!==void 0&&(c(this,Nt)[t].enabled=!0)}disableSource(t){c(this,Nt)[t]!==void 0&&(c(this,Nt)[t].enabled=!1)}generateAvatar(t,e){return u(this,null,function*(){if(!e)return;const r=new Image;try{const n=yield fetch(e).then(s=>s.blob()),i=window.URL.createObjectURL(n);r.onload=()=>{this.updateSource(t,{image:r}),window.URL.revokeObjectURL(i)},r.src=i}catch(n){l.error("DytePip::GenerateAvatar",{error:n})}})}addSource(t,e,r,n=!1,i=void 0,s=void 0,a=!1){l.debug("DytePIP::AddSource",{pip:{id:t,handRaised:a}}),c(this,Nt)[t]={id:t,element:e,enabled:r,pinned:n,displayText:i?ww(i):void 0,imageUrl:s,handRaised:a},s&&this.generateAvatar(t,s)}updateSource(t,e){l.info("DytePIP::UpdateSource",{pip:{id:t,handRaised:e.handRaised}});const r=c(this,Nt)[t];r&&(c(this,Nt)[t]=U(U({},r),e))}removeSource(t){delete c(this,Nt)[t]}removePinnedSource(){Object.values(c(this,Nt)).forEach(t=>{t.pinned&&this.removeSource(t.id)})}removeAllSources(){S(this,Nt,{})}enable(){S(this,hn,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",c(this,Xe).videoEnabled),this.updateMediaSession("MIC",c(this,Xe).audioEnabled),document.body.appendChild(c(this,Tt)),S(this,un,requestAnimationFrame(()=>this.animate())),c(this,ar).onloadedmetadata=()=>{c(this,ar).requestPictureInPicture().then(()=>{S(this,hn,"active")})},c(this,ar).readyState===4&&c(this,ar).requestPictureInPicture().then(()=>{S(this,hn,"active")})}};let Cw=df;sr=new WeakMap,Os=new WeakMap,Tt=new WeakMap,ar=new WeakMap,Ge=new WeakMap,kr=new WeakMap,un=new WeakMap,Nt=new WeakMap,Xe=new WeakMap,Ns=new WeakMap,Ls=new WeakMap,hn=new WeakMap,xs=new WeakMap;var Ht;(function(t){t[t.PUBLISHER=0]="PUBLISHER",t[t.SUBSCRIBER=1]="SUBSCRIBER"})(Ht||(Ht={}));var Lt;(function(t){t[t.AUDIO=0]="AUDIO",t[t.VIDEO=1]="VIDEO"})(Lt||(Lt={}));class Pw extends E{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}])}}const Rw=new Pw;class Aw extends E{constructor(){super("media.HeaderExtension",[{no:1,name:"direction",kind:"scalar",opt:!0,T:9},{no:2,name:"uri",kind:"scalar",T:9}])}}const Mw=new Aw;class Dw extends E{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new Dw;class Ow extends E{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",Ht]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const or=new Ow;class Nw extends E{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:()=>or},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8}])}}const lf=new Nw;class Lw extends E{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>or},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8}])}}const _l=new Lw;class xw extends E{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>or}])}}const uf=new xw;class Fw extends E{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>or}])}}new Fw;class Vw extends E{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 Uw=new Vw;class Bw extends E{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 jw=new Bw;class Hw extends E{constructor(){super("media.ProducerEntry",[{no:1,name:"producing_transport_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9}])}}new Hw;class Ww extends E{constructor(){super("media.ConsumerEntry",[{no:1,name:"consuming_transport_id",kind:"scalar",T:9},{no:2,name:"consumer_id",kind:"scalar",T:9}])}}new Ww;class $w extends E{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",Lt]},{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}])}}const Fs=new $w;class Jw extends E{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Fs},{no:3,name:"producer_track",kind:"message",T:()=>jw}])}}const Gw=new Jw;class qw extends E{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>Gw}}])}}const hf=new qw;class zw extends E{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>ff},{no:2,name:"receiver",kind:"message",T:()=>ff}])}}const pf=new zw;class Kw extends E{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>Rw},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>Mw}])}}const mf=new Kw;class Yw extends E{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>mf},{no:2,name:"video",kind:"message",T:()=>mf}])}}const ff=new Yw;class Qw extends E{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 Xw=new Qw;class Zw extends E{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 eI=new Zw;class tI extends E{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:()=>eI},{no:9,name:"capabilities",kind:"message",T:()=>pf}])}}const gf=new tI;class rI extends E{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const vf=new rI;class nI extends E{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const yf=new nI;class iI extends E{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 iI;class sI extends E{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:()=>Xw}])}}const bl=new sI;class aI extends E{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>bl}])}}new aI;class oI extends E{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:()=>or},{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}])}}const Sf=new oI;class cI extends E{constructor(){super("media.edge.SelectedPeersRequest",[])}}new cI;class dI extends E{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Ef=new dI;class lI extends E{constructor(){super("media.edge.ProducerToggleRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const pn=new lI;class uI extends E{constructor(){super("media.edge.ConsumerToggleRequest",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const Go=new uI;class hI extends E{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>or}])}}const Tf=new hI;class pI extends E{constructor(){super("media.edge.ConsumerCloseRequest",[{no:1,name:"consumer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"description",kind:"message",T:()=>or}])}}const kf=new pI;class mI extends E{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const _f=new mI;class fI extends E{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const wl=new fI;class gI extends E{constructor(){super("media.edge.PeerDisplayNameEditRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}const bf=new gI;class vI extends E{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 wf=new vI;class yI extends E{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 If=new yI;class SI extends E{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 EI=new SI;class TI extends E{constructor(){super("media.edge.ErrorResponse",[{no:1,name:"error_message",kind:"scalar",T:9},{no:2,name:"event_id",kind:"scalar",T:5}])}}const kI=new TI;class _I extends E{constructor(){super("media.edge.EmptyResponse",[])}}new _I;class bI extends E{constructor(){super("media.edge.RoomParticipants",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"producer_states",kind:"message",repeat:1,T:()=>Fs},{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:()=>pf}])}}const Cf=new bI;class wI extends E{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 Il=new wI;class II extends E{constructor(){super("media.edge.SelectedPeersDiffEntry",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"priority",kind:"scalar",T:5}])}}const CI=new II;class PI extends E{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>CI}])}}const Pf=new PI;class RI extends E{constructor(){super("media.edge.PeerJoinResponse",[])}}new RI;class AI extends E{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>EI},{no:2,name:"participants",kind:"message",repeat:1,T:()=>Cf},{no:3,name:"selected_peers",kind:"message",T:()=>Il},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const qo=new AI;class MI extends E{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const Rf=new MI;class DI extends E{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>hf}])}}new DI;class OI extends E{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>hf},{no:3,name:"description",kind:"message",T:()=>or}])}}const Af=new OI;class NI extends E{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:()=>or}])}}const Mf=new NI;class LI extends E{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>Uw}])}}new LI;class xI extends E{constructor(){super("media.edge.ActiveSpeakerResponse",[{no:1,name:"responsepeer_id",kind:"scalar",T:9},{no:2,name:"volume",kind:"scalar",T:5}])}}new xI;class FI extends E{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new FI;class VI extends E{constructor(){super("media.edge.ProducerToggleResponse",[])}}new VI;class UI extends E{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new UI;class BI extends E{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>or}])}}const Df=new BI;class jI extends E{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>or}])}}new jI;class HI extends E{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new HI;class WI extends E{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Of=new WI;class $I extends E{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Nf=new $I;class JI extends E{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Lf=new JI;class GI extends E{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const xf=new GI;class qI extends E{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Ff=new qI;class zI extends E{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>Cf}])}}const Vf=new zI;class KI extends E{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const Uf=new KI;class YI extends E{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>Uf},{no:3,name:"screenshare",kind:"message",T:()=>Uf}])}}const QI=new YI;class XI extends E{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>_l},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>QI}])}}new XI;class ZI extends E{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Fs}])}}const Bf=new ZI;class eC extends E{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Fs},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const Cl=new eC;class tC extends E{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Fs}])}}const jf=new tC;class rC extends E{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const zo=new rC;class nC extends E{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Hf=new nC;class iC extends E{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new iC;class sC extends E{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new sC;class aC extends E{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new aC;class oC extends E{constructor(){super("media.edge.PeerDisplayNameEditBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}new oC;class cC extends E{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new cC;class dC extends E{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new dC;class lC extends E{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 Pl=new lC;class uC extends E{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 uC;class hC extends E{constructor(){super("socket.api.ErrorMessage",[{no:1,name:"code",kind:"scalar",opt:!0,T:5},{no:2,name:"message",kind:"scalar",T:9}])}}const pC=new hC;var zn;(function(t){t[t.BROWSER=0]="BROWSER",t[t.TRACK=1]="TRACK",t[t.COMPOSITE=2]="COMPOSITE"})(zn||(zn={}));var Dr;(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"})(Dr||(Dr={}));var Rl;(function(t){t[t.NONE=0]="NONE",t[t.RECORDER=1]="RECORDER",t[t.LIVESTREAMER=2]="LIVESTREAMER"})(Rl||(Rl={}));var Al;(function(t){t[t.PEERS=0]="PEERS",t[t.ROOMS=1]="ROOMS"})(Al||(Al={}));var Ko;(function(t){t[t.HIVE=0]="HIVE",t[t.CHAT=1]="CHAT",t[t.PING=2]="PING"})(Ko||(Ko={}));class mC extends E{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 fC=new mC;class gC extends E{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",Dr,"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:()=>fC}])}}const Yo=new gC;class vC extends E{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>Yo}])}}const Fi=new vC;class yC extends E{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",Dr,"STAGE_TYPE_"]}])}}const Wf=new yC;class SC extends E{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 EC=new SC;class TC extends E{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>Yo}])}}const Ml=new TC;class kC extends E{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const $f=new kC;class _C extends E{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:()=>wC},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const Jf=new _C;class bC extends E{constructor(){super("socket.room.ActiveRecording",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",zn]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const wC=new bC;class IC extends E{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>Jf}])}}const Gf=new IC;class CC extends E{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const qf=new CC;class PC extends E{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 PC;class RC extends E{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Yo},{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",Ko,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const AC=new RC;class MC extends E{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Yo},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const DC=new MC;class OC extends E{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>Jf}])}}new OC;class NC extends E{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new NC;class LC extends E{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 Dl=new LC;class xC extends E{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 FC=new xC;class VC extends E{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:()=>FC}])}}const zf=new VC;class UC extends E{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>zf},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>zf}])}}const BC=new UC;class jC extends E{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const HC=new jC;class WC extends E{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>HC}])}}const $C=new WC;class JC extends E{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:()=>Dl}])}}const GC=new JC;class qC extends E{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>GC}])}}const Kf=new qC;class zC extends E{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 KC=new zC;class YC extends E{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>KC}])}}new YC;class QC extends E{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const XC=new QC;class ZC extends E{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>XC}])}}const eP=new ZC;class tP extends E{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>iP}])}}const rP=new tP;class nP extends E{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:()=>Dl}])}}const iP=new nP;class sP extends E{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 aP=new sP;class oP extends E{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:()=>aP}])}}const cP=new oP;class dP extends E{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:()=>Dl}])}}const Yf=new dP;class lP extends E{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Yf}])}}new lP;class uP extends E{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 hP=new uP;class pP extends E{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>gP}])}}const mP=new pP;class fP extends E{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 gP=new fP;class vP extends E{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const yP=new vP;class SP extends E{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",Al,"BROADCAST_TYPE_"]}])}}const Vs=new SP;class EP extends E{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const TP=new EP;class kP extends E{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const _P=new kP;class bP extends E{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 wP=new bP;class IP extends E{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>wP}])}}const Qf=new IP;class CP extends E{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 Xf=new CP;var Ol;(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"})(Ol||(Ol={}));var mn;(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"})(mn||(mn={}));class PP extends E{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 RP=new PP;class AP extends E{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 MP=new AP;class DP extends E{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 OP=new DP;class NP extends E{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 LP=new NP;class xP extends E{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>OP},{no:2,name:"private",kind:"message",T:()=>LP}])}}const FP=new xP;class VP extends E{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 UP=new VP;class BP extends E{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",mn,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",mn,"STREAM_PERMISSION_TYPE_"]}])}}const Nl=new BP;class jP extends E{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>Nl},{no:2,name:"audio",kind:"message",T:()=>Nl},{no:3,name:"screenshare",kind:"message",T:()=>Nl}])}}const HP=new jP;class WP extends E{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>RP},{no:2,name:"plugins",kind:"message",T:()=>MP},{no:3,name:"chat",kind:"message",T:()=>FP},{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",Ol,"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",Rl,"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:()=>UP},{no:23,name:"media",kind:"message",T:()=>HP}])}}const Ll=new WP;class $P extends E{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const JP=new $P;class GP extends E{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 qP=new GP;class zP extends E{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>qP}])}}const KP=new zP;class YP extends E{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>Ll}])}}const Zf=new YP;class QP extends E{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>Zf}])}}const XP=new QP;class ZP extends E{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>Zf}])}}const eg=new ZP;class eR extends E{constructor(){super("socket.preset.PeerUserIDMap",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9}])}}const tR=new eR;class rR extends E{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>tR},{no:2,name:"patch",kind:"message",T:()=>Ll}])}}new rR;class nR extends E{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>Ll}])}}new nR;class iR extends E{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 Kn=new iR;class sR extends E{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 aR=new sR;class oR extends E{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Kn},{no:2,name:"next",kind:"scalar",T:8}])}}const cR=new oR;class dR extends E{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Kn}])}}const tg=new dR;class lR extends E{constructor(){super("socket.chat.SendChatMessageToRoomRequest",[{no:1,name:"payload_type",kind:"scalar",T:5},{no:2,name:"payload",kind:"scalar",T:9}])}}const uR=new lR;class hR extends E{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>Kn}])}}const xl=new hR;class pR extends E{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 mR=new pR;class fR extends E{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>Kn}])}}const Fl=new fR;class gR extends E{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 vR=new gR;class yR extends E{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>Kn}])}}new yR;class SR extends E{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 ER=new SR;class TR extends E{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 kR=new TR;class _R extends E{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 Qo=new _R;class bR extends E{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>Kn}])}}const Xo=new bR;class wR extends E{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 IR=new wR;class CR extends E{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 Zo=new CR;class PR extends E{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 RR=new PR;class AR extends E{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 MR=new AR;class DR extends E{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}const OR=new DR;class NR extends E{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 LR=new NR;class xR extends E{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 FR=new xR;class VR extends E{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new VR;class UR extends E{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}const BR=new UR;class jR extends E{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>Kn},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const HR=new jR;class WR extends E{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:()=>HR},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const $R=new WR;class JR extends E{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>$R}])}}const Or=new JR;class GR extends E{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 qR=new GR;class zR extends E{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>qR}])}}const KR=new zR;class YR extends E{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const QR=new YR;class XR extends E{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const ZR=new XR;class eA extends E{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const tA=new eA;class rA extends E{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const nA=new rA;class iA extends E{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 sA=new iA;class aA extends E{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 oA=new aA;class cA extends E{constructor(){super("socket.plugin.PluginEventToRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const dA=new cA;class lA extends E{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 uA=new lA;class hA extends E{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 Vl=new hA;class pA extends E{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:()=>Vl}])}}const rg=new pA;class mA extends E{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:()=>Vl}])}}const fA=new mA;class gA extends E{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:()=>Vl}])}}const vA=new gA;class yA extends E{constructor(){super("socket.plugin.PluginStoreDeleteRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9}])}}const SA=new yA;class EA extends E{constructor(){super("socket.plugin.EnablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"enabled_by",kind:"scalar",T:9}])}}const Ul=new EA;class TA extends E{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>Ul}])}}const kA=new TA;class _A extends E{constructor(){super("socket.plugin.DisablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"disabled_by",kind:"scalar",T:9}])}}const ng=new _A;class bA extends E{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 wA=new bA;class IA extends E{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:()=>wA}])}}const ig=new IA;class CA extends E{constructor(){super("socket.plugin.PluginEventResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const sg=new CA;class PA extends E{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 ag=new PA;class RA extends E{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const og=new RA;class AA extends E{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 MA=new AA;class DA extends E{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>MA}])}}const Bl=new DA;class OA extends E{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const NA=new OA;class LA extends E{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const xA=new LA;class FA extends E{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const cg=new FA;class VA extends E{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:()=>BA},{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 dg=new VA;class UA extends E{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:()=>HA}])}}const BA=new UA;class jA extends E{constructor(){super("socket.polls.PollVote",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])}}const HA=new jA;class WA extends E{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 $A=new WA;class JA extends E{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 GA=new JA;class qA extends E{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>dg}])}}const jl=new qA;class zA extends E{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>dg}])}}const KA=new zA;class YA extends E{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",zn]}])}}const lg=new YA;class QA extends E{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(),r=Date.now();return e.seconds=Ie.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}toDate(e){return new Date(Ie.from(e.seconds).toNumber()*1e3+Math.ceil(e.nanos/1e6))}fromDate(e){const r=this.create(),n=e.getTime();return r.seconds=Ie.from(Math.floor(n/1e3)).toBigInt(),r.nanos=n%1e3*1e6,r}internalJsonWrite(e,r){let n=Ie.from(e.seconds).toNumber()*1e3;if(n<Date.parse("0001-01-01T00:00:00Z")||n>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 i="Z";if(e.nanos>0){let s=(e.nanos+1e9).toString().substring(1);s.substring(3)==="000000"?i="."+s.substring(0,3)+"Z":s.substring(6)==="000"?i="."+s.substring(0,6)+"Z":i="."+s+"Z"}return new Date(n).toISOString().replace(".000Z",i)}internalJsonRead(e,r,n){if(typeof e!="string")throw new Error("Unable to parse Timestamp from JSON "+_d(e)+".");let i=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(!i)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let s=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(s))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(s<Date.parse("0001-01-01T00:00:00Z")||s>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 n||(n=this.create()),n.seconds=Ie.from(s/1e3).toBigInt(),n.nanos=0,i[7]&&(n.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),n}}new QA;const XA=0,ZA=1,eM=2,tM=3,rM=4,nM=5,iM={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},sM={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,sendMessageToChannel:6,searchChannelMessages:7,getAllChatChannels:8,markChannelIndexAsRead:9,pinMessage:10},aM={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},oM={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},ug={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},cM={createChatChannel:0,getChatChannel:1,deprecatedGetAllChatChannels:2,getChannelMembers:3,updateChatChannel:4},dM={getUserPresets:0,updateUserPreset:1};function Vi(t,e){return Object.keys(e).reduce((r,n)=>(r[n]=(t<<16)+e[n],r),{})}function hg(t,e){return Object.keys(t).reduce((r,n)=>(r[n]=e|t[n],r),{})}const j=Vi(XA,iM),xe=Vi(ZA,sM),z=Vi(eM,aM),Nr=Vi(tM,oM),Yn=Vi(rM,cM),oe=hg(ug,16777216),ce=hg(ug,50331648),ec=Vi(nM,dM);var lM=Object.defineProperty,uM=Object.getOwnPropertyDescriptor,Hl=(t,e,r,n)=>{for(var i=n>1?void 0:n?uM(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&lM(e,r,i),i},Qn,pg;const Wl=(pg=class{constructor(t){T(this,Qn,void 0),S(this,Qn,t)}createChannel(t,e,r,n="public",i=!1){return u(this,null,function*(){const s={displayName:t,targetUserIds:e,displayPictureUrl:r,visibility:n,isDirectMessage:i};i&&(s.visibility="private");const a=yield c(this,Qn).sendMessagePromise(Yn.createChatChannel,LR.toBinary(s)),o=Or.fromBinary(a.payload).chatChannels;return Wl.formatChannel(o[0])})}updateChannel(t,e){return u(this,null,function*(){const r=yield c(this,Qn).sendMessagePromise(Yn.updateChatChannel,FR.toBinary({chatChannelId:t,targetUserIds:e.memberIds,displayName:e.displayName,displayPictureUrl:e.displayPictureUrl,visibility:e.visibility})),n=Or.fromBinary(r.payload).chatChannels;return Wl.formatChannel(n[0])})}static formatChannel(t){var e;const{latestMessageAndUnreadCount:r}=t,n=X(U({},t),{id:t.chatChannelId,memberIds:t.targetUserIds,unreadCount:(e=r==null?void 0:r.unreadCount)!=null?e:0});return r!=null&&r.message&&(n.latestMessage=xr.formatSocketServiceMessage(r.message)),delete n.chatChannelId,delete n.targetUserIds,delete n.latestMessageAndUnreadCount,n}getChannelMembers(t){return u(this,null,function*(){try{const e=yield c(this,Qn).sendMessagePromise(Yn.getChannelMembers,BR.toBinary({chatChannelId:t}));return KR.fromBinary(e.payload).channelMembers.map(r=>{var n=r,{id:i}=n,s=po(n,["id"]);return X(U({},s),{userId:i})})}catch(e){return[]}})}on(t,e){let r,n;switch(t){case Yn.createChatChannel:{r=Or.fromBinary.bind(Or),n=Or.create();break}case Yn.updateChatChannel:{r=Or.fromBinary.bind(Or),n=Or.create();break}}if(!r){l.warn(`ChatChannelSocketHandler::Event ${t} is not recognized`);return}c(this,Qn).on(t,({payload:i})=>{let s=n;try{s=r(i)}catch(a){l.error("ChatChannelSocketHandler::on::binary_decode_error",{error:a})}return e(s)})}},Qn=new WeakMap,pg);let Xn=Wl;Hl([y.trace("ChatChannelHandler.createChannel")],Xn.prototype,"createChannel",1),Hl([y.trace("ChatChannelHandler.updateChannel")],Xn.prototype,"updateChannel",1),Hl([y.trace("ChatChannelHandler.getChannelMembers")],Xn.prototype,"getChannelMembers",1);var hM=Object.defineProperty,pM=Object.getOwnPropertyDescriptor,cr=(t,e,r,n)=>{for(var i=n>1?void 0:n?pM(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&hM(e,r,i),i},kt=(t=>(t[t.TEXT=0]="TEXT",t[t.IMAGE=1]="IMAGE",t[t.FILE=2]="FILE",t[t.CUSTOM=3]="CUSTOM",t))(kt||{}),_t;class Xt{constructor(e){T(this,_t,void 0),S(this,_t,e)}getChatMessages(){return c(this,_t).sendMessagePromise(xe.getMessages)}getChatMessagesPaginated(e,r,n,i=0,s=""){return u(this,null,function*(){const a={timeStamp:e,size:r,from:i,reversed:n,channelId:s},o=yield c(this,_t).sendMessagePromise(xe.getPaginatedMessages,aR.toBinary(a));return o.payload?cR.fromBinary(o.payload):{messages:[],next:!1}})}sendMessageToRoom(e,r){const n={payloadType:r,payload:e};c(this,_t).sendMessage(xe.sendMessageToRoom,uR.toBinary(n))}sendMessageToPeers(e,r,n){const i={payloadType:r,peerIds:n,payload:e};c(this,_t).sendMessage(xe.sendMessageToPeers,mR.toBinary(i))}sendMessageToChannel(e,r,n){const i={payloadType:r,channelId:n,payload:e};c(this,_t).sendMessage(xe.sendMessageToChannel,vR.toBinary(i))}sendMessage(e,r,n,i){if(i&&this.sendMessageToChannel(e,r,i),n&&n.length>0){this.sendMessageToPeers(e,r,n);return}this.sendMessageToRoom(e,r)}editMessage(e,r,n,i,s){return u(this,null,function*(){const a={chatId:e,payloadType:n,payload:r};i&&(a.channelId=i),s!==void 0&&(a.pinned=s);const o=yield c(this,_t).sendMessagePromise(xe.editMessage,ER.toBinary(a));return Xo.fromBinary(o.payload).message})}deleteMessage(e,r){return u(this,null,function*(){const n={chatId:e};r&&(n.channelId=r);const i=yield c(this,_t).sendMessagePromise(xe.deleteMessage,IR.toBinary(n)),s=Zo.fromBinary(i.payload);return U({id:s.chatId},s.channelId?{channelId:s.channelId}:{})})}searchMessages(e,r){return u(this,null,function*(){var n,i,s;const a={searchTerm:e,timeStamp:(n=r.timestamp)!=null?n:Date.now(),size:(i=r.size)!=null?i:75,from:0,reversed:(s=r.reversed)!=null?s:!0};r.channelId&&(a.channelId=r.channelId);try{const o=yield c(this,_t).sendMessagePromise(xe.searchChannelMessages,RR.toBinary(a));return tg.fromBinary(o.payload).messages}catch(o){return[]}})}getAllChannels(){return u(this,null,function*(){try{const e=yield c(this,_t).sendMessagePromise(xe.getAllChatChannels);return Or.fromBinary(e.payload).chatChannels.map(Xn.formatChannel)}catch(e){return[]}})}markLastReadMessage(e,r){return u(this,null,function*(){const n=yield c(this,_t).sendMessagePromise(xe.markChannelIndexAsRead,MR.toBinary({channelId:e,userId:r.userId,channelIndex:r.channelIndex}));return OR.fromBinary(n.payload).channelIndex})}setPinState(e,r){return u(this,null,function*(){const n={chatId:e.id,pinned:r,channelId:e.channelId},i=yield c(this,_t).sendMessagePromise(xe.pinMessage,kR.toBinary(n));return Qo.fromBinary(i.payload)})}on(e,r){let n,i;switch(e){case xe.sendMessageToRoom:{n=xl.fromBinary.bind(xl),i=xl.create();break}case xe.sendMessageToPeers:{n=Fl.fromBinary.bind(Fl),i=Fl.create();break}case xe.editMessage:{n=Xo.fromBinary.bind(Xo),i=Xo.create();break}case xe.pinMessage:{n=Qo.fromBinary.bind(Qo),i=Qo.create();break}case xe.deleteMessage:{n=Zo.fromBinary.bind(Zo),i=Zo.create();break}}if(!n){l.warn(`ChatSocketHandler::Event ${e} is not recognized`);return}c(this,_t).on(e,({payload:s})=>{let a=i;try{a=n(s)}catch(o){l.error("chatSocketHandler::on::binary_decode_error",{error:o})}return r(a)})}}_t=new WeakMap,cr([y.trace("SocketService.getChatMessages")],Xt.prototype,"getChatMessages",1),cr([y.trace("SocketService.getChatMessagesPaginated")],Xt.prototype,"getChatMessagesPaginated",1),cr([y.trace("SocketService.sendMessageToRoom")],Xt.prototype,"sendMessageToRoom",1),cr([y.trace("SocketService.sendMessageToPeers")],Xt.prototype,"sendMessageToPeers",1),cr([y.trace("SocketService.sendMessageToChannel")],Xt.prototype,"sendMessageToChannel",1),cr([y.trace("SocketService.sendMessage")],Xt.prototype,"sendMessage",1),cr([y.trace("SocketService.editMessage")],Xt.prototype,"editMessage",1),cr([y.trace("SocketService.deleteMessage")],Xt.prototype,"deleteMessage",1),cr([y.trace("SocketService.searchMessages")],Xt.prototype,"searchMessages",1),cr([y.trace("SocketService.getAllChannels")],Xt.prototype,"getAllChannels",1),cr([y.trace("SocketService.markLastReadMessage")],Xt.prototype,"markLastReadMessage",1);function mM(t){return t.replace(/([-_]\w)/g,e=>e[1].toUpperCase())}function dr(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>dr(r));const e={};return Object.keys(t).forEach(r=>{const n=Td(r)?r:mM(r);e[n]=dr(t[r])}),e}function fM(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function mg(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>mg(r));const e={};return Object.keys(t).forEach(r=>{const n=Td(r)?r:fM(r);e[n]=t[r]}),e}function tc(t,e={}){return t==null?{}:(Object.getOwnPropertyNames(t).forEach(r=>{if(typeof t[r]!="function"){if(typeof t[r]=="object"){tc(t[r],e[r]={});return}e[r]=t[r]}}),e)}const gM=3,vM=30,yM=8e3;class SM{constructor(e,r){f(this,"ipInfo"),f(this,"axios"),f(this,"requests"),f(this,"roomName"),f(this,"roomUUID"),f(this,"authToken"),f(this,"organizationId"),f(this,"iceServers"),f(this,"pluginInformation"),f(this,"userDetails"),f(this,"roomDetails"),f(this,"context"),this.context=e;const{timeout:n=yM,retry:i=gM,retryDelay:s=vM,baseURL:a="https://api.cluster.dyte.in",authToken:o,cachedUserDetails:d}=r||{};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=Ro.create({baseURL:a,responseType:"json",timeout:n,retry:i,retryDelay:s}),this.axios=Ro,this.setAuthToken(o,{bearer:!0}),this.requests.interceptors.request.use(h=>(y.injectContext(this.requests.defaults.headers.common),h),h=>u(this,null,function*(){l.error("xhr::axios",{debuggingHint:"otelRequestInterceptor failed.",error:h})})),this.requests.interceptors.response.use(h=>{try{h.config.url!==y.logsEndpoint&&l.debug("xhr::axios",{networkCall:{status:h.status,statusText:h.statusText,baseURL:h.config.baseURL,url:h.config.url,method:h.config.method}})}catch(p){console.error("xhr::dyte",{error:"responseInterceptorFailed",err:p,response:h})}return h},h=>u(this,null,function*(){var p;try{if(!h)return Promise.reject(new _("Unknown network error occurred","0011"));h&&h.config&&((p=h.config)==null?void 0:p.url)!==y.logsEndpoint&&l.error("xhr::axios",{error:h,networkCall:{status:h.status,statusText:h.statusText,baseURL:h.config.baseURL,url:h.config.url,retries:h.config.retry,method:h.config.method,isOnline:navigator.onLine?"online":"offline"}});const{config:m,message:g}=h;return m&&g&&m.retry!==void 0&&m.retry>0&&(g.includes("timeout")||g.includes("Network Error"))?(m.retry-=1,this.requests(m)):Promise.reject(new _(g,"0011"))}catch(m){return console.error("xhr::dyte",{error:"responseInterceptorFailed",err:m,responseError:h}),Promise.reject(new _(m.message,"0011"))}}))}get peerId(){return this.context.getValue("peerId")}setAuthToken(e,r){const{bearer:n}=r||{};this.authToken=e,this.requests.defaults.headers.common.Authorization=n?`Bearer ${e}`:e}setHeader(e,r){this.requests.defaults.headers.common[e]=r}setRoomName(e){this.roomName=e}setRoomUUID(e){this.roomUUID=e}setOrganizationId(e){this.organizationId=e}}var EM=Object.defineProperty,TM=Object.getOwnPropertyDescriptor,$l=(t,e,r,n)=>{for(var i=n>1?void 0:n?TM(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&EM(e,r,i),i};class rc extends SM{constructor(e,r){super(e,r),this.setHeader("x-dyte-web-core-version",e.getValue("sdkVersion"))}getIPDetails(){return u(this,null,function*(){var e;const{peerId:r}=this;try{const n=yield Ld.getIPDetails({peerId:r,apiHostnames:nf(this.context),logger:l});if(l.log("ipInfo",{ipInfo:n}),((e=n==null?void 0:n.loc)==null?void 0:e.length)>5)return n;throw Error("Insufficient data")}catch(n){l.warn("ApiClient.getRoomNodeLinkAndTitleV1 Failed to get ip details",{error:{name:n.name,message:n.message}});return}})}getICEServers(){return u(this,null,function*(){if(this.iceServers)return this.iceServers;const{success:e,iceServers:r}=(yield this.requests.get("/iceservers")).data;if(e)return(r==null?void 0:r.length)>0&&(this.iceServers=r),r})}getPlugins(){return u(this,null,function*(){var e,r,n,i,s,a,o;if(this.pluginInformation)return this.pluginInformation;const{plugins:d}=(yield this.requests.get("/v2/plugins/user")).data.data,h=((r=(e=Q.getValue(ie.V1_PLUGINS))==null?void 0:e.toString())==null?void 0:r.split(","))||[],p=d.reduce((m,g)=>(m[h.includes(g.id)?"v1":"v2"].push(X(U({},g),{name:g.name.replace("v2","")})),m),{v1:[],v2:[]});return(s=(i=(n=this.context.getValue("modules"))==null?void 0:n.devTools)==null?void 0:i.plugins)!=null&&s.length&&((o=(a=this.context.getValue("modules"))==null?void 0:a.devTools)==null||o.plugins.forEach(m=>{var g,v,I;const A=X(U({},Ds),{tags:[...Ds.tags],baseUrl:`http://localhost:${m.port}`,name:m.name,picture:(g=m.picture)!=null?g:Ds.picture,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),id:m.id,organizationId:this.organizationId,description:(v=m.description)!=null?v:Ds.description,staggered:(I=m.staggered)!=null?I:Ds.staggered});p.v2.push(A)})),p.v2})}getPluginDetails(e){return u(this,null,function*(){const{plugin:r}=(yield this.requests.get(`/v2/plugins/view/${e}`)).data.data;return r})}getPluginConfig(e){return u(this,null,function*(){return(yield this.axios.get(`${e}/dyte-config.json`)).data})}authorizePlugin(e){return u(this,null,function*(){const r={peerId:this.peerId},{token:n}=(yield this.requests.post(`/v2/plugins/authorize/${e}`,r)).data.data;return n})}getPresignedUrls(e,r){return u(this,null,function*(){const n=Ho(this.context,"chat_upload_expiry"),i={roomUUID:this.roomUUID,filename:e,expiry:typeof n=="number"?n:void 0};Q.hasFeature(ie.FEAT_CHAT_SDK)&&(i.viewType=r);const{getLocation:s,putLocation:a}=(yield this.requests.post("/v1/meetings/genPreSignedUploadUrl",i)).data.data;return{getLocation:s,putLocation:a}})}uploadFile(e,r){return u(this,null,function*(){if(navigator.isReactNative&&"uri"in e)try{yield fetch(r,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:{uri:e.uri,name:e.name}})}catch(n){l.error(`sendFileMessage::${n}`)}else yield this.axios.put(r,e,{headers:{"Content-Type":e.type}})})}}$l([y.trace("APIClient.getIPDetails")],rc.prototype,"getIPDetails",1),$l([y.trace("APIClient.getICEServers")],rc.prototype,"getICEServers",1),$l([y.trace("APIClient.getPlugins")],rc.prototype,"getPlugins",1);var kM=Object.defineProperty,_M=Object.getOwnPropertyDescriptor,Lr=(t,e,r,n)=>{for(var i=n>1?void 0:n?_M(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&kM(e,r,i),i};class _r extends rc{startLivestreaming(e){return u(this,arguments,function*({manualIngestion:r}){const n=dr(yield this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/livestreams`,{manual_ingest:!!r})).data.data;return{playbackUrl:n.playbackUrl,status:n.status,manualIngest:n.manualIngest,ingestionCredentials:n.streamKey?{ingestionServer:n.ingestServer,streamKey:n.streamKey}:null}})}stopLivestreaming(){return u(this,null,function*(){return this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream/stop`)})}getActiveLivestream(){return u(this,null,function*(){const e=dr((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 u(this,null,function*(){if(this.userDetails)return this.userDetails;const e=(yield this.requests.get("v2/internals/participant-details")).data.data;return dr(e)})}startRecording(e,r){return u(this,null,function*(){return(yield this.requests.post("/v2/recordings",X(U({},mg(e)),{meeting_id:this.context.getValue("meetingId"),allow_multiple_recordings:!!r}))).data.data.id})}updateRecording(e,r){return u(this,null,function*(){return this.requests.put(`v2/recordings/${e}`,{action:r})})}getActiveRecording(){return u(this,null,function*(){const{status:e,id:r}=(yield this.requests.get(`v2/recordings/active-recording/${this.context.getValue("meetingId")}`)).data.data;return{status:e,id:r}})}getActiveTranscript(){return u(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.axios.get(e)).data}}catch(r){throw new _("Cant fetch transcript s3 url","1801")}})}getRoomNodeData(){return u(this,null,function*(){const e=yield this.getIPDetails();if(this.ipInfo=e,this.roomDetails)return this.roomDetails;const{roomNodeLink:r,title:n,useHiveMedia:i,sfu:s}=dr((yield this.requests.post("v2/internals/rooms",{ip_information:e})).data.data);return{roomNodeUrl:r,meetingTitle:n,useHiveMedia:i!=null?i:!1,sfu:s}})}}Lr([y.trace("APIClient.startLivestreaming")],_r.prototype,"startLivestreaming",1),Lr([y.trace("APIClient.stopLivestreaming")],_r.prototype,"stopLivestreaming",1),Lr([y.trace("APIClient.getActiveLivestream")],_r.prototype,"getActiveLivestream",1),Lr([y.trace("APIClient.getUserDetails")],_r.prototype,"getUserDetails",1),Lr([y.trace("APIClient.startRecording")],_r.prototype,"startRecording",1),Lr([y.trace("APIClient.stopRecording")],_r.prototype,"updateRecording",1),Lr([y.trace("APIClient.getActiveRecording")],_r.prototype,"getActiveRecording",1),Lr([y.trace("APIClient.getActiveTranscript")],_r.prototype,"getActiveTranscript",1),Lr([y.trace("APIClient.getRoomNodeData")],_r.prototype,"getRoomNodeData",1);let Jl;function bM(t,e){return Jl=new _r(t,e),Jl}function qe(){return Jl}function wM(t,e){return`<blockquote>${e.replace(/<blockquote>[.\s\S]*<\/blockquote>\n\n/m,"")}</blockquote>
16
16
 
17
- ${t}`}function Ct(t){return function(e,r,n){const i=n.value;let s=0,o=Date.now();return n.value=function(...a){const d=Date.now();if(d-o>t.period*1e3&&(o=d,s=0),s>=t.maxInvocations)throw new C(`Method rate limit ${t.maxInvocations} invocations/${t.period}sec exceeded`);return s+=1,i.apply(this,a)},n}}var BP=Object.defineProperty,jP=Object.getOwnPropertyDescriptor,lt=(t,e,r,n)=>{for(var i=n>1?void 0:n?jP(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&BP(e,r,i),i};const HP=["text","image","file","custom","poll"],Sa={maxInvocations:180,period:60};var re,Ri,qe,Pi,Ta,al,kf,_f;let Ze=(_f=class extends Dt{constructor(t,e,r,n,i){super(),_(this,al),m(this,"messages"),m(this,"channels",[]),_(this,re,void 0),_(this,Ri,void 0),_(this,qe,void 0),_(this,Pi,void 0),_(this,Ta,void 0),m(this,"maxTextLimit",2e3),T(this,Ta,t),T(this,qe,e),T(this,Pi,r),T(this,re,n),T(this,Ri,i),this.messages=[]}setMaxTextLimit(t){this.maxTextLimit=t}get roomJoined(){var t;return((t=c(this,al,kf))==null?void 0:t.roomJoined)===!0}sendMessageInternal(t,e,r){return u(this,arguments,function*(n,i,s,o={}){switch(n.type){case"text":{const a=o.replyTo&&o.replyTo.type==="text"?VP(n.message,o.replyTo.message):n.message;yield this.sendTextMessageInternal(a,i,s);break}case"image":yield this.sendImageMessageInternal(n.image,i,s);break;case"file":yield this.sendFileMessageInternal(n.file,i,s);break;default:l.error("sendMessage::message_type_not_supported",{dyteChat:{messageType:n.type}});break}})}sendTextMessageInternal(t,e,r){return u(this,null,function*(){var n,i,s,o,a,d;if(t.length>this.maxTextLimit)throw new C("Max character limit breached");if(e&&e.length>0){if(!((n=c(this,re).permissions)!=null&&n.chatPrivate.canSend)||!((i=c(this,re).permissions)!=null&&i.chatPrivate.text))throw l.error("sendTextMessage::private_chat_permission_denied"),new C("Could not send message to private chat.","0501")}else if(!((o=(s=c(this,re).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(a=c(this,re).permissions)==null?void 0:a.chatPublic)!=null&&d.text))throw l.error("sendTextMessage::public_chat_permission_denied"),new C("Could not send message to public chat.","0501");if(!t)throw l.error("sendTextMessage::message_can_not_be_empty"),new C("Message can not be empty.","0502");if(r){c(this,qe).sendMessageToChannel(t,mt.TEXT,r);return}let h=[];e&&e.length>0&&(e.push(c(this,re).id),h=c(this,Ri).joined.toArray().filter(p=>e.includes(p.id)).map(p=>p.userId),h.push(c(this,re).userId)),c(this,qe).sendMessage(t,mt.TEXT,e)})}sendImageMessageInternal(t,e,r){return u(this,null,function*(){var n,i,s,o,a,d;if(e&&e.length>0){if(!((n=c(this,re).permissions)!=null&&n.chatPrivate.canSend)||!((i=c(this,re).permissions)!=null&&i.chatPrivate.files)){l.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((o=(s=c(this,re).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(a=c(this,re).permissions)==null?void 0:a.chatPublic)!=null&&d.files)){l.error("sendImageMessage::permission_denied");return}if(!t){l.error("sendImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(t.type)){l.error("sendImageMessage::image_type_not_supported",{dyteChat:{imageType:t.type}});return}try{const h=je(),{getLocation:p,putLocation:f}=yield h.getPresignedUrls(t.name,c(this,re).config.viewType);if(yield h.uploadFile(t,f),r){c(this,qe).sendMessageToChannel(p,mt.IMAGE,r);return}let g=[];e&&e.length>0&&(e.push(c(this,re).id),g=c(this,Ri).joined.toArray().filter(E=>e.includes(E.id)).map(E=>E.userId),g.push(c(this,re).userId)),c(this,qe).sendMessage(p,mt.IMAGE,e)}catch(h){throw new C("Error sending image message.")}})}sendFileMessageInternal(t,e,r){return u(this,null,function*(){var n,i,s,o,a,d;if(e&&e.length>0){if(!((n=c(this,re).permissions)!=null&&n.chatPrivate.canSend)||!((i=c(this,re).permissions)!=null&&i.chatPrivate.files)){l.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((o=(s=c(this,re).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(a=c(this,re).permissions)==null?void 0:a.chatPublic)!=null&&d.files)){l.error("sendFileMessage::permission_denied");return}if(!t){l.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const h=je(),{getLocation:p,putLocation:f}=yield h.getPresignedUrls(t.name,c(this,re).config.viewType);if(yield h.uploadFile(t,f),r){c(this,qe).sendMessageToChannel(JSON.stringify({link:p,name:t.name,size:"size"in t?t.size:0}),mt.FILE,r);return}let g=[];e&&e.length>0&&(e.push(c(this,re).id),g=c(this,Ri).joined.toArray().filter(v=>e.includes(v.id)).map(v=>v.userId),g.push(c(this,re).userId));const E=JSON.stringify({link:p,name:t.name,size:"size"in t?t.size:0});c(this,qe).sendMessage(E,mt.FILE,e)}catch(h){throw new C("Error sending file message.")}})}get rateLimits(){return Sa}updateRateLimits(t,e){Sa.maxInvocations=t,Sa.period=e}sendTextMessage(t,e){return u(this,null,function*(){return this.sendTextMessageInternal(t,e)})}sendCustomMessage(t,e){return u(this,null,function*(){var r,n,i,s,o,a,d,h,p,f,g,E,v,R,A;if(e&&e.length>0){if(!((r=c(this,re).permissions)!=null&&r.chatPrivate.canSend)||!((n=c(this,re).permissions)!=null&&n.chatPrivate.files)||!((i=c(this,re).permissions)!=null&&i.chatPrivate.text)){l.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((o=(s=c(this,re).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(a=c(this,re).permissions)==null?void 0:a.chatPublic)!=null&&d.files)||!((p=(h=c(this,re).permissions)==null?void 0:h.chatPublic)!=null&&p.text)){l.error("sendCustomMessage::permission_denied");return}const L=W=>u(this,null,function*(){try{if(typeof W=="string")return{link:W};const H=je(),{getLocation:I,putLocation:S}=yield H.getPresignedUrls(W.name,c(this,re).config.viewType);return yield H.uploadFile(W,S),{link:I,type:W.type,name:W.name,size:W.size}}catch(H){throw new C("Error sending image message.")}}),F=ne(V({},t),{files:yield Promise.all((g=(f=t.files)!=null?f:[])==null?void 0:g.map(W=>u(this,null,function*(){return L(W)}))),images:yield Promise.all((v=(E=t.images)!=null?E:[])==null?void 0:v.map(W=>u(this,null,function*(){return L(W)}))),videos:yield Promise.all((A=(R=t.videos)!=null?R:[])==null?void 0:A.map(W=>u(this,null,function*(){return L(W)})))});c(this,qe).sendMessage(JSON.stringify(F),mt.CUSTOM,e)})}sendImageMessage(t,e){return u(this,null,function*(){return this.sendImageMessageInternal(t,e)})}sendFileMessage(t,e){return u(this,null,function*(){return this.sendFileMessageInternal(t,e)})}sendMessage(t,e){return u(this,null,function*(){return this.sendMessageInternal(t,e)})}editTextMessage(t,e,r){return u(this,null,function*(){var n,i,s,o,a,d;if(((i=(n=c(this,re).permissions)==null?void 0:n.chatMessage)==null?void 0:i.canEdit)==="NONE")throw new C("Not permitted to edit messages","0501");if(!((o=(s=c(this,re).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(a=c(this,re).permissions)==null?void 0:a.chatPublic)!=null&&d.text)){l.error("editTextMessage::permission_denied");return}if(!e){l.error("editTextMessage::message_can_not_be_empty");return}c(this,qe).editMessage(t,e,mt.TEXT,r)})}editImageMessage(t,e,r){return u(this,null,function*(){var n,i,s,o;if(!((i=(n=c(this,re).permissions)==null?void 0:n.chatPublic)!=null&&i.canSend)||!((o=(s=c(this,re).permissions)==null?void 0:s.chatPublic)!=null&&o.files)){l.error("editImageMessage::permission_denied");return}if(!e){l.error("editImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(e.type)){l.error("sendImageMessage::image_type_not_supported",{dyteChat:{imageType:e.type}});return}try{const a=je(),{getLocation:d,putLocation:h}=yield a.getPresignedUrls(e.name,c(this,re).config.viewType);yield a.uploadFile(e,h),c(this,qe).editMessage(t,d,mt.IMAGE,r)}catch(a){throw new C("Error editing image message.")}})}editFileMessage(t,e,r){return u(this,null,function*(){var n,i,s,o;if(!((i=(n=c(this,re).permissions)==null?void 0:n.chatPublic)!=null&&i.canSend)||!((o=(s=c(this,re).permissions)==null?void 0:s.chatPublic)!=null&&o.files)){l.error("sendFileMessage::permission_denied");return}if(!e){l.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const a=je(),{getLocation:d,putLocation:h}=yield a.getPresignedUrls(e.name,c(this,re).config.viewType);yield a.uploadFile(e,h),c(this,qe).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),mt.FILE,r)}catch(a){throw new C("Error editing file message.")}})}editMessage(t,e,r){return u(this,null,function*(){switch(e.type){case"text":{this.editTextMessage(t,e.message,r);break}case"image":{this.editImageMessage(t,e.image,r);break}case"file":{this.editFileMessage(t,e.file,r);break}default:{l.error("editMessage::message_type_not_supported",{dyteChat:{messageType:e.type}});break}}})}deleteMessage(t,e){return u(this,null,function*(){var r,n;if(((n=(r=c(this,re).permissions)==null?void 0:r.chatMessage)==null?void 0:n.canDelete)==="NONE")throw new C("Not permitted to delete messages","0501");c(this,qe).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 u(this,null,function*(){if(!this.roomJoined)throw new C("Can`t pin message without joining room");if(!c(this,re).permissions.pinParticipant)throw new C("You do not have permission to pin messages.");const e=this.messages.find(r=>r.id===t);if(e){c(this,qe).setPinState(e,!0);return}throw new C(`No message found with id: ${t}`)})}unpin(t){return u(this,null,function*(){if(!this.roomJoined)throw new C("Can`t unpin message without joining room");if(!c(this,re).permissions.pinParticipant)throw new C("You do not have permission to unpin messages.");const e=this.messages.find(r=>r.id===t);if(e){c(this,qe).setPinState(e,!1);return}throw new C(`No message found with id: ${t}`)})}getMessages(t,e,r,n=0,i=void 0){return u(this,null,function*(){const s=yield c(this,qe).getChatMessagesPaginated(t,e,r,n,i);return{messages:s.messages.map(o=>wr.formatSocketServiceMessage(o)),next:s.next}})}createChannel(t,e){return u(this,arguments,function*(r,n,i={}){var s;const o=(s=c(this,re).permissions)==null?void 0:s.chatChannel;if(o){if(o.canCreate==="NONE")throw new C("Not permitted to create channels","0501");if(i.visibility==="public"&&!(o.canCreate==="PUBLIC"||o.canCreate==="ALL"))throw new C("Not permitted to create public channels","0501");if(i.visibility==="private"&&!(o.canCreate==="PRIVATE"||o.canCreate==="ALL"))throw new C("Not permitted to create private channels","0501")}if(!r||r.trim().length===0)throw new C("channel name cannot be empty.","0510");const a=[...new Set([...n,c(this,re).userId])];return yield c(this,Pi).createChannel(r.trim(),a,i.displayPictureUrl,i.visibility,i.isDirectMessage)})}updateChannel(t,e){var r,n,i,s,o;const a=this.channels.find(p=>p.id===t),d=(r=c(this,re).permissions)==null?void 0:r.chatChannel;if(d){if(d.canUpdate==="NONE")throw new C("Not permitted to update channels","0501");if(a.visibility==="public"&&!(d.canUpdate==="PUBLIC"||d.canUpdate==="ALL"))throw new C("Not permitted to update public channels","0501");if(a.visibility==="private"&&!(d.canUpdate==="PRIVATE"||d.canUpdate==="ALL"))throw new C("Not permitted to update private channels","0501")}const h={memberIds:(n=e.memberIds)!=null?n:a.memberIds,displayName:(i=e.displayName)!=null?i:a.displayName,displayPictureUrl:(s=e.displayPictureUrl)!=null?s:a.displayPictureUrl,visibility:(o=e.visibility)!=null?o:a.visibility};return c(this,Pi).updateChannel(t,h)}sendMessageToChannel(t,e){return u(this,arguments,function*(r,n,i={}){return this.sendMessageInternal(r,null,n,i)})}getChannelMembers(t){return u(this,null,function*(){return c(this,Pi).getChannelMembers(t)})}searchMessages(t){return u(this,arguments,function*(e,r={}){if(!K.hasFeature(X.FEAT_CHAT_SDK_SEARCH))throw new C("searchMessages is temporarily disabled!");return(yield c(this,qe).searchMessages(e,r)).map(wr.formatSocketServiceMessage)})}markLastReadMessage(t,e){return u(this,null,function*(){yield c(this,qe).markLastReadMessage(t,e);const r=this.channels.find(n=>n.id===t);if(r){const n=ne(V({},r),{unreadCount:0});this.channels=this.channels.map(i=>i.id===t?n:i),this.emit("channelMessageUpdate",n)}})}get pinned(){return this.messages.filter(t=>t.pinned)}},re=new WeakMap,Ri=new WeakMap,qe=new WeakMap,Pi=new WeakMap,Ta=new WeakMap,al=new WeakSet,kf=function(){return c(this,Ta).getValue("roomNodeClient")},_f);lt([y.trace("DyteChat.sendTextMessage"),Ct(Sa)],Ze.prototype,"sendTextMessage",1),lt([y.trace("DyteChat.sendImageMessage"),Ct({maxInvocations:20,period:60})],Ze.prototype,"sendImageMessage",1),lt([y.trace("DyteChat.sendFileMessage"),Ct({maxInvocations:20,period:60})],Ze.prototype,"sendFileMessage",1),lt([y.trace("DyteChat.sendMessage"),Ct({maxInvocations:180,period:60})],Ze.prototype,"sendMessage",1),lt([y.trace("DyteChat.editTextMessage")],Ze.prototype,"editTextMessage",1),lt([y.trace("DyteChat.editImageMessage")],Ze.prototype,"editImageMessage",1),lt([y.trace("DyteChat.editFileMessage")],Ze.prototype,"editFileMessage",1),lt([y.trace("DyteChat.editMessage")],Ze.prototype,"editMessage",1),lt([y.trace("DyteChat.deleteMessage")],Ze.prototype,"deleteMessage",1),lt([y.trace("DyteChat.createChannel")],Ze.prototype,"createChannel",1),lt([y.trace("DyteChat.updateChannel")],Ze.prototype,"updateChannel",1),lt([y.trace("DyteChat.sendMessageToChannel")],Ze.prototype,"sendMessageToChannel",1),lt([y.trace("DyteChat.getChannelMembers")],Ze.prototype,"getChannelMembers",1),lt([y.trace("DyteChat.searchMessages")],Ze.prototype,"searchMessages",1),lt([y.trace("DyteChat.markLastReadMessage")],Ze.prototype,"markLastReadMessage",1),Ze=lt([dt("0500")],Ze);var w=(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.REFRESH_GRID="hive/refresh-grid",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_ALL="MUTE_ALL",t.MUTE_ALL_VIDEO="MUTE_ALL_VIDEO",t))(w||{}),WP=Object.defineProperty,$P=Object.getOwnPropertyDescriptor,GP=(t,e,r,n)=>{for(var i=n>1?void 0:n?$P(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&WP(e,r,i),i},cl,bf;const Rn=(bf=class{constructor(t,e,r,n,i){m(this,"chat"),m(this,"chatSocketHandler"),m(this,"chatChannelSocketHandler"),m(this,"self"),_(this,cl,void 0),T(this,cl,t),this.chatSocketHandler=e,this.chatChannelSocketHandler=r,this.chat=new Ze(t,e,r,n,i),this.self=n,this.setupEvents()}static init(t,e,r,n,i){return u(this,null,function*(){return new Rn(t,e,r,n,i)})}static formatMessage(t){return ne(V({},t),{time:new Date(t.time),type:HP[t.type]})}static formatSocketServiceMessage(t){const e=t.createdAt*1e3,r={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(r.type){case mt.TEXT:{r.message=t.payload;break}case mt.IMAGE:{r.link=t.payload;break}case mt.FILE:{const{link:n,name:i,size:s}=JSON.parse(t.payload);r.link=n,r.name=i,r.size=s;break}case mt.CUSTOM:{const{html:n,images:i,message:s,videos:o,files:a}=JSON.parse(t.payload);r.message=s,r.html=n,r.images=i,r.videos=o,r.files=a;break}}return Rn.formatMessage(r)}getChatMessages(){return u(this,null,function*(){if(this.self.config.viewType==="LIVESTREAM"||this.self.config.viewType==="CHAT"||K.hasFeature(X.FEAT_PAGINATED_CHAT))return;const t=yield this.chatSocketHandler.getChatMessages();if(!(t!=null&&t.payload))return;const e=cf.fromBinary(t.payload).messages;this.chat.messages=e.map(r=>Rn.formatSocketServiceMessage(r))})}setupEvents(){b.on(w.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){this.getChatMessages()})),this.chatSocketHandler.on(De.sendMessageToRoom,t=>{const e=Rn.formatSocketServiceMessage(t.message);if(!e.channelId)this.chat.messages=[...this.chat.messages,e];else{const r=this.chat.channels.find(n=>n.id===e.channelId);r&&(r.latestMessage=e,r.unreadCount+=1,this.chat.emit("channelMessageUpdate",r))}this.chat.emit("chatUpdate",{action:"add",message:e,messages:this.chat.messages})}),this.chatSocketHandler.on(De.sendMessageToPeers,t=>{const e=Rn.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(De.editMessage,t=>{const e=Rn.formatSocketServiceMessage(t.message);if(e.channelId){this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages});return}const r=this.chat.messages.findIndex(n=>n.id===e.id);r!==-1&&(this.chat.messages[r]=e,this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages}))}),this.chatSocketHandler.on(De.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(n=>n.id===t.chatId);if(e===-1)return;const[r]=this.chat.messages.splice(e,1);this.chat.emit("chatUpdate",{action:"delete",message:r,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(wn.createChatChannel,t=>{const[e]=t.chatChannels,r=In.formatChannel(e);this.chat.channels.push(r),this.chat.emit("channelCreate",r)}),this.chatSocketHandler.on(De.pinMessage,t=>{const e=this.chat.messages.findIndex(n=>n.id===t.chatId);if(e===-1)return;const r=this.chat.messages[e];r.pinned=t.pinned,this.chat.messages[e]=r,this.chat.emit("chatUpdate",{action:"edit",message:r,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(wn.updateChatChannel,t=>{const[e]=t.chatChannels,r=In.formatChannel(e);this.chat.channels=this.chat.channels.map(n=>n.id===r.id?r:n),this.chat.emit("channelUpdate",r)})}},cl=new WeakMap,bf);let wr=Rn;GP([y.trace("ChatController.setupEvents")],wr.prototype,"setupEvents",1);var JP=Object.defineProperty,qP=Object.getOwnPropertyDescriptor,KP=(t,e,r,n)=>{for(var i=n>1?void 0:n?qP(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&JP(e,r,i),i},dl,wf,Ai,_s,ka,Cf;let ll=(Cf=class extends Dt{constructor(t,e,r){super(),_(this,dl),m(this,"items"),_(this,Ai,void 0),_(this,_s,void 0),_(this,ka,void 0),T(this,ka,t),T(this,Ai,e),T(this,_s,r),this.items=[]}get roomJoined(){var t;return((t=c(this,dl,wf))==null?void 0:t.roomJoined)===!0}create(t,e,r=!1,n=!1){return u(this,null,function*(){if(c(this,Ai).config.viewType!=="LIVESTREAM"&&!this.roomJoined)throw new C("Can't create polls without joining room");if(!c(this,Ai).permissions.polls.canCreate){l.error("DytePolls::create::permission_denied");return}if(!t||!e){l.error("DytePolls::question_and_options_can_not_be_empty",{dytePolls:{hasQuestion:!!t,optionsLength:e==null?void 0:e.length}});return}if(e.length<2){l.error("DytePolls::there_must_be_at_least_two_options",{dytePolls:{hasQuestion:!!t,optionsLength:e.length}});return}yield c(this,_s).createPoll(t,e,r,n)})}vote(t,e){return u(this,null,function*(){if(!c(this,Ai).permissions.polls.canVote){l.error("DytePolls::vote::permission_denied");return}yield c(this,_s).votePoll(t,e)})}},dl=new WeakSet,wf=function(){return c(this,ka).getValue("roomNodeClient")},Ai=new WeakMap,_s=new WeakMap,ka=new WeakMap,Cf);ll=KP([dt("0700")],ll);var zP=Object.defineProperty,YP=Object.getOwnPropertyDescriptor,QP=(t,e,r,n)=>{for(var i=n>1?void 0:n?YP(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&zP(e,r,i),i},_a,Pn,If;const Mi=(If=class{constructor(t,e,r){m(this,"polls"),_(this,_a,void 0),_(this,Pn,void 0),this.polls=new ll(t,e,r),T(this,_a,e),T(this,Pn,r),this.setupEvents()}static init(t,e,r){return u(this,null,function*(){return new Mi(t,e,r)})}canViewPolls(){return c(this,_a).permissions.polls.canView}setupEvents(){b.on(w.UPDATE_PERMISSIONS,t=>{t.polls&&(t.polls.canView?this.getPolls():this.polls.items=[])}),this.canViewPolls()&&(b.on(w.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),c(this,Pn).on(_r.createPoll,t=>{t.poll&&this.updatePoll(Mi.formatSocketServicePoll(t.poll))}),c(this,Pn).on(_r.updatePoll,t=>{t.poll&&this.updatePoll(Mi.formatSocketServicePoll(t.poll))}),c(this,Pn).on(_r.votePoll,t=>{t.poll&&this.updatePoll(Mi.formatSocketServicePoll(t.poll))}))}updatePoll(t){if(!this.canViewPolls())return;const e=this.polls.items.findIndex(r=>r.id===t.id);if(e>-1){const r=JSON.stringify(this.polls.items[e]);this.polls.items[e]=t,r!==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 u(this,null,function*(){const t=yield c(this,Pn).getPolls();if(!(t!=null&&t.payload))return;const{polls:e}=dP.fromBinary(t.payload);this.polls.items=e.map(r=>Mi.formatSocketServicePoll(r))})}static formatSocketServicePoll(t){const e=t.options.map(r=>({count:r.count,text:r.text,votes:r.votes.map(n=>({id:n.userId,name:n.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}}},_a=new WeakMap,Pn=new WeakMap,If);let Rf=Mi;QP([y.trace("PollController.setupEvents")],Rf.prototype,"setupEvents",1);var XP=Object.defineProperty,ZP=Object.getOwnPropertyDescriptor,eA=(t,e,r,n)=>{for(var i=n>1?void 0:n?ZP(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&XP(e,r,i),i},Pf=(t=>(t[t.User=0]="User",t[t.Meeting=1]="Meeting",t))(Pf||{}),ba,bs,wa,Di,Ca,Af;let ul=(Af=class extends Dt{constructor(t,e,r,n,i){super(),_(this,bs),m(this,"selfActiveTab"),m(this,"broadcastTabChanges"),_(this,ba,void 0),_(this,Di,void 0),_(this,Ca,void 0),m(this,"viewType"),m(this,"meetingStartedTimestamp"),m(this,"meetingTitle"),m(this,"sessionId"),T(this,ba,t),T(this,Di,e),this.viewType=r,T(this,Ca,n),this.meetingTitle=i,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){var t;return(t=c(this,bs,wa))==null?void 0:t.socketState}get mediaState(){var t;return(t=c(this,bs,wa))==null?void 0:t.mediaState}get meetingId(){var t;return(t=c(this,bs,wa))==null?void 0:t.roomName}setBroadcastTabChanges(t){if(!c(this,Di).permissions.canSpotlight)throw l.error("DyteSpotlight::setSpotlighted::permission_denied"),new C("User does not have permission to toggle spotlight");this.broadcastTabChanges=t,this.emit("broadcastTabChangesUpdate",this.broadcastTabChanges),this.broadcastTabChanges&&this.assertActiveTabToRoom()}setSelfActiveTab(t,e){var r;l.info("DyteSpotlight::setActiveTab",{spotlight:{currentTab:{id:t.id,type:t.type}}}),this.selfActiveTab=t,e===0&&this.emit("selfTabUpdate",t),(r=c(this,Di).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){c(this,Ca).broadcastMessage("spotlight",{userId:c(this,Di).userId,currentTab:this.selfActiveTab})}},ba=new WeakMap,bs=new WeakSet,wa=function(){return c(this,ba).getValue("roomNodeClient")},Di=new WeakMap,Ca=new WeakMap,Af);ul=eA([dt("0800")],ul);function tA(t){let e="",r=[""];const n=[r];let i=0,s=0,o=!0,a;for(a of t)a==='"'?(o&&a===e&&(r[i]+=a),o=!o):a===","&&o?a=r[++i]="":a===`
18
- `&&o?(e==="\r"&&(r[i]=r[i].slice(0,-1)),r=n[++s]=[a=""],i=0):r[i]+=a,e=a;return n}var rA=Object.defineProperty,nA=Object.getOwnPropertyDescriptor,Mf=(t,e,r,n)=>{for(var i=n>1?void 0:n?nA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&rA(e,r,i),i};let Gr=class extends Dt{constructor(){super(),m(this,"transcripts"),this.transcripts=[]}static init(t){return u(this,null,function*(){const e=new Gr;try{t&&e.getActiveTranscript()}catch(r){l.error("Error fetching active transcriptions ",r)}return e})}static parseTranscript(t,e=!1){try{if(!t)return;const[[r,n,i,s,o,a]]=tA(t);return{id:gn(),name:o,peerId:n,userId:i,customParticipantId:s,transcript:a,isPartialTranscript:e,date:new Date(parseInt(r,10)*1e3)}}catch(r){l.error(`Failed to parse transcript: ${t}`,r);return}}static parseTranscripts(t){return t?t.split(`
19
- `).map(e=>Gr.parseTranscript(e,!1)).filter(Boolean):[]}getActiveTranscript(){return u(this,null,function*(){try{const t=je(),{transcript:e}=yield t.getActiveTranscript();this.transcripts=Gr.parseTranscripts(e)}catch(t){}})}onTranscript(t){return u(this,null,function*(){var e;const r=this.transcripts.filter(({peerId:n})=>n===t.peerId);if((e=r==null?void 0:r.at(-1))!=null&&e.isPartialTranscript){const n=r.at(-1);n.transcript=t.transcript,n.isPartialTranscript=t.isPartialTranscript,this.emit("transcript",n);return}this.transcripts.push(t),this.emit("transcript",t)})}};Mf([y.trace("DyteAi.getActiveTranscript")],Gr.prototype,"getActiveTranscript",1),Gr=Mf([dt("0000")],Gr);var iA=Object.defineProperty,sA=Object.getOwnPropertyDescriptor,oA=(t,e,r,n)=>{for(var i=n>1?void 0:n?sA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&iA(e,r,i),i},An,ws,hl,Df;const Of=(Df=class{constructor(t,e,r,n,i,s){m(this,"meta"),m(this,"ai"),_(this,An,void 0),_(this,ws,void 0),m(this,"aiSocketHandler"),_(this,hl,void 0),T(this,hl,t),this.meta=new ul(t,e,e.config.viewType,r,s),this.ai=n,T(this,An,e),T(this,ws,r),this.aiSocketHandler=i,e.config.viewType!==We.Chat&&this.setupEvents()}static init(t,e,r,n,i){return u(this,null,function*(){const s=yield Gr.init(e.permissions.transcriptionEnabled);return new Of(t,e,r,s,n,i)})}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,Pf.Meeting),this.meta.emit("activeTabUpdate",t.currentTab))}setupEvents(){b.on(w.TRANSPORT_STATE_UPDATE,t=>{this.meta.emit("mediaConnectionUpdate",t)}),b.on(w.SOCKET_STATE_UPDATE,t=>{this.meta.emit("socketConnectionUpdate",t)}),b.on(w.ROOM_STATE,({createdAt:t,roomUuid:e})=>{const r=this.meta.meetingStartedTimestamp;if(e&&(this.meta.sessionId=e),t&&!r){const n=new Date(t*1e3);this.meta.meetingStartedTimestamp=n,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),b.on(w.PRODUCER_SCORE_UPDATE,({score:t})=>{t<5&&this.meta.emit("poorConnection",{score:t})}),c(this,An).permissions.canSpotlight&&(l.info("DyteMetaController::Asserting Spotlight"),this.meta.selfActiveTab&&c(this,ws).broadcastMessage("spotlight",{userId:c(this,An).userId,currentTab:this.meta.selfActiveTab})),b.on(w.PEER_JOINED_INTERNAL,t=>u(this,null,function*(){c(this,An).permissions.canSpotlight&&this.meta.selfActiveTab&&c(this,ws).broadcastToPeers("spotlight",[t.id],{userId:c(this,An).userId,currentTab:this.meta.selfActiveTab})})),b.on(w.ROOM_MESSAGE,t=>{var e,r;let n;if("type"in t){if(t.type!=="spotlight")return;n=V(V({},t),t.payload)}else if("roomMessageType"in t){if(t.roomMessageType!=="spotlight")return;n=t}else return;l.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:n.userId},currentTab:{id:(e=n.currentTab)==null?void 0:e.id,type:(r=n.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(n)}),b.on(w.MESSAGE,t=>{var e,r;let n;if("type"in t){if(t.type!=="spotlight")return;n=V(V({},t),t.payload)}else if("roomMessageType"in t){if(t.roomMessageType!=="spotlight")return;n=t}else return;l.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:n.userId},currentTab:{id:(e=n.currentTab)==null?void 0:e.id,type:(r=n.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(n)}),this.aiSocketHandler.on(j.transcript,t=>{const{meetingId:e,transcript:r,isPartial:n}=t,i=Gr.parseTranscript(r,n);if(!i){l.warn("Received empty transcript data");return}this.ai.onTranscript(i),this.meta.emit("transcript",i);const{peerId:s,name:o,transcript:a}=i;l.debug(`${e} Received transcript for peer ${s} - ${o}: ${a}`)})}},An=new WeakMap,ws=new WeakMap,hl=new WeakMap,Df);let Nf=Of;oA([y.trace("MetaController.setupEvents")],Nf.prototype,"setupEvents",1);var aA=Object.defineProperty,cA=Object.getOwnPropertyDescriptor,Mn=(t,e,r,n)=>{for(var i=n>1?void 0:n?cA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&aA(e,r,i),i},ur,Cs,xe,Ia,Dn,hr,Is,Ra;class Jr extends Dt{constructor(e,r,n,i,s){super(),_(this,Is),_(this,ur,void 0),_(this,Cs,void 0),_(this,xe,void 0),_(this,Ia,void 0),_(this,Dn,void 0),_(this,hr,void 0),T(this,hr,e),T(this,ur,i),T(this,Cs,s),T(this,xe,r),T(this,Ia,n),T(this,Dn,[]),this.setupEvents()}get status(){return c(this,hr).getValue("stageStatus")}setupEvents(){b.onAsync(w.GET_STAGE_REQUESTS,e=>u(this,null,function*(){T(this,Dn,e)})),b.onAsync(w.UPDATE_STAGE_REQUESTS,e=>u(this,[e],function*({add:r}){const n=c(this,Ia).joined.toArray().filter(i=>i.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(i=>({displayName:i.name,userId:i.userId,peerId:i.id}));(r||n.length>c(this,Dn).length)&&this.emit("newStageRequest",{count:n.length}),T(this,Dn,n),this.emit("stageAccessRequestUpdate",n)}))}getAccessRequests(){if(!c(this,xe).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new C("Stage is disabled");if(!c(this,xe).permissions.acceptStageRequests)throw l.error("DyteStage::get_access_request::permission_denied"),new C("You do not have permission to perform this action/");return{stageRequests:c(this,Dn)}}requestAccess(){return u(this,null,function*(){if(!c(this,xe).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new C("Stage is disabled");if(this.status!=="OFF_STAGE")throw new C(`Unable to request access you are currently ${this.status}`);if(c(this,xe).permissions.stageAccess===q.Allowed){ue(this,Is,Ra).call(this,"ACCEPTED_TO_JOIN_STAGE");return}c(this,ur).requestAccess(),ue(this,Is,Ra).call(this,"REQUESTED_TO_JOIN_STAGE")})}cancelRequestAccess(){return u(this,null,function*(){if(!c(this,xe).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new C("Stage is disabled");c(this,ur).cancelRequestAccess(),ue(this,Is,Ra).call(this,"OFF_STAGE")})}grantAccess(e){if(!c(this,xe).roomJoined)throw new C("Can`t rejectRequestToJoinStage for participant without joining room");if(!c(this,xe).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new C("Stage is disabled");if(!c(this,xe).permissions.acceptStageRequests)throw l.error("DyteStage::grant_access::permission_denied"),new C("You do not have permission to perform this action/");return c(this,ur).grantAccess(e)}denyAccess(e){if(!c(this,xe).roomJoined)throw new C("Can`t rejectRequestToJoinStage for participant without joining room");if(!c(this,xe).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new C("Stage is disabled");if(!c(this,xe).permissions.acceptStageRequests)throw l.error("DyteStage::deny_access::permission_denied"),new C("You do not have permission to perform this action/");return c(this,ur).denyAccess(e)}join(){return u(this,null,function*(){const e=c(this,hr).getValue("viewType");if(this.status==="ON_STAGE")throw new C("You are already on stage.");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||c(this,xe).permissions.stageAccess===q.NotAllowed)throw new C(`Unable to join stage you are currently ${this.status}`);if(yield c(this,ur).joinStage(),e===We.Livestream){const{name:r,id:n,userId:i}=c(this,xe);yield c(this,Cs).joinRoom(r,n,i,e)}if(c(this,hr).setValue("stageStatus","ON_STAGE",!1),yield b.emitAsync(w.JOIN_MEDIA_ROOM),c(this,hr).notify("stageStatus"),e===We.Livestream){const{peers:r}=yield c(this,Cs).getStagePeers();b.emit(w.SOCKET_PEERS,r)}})}leave(){return u(this,null,function*(){if(!c(this,xe).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new C("Stage is disabled");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new C(`Unable to leave stage you are currently ${this.status}`);c(this,xe).setIsPinned(!1),yield c(this,ur).leaveStage(c(this,xe).userId),c(this,hr).setValue("stageStatus","OFF_STAGE",!1),yield b.emitAsync(w.LEAVE_MEDIA_ROOM,"stageLeft"),c(this,hr).notify("stageStatus")})}kick(e){return u(this,null,function*(){if(!c(this,xe).roomJoined)throw new C("Can`t kick participant without joining room");if(!c(this,xe).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new C("Stage is disabled");if(!c(this,xe).permissions.acceptStageRequests)throw l.error("DyteStage::kick::permission_denied"),new C("You do not have permissions for kick");return c(this,ur).kick(e)})}}ur=new WeakMap,Cs=new WeakMap,xe=new WeakMap,Ia=new WeakMap,Dn=new WeakMap,hr=new WeakMap,Is=new WeakSet,Ra=function(t){return u(this,null,function*(){this.status!==t&&c(this,hr).setValue("stageStatus",t)})},Mn([y.trace("DyteStage.getStageRequests")],Jr.prototype,"getAccessRequests",1),Mn([y.trace("DyteStage.requestAccess")],Jr.prototype,"requestAccess",1),Mn([y.trace("DyteStage.cancelRequestAccess")],Jr.prototype,"cancelRequestAccess",1),Mn([y.trace("DyteStage.grantAccess")],Jr.prototype,"grantAccess",1),Mn([y.trace("DyteStage.denyAccess")],Jr.prototype,"denyAccess",1),Mn([y.trace("DyteStage.joinStage")],Jr.prototype,"join",1),Mn([y.trace("DyteStage.leaveStage")],Jr.prototype,"leave",1);function dA(t){return!(t.viewType==="LIVESTREAM"||t.viewType==="CHAT")}function Pa(t){switch(t){case Tr.UNSPECIFIED:return"OFF_STAGE";case Tr.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case Tr.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case Tr.OFF_STAGE:return"OFF_STAGE";case Tr.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var lA=Object.defineProperty,uA=Object.getOwnPropertyDescriptor,hA=(t,e,r,n)=>{for(var i=n>1?void 0:n?uA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&lA(e,r,i),i},On,Oi,Nn,Aa,qr;class Lf{constructor(e,r,n,i,s){m(this,"stage"),_(this,On,void 0),_(this,Oi,void 0),_(this,Nn,void 0),_(this,Aa,0),_(this,qr,void 0),T(this,qr,e),this.stage=new Jr(e,i,s,r,n),T(this,Nn,r),T(this,On,i),T(this,Oi,s),this.setupEvents()}setupEvents(){c(this,qr).subscribe("stageStatus",e=>{this.stage.emit("stageStatusUpdate",e)}),c(this,Nn).on(j.grantStageAccess,()=>{c(this,On).permissions.stageAccess!==q.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),c(this,Nn).on(j.peerStageStatusUpdate,e=>{e!==void 0&&(e.peerId===c(this,On).id?this.selfStageStatusHandler(e):this.peerStageStatusHandler(e))}),c(this,Nn).on(j.denyStageAccess,()=>{c(this,On).permissions.stageAccess!==q.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),c(this,Nn).on(j.getStageRequests,e=>u(this,null,function*(){var r;if(c(this,On).permissions.stageAccess!==q.Allowed)return;const n=(r=e==null?void 0:e.stageRequests)!=null?r:[];yield b.emitAsync(w.GET_STAGE_REQUESTS,n),c(this,Aa)<n.length&&n.length>0&&this.stage.emit("newStageRequest",{count:n.length}),T(this,Aa,n.length),this.stage.emit("stageAccessRequestUpdate",n)}))}getCurrentStageRequests(){return c(this,Oi).joined.toArray().filter(e=>e.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(e=>({displayName:e.name,userId:e.userId,peerId:e.id}))}setStageStatus(e){return u(this,null,function*(){this.stage.status!==e&&c(this,qr).setValue("stageStatus",e)})}selfStageStatusHandler(e){const r=Pa(e.stageType),n=c(this,qr).getValue("stageStatus");if(n!==r)switch(e.stageType){case 1:c(this,qr).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(n);break;case 0:case 4:default:c(this,qr).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}peerStageStatusHandler(e){return u(this,null,function*(){const r=c(this,Oi).joined.get(e.peerId),n=c(this,Oi).viewMode==="ACTIVE_GRID";if(!r){l.warn("err::peerStageStatusUpdate: participant not found");return}switch(e.stageType){case 1:r.setStageStatus("ON_STAGE"),n&&b.emit(w.REFRESH_GRID);break;case 2:r.setStageStatus("ACCEPTED_TO_JOIN_STAGE");break;case 3:r.setStageStatus("REQUESTED_TO_JOIN_STAGE");break;case 0:case 4:default:r.setStageStatus("OFF_STAGE"),n&&b.emit(w.REFRESH_GRID);break}b.emit(w.UPDATE_PEER_STAGE_STATUS,{id:r.id,status:r.stageStatus})})}}On=new WeakMap,Oi=new WeakMap,Nn=new WeakMap,Aa=new WeakMap,qr=new WeakMap,hA([y.trace("DyteStage.setupEvents")],Lf.prototype,"setupEvents",1);var pA=Object.defineProperty,mA=Object.getOwnPropertyDescriptor,Ma=(t,e,r,n)=>{for(var i=n>1?void 0:n?mA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&pA(e,r,i),i};const Fe={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 gt,Yt,Rs,Ps,Kr,As,Ms,Ni,Ds,xf;let Li=(xf=class extends Ci{constructor(t,{baseURL:e,createdAt:r,description:n,id:i,name:s,organizationId:o,picture:a,private:d,published:h,staggered:p,tags:f,type:g,updatedAt:E},v,R,A,L){super(),_(this,Ni),_(this,gt,void 0),m(this,"baseURL"),m(this,"createdAt"),m(this,"description"),m(this,"id"),m(this,"name"),_(this,Yt,void 0),_(this,Rs,void 0),_(this,Ps,void 0),m(this,"organizationId"),m(this,"picture"),m(this,"private"),m(this,"published"),m(this,"staggered"),m(this,"tags"),m(this,"type"),m(this,"updatedAt"),_(this,Kr,void 0),m(this,"config"),_(this,As,void 0),m(this,"active"),m(this,"iframes"),m(this,"enabledBy"),_(this,Ms,void 0),T(this,Ms,t),this.baseURL=e,this.createdAt=new Date(r),this.description=n,this.id=i,this.name=s,T(this,Yt,R),this.organizationId=o,this.picture=a,this.private=d,this.published=h,this.staggered=p,this.tags=f,this.type=g,this.updatedAt=new Date(E),this.active=!1,this.iframes=new Map,T(this,gt,v),T(this,Rs,A),T(this,Ps,L),this.enabledBy=""}sendIframeEvent(t){this.iframes.size&&this.iframes.forEach(e=>{const{iframe:r}=e;r&&(navigator.isReactNative?r.postMessage(JSON.stringify(t)):r.contentWindow.postMessage(t,"*"))})}handleIframeMessage(t){return u(this,null,function*(){var e;if(!this.active)return;const r=t,{payload:n,uuid:i,type:s}=r;switch(s){case J.customPluginEventToRoom:{c(this,gt).customPluginEventToRoom(this.id,n,i);break}case J.customPluginEventToPeers:{c(this,gt).customPluginEventToPeers(this.id,n.peerIds,n,i);break}case J.enablePluginForRoom:{c(this,gt).enablePluginForRoom(this.id,i);break}case J.enablePluginForPeers:{c(this,gt).enablePluginForPeers(this.id,n.peerIds,i);break}case J.disablePluginForRoom:{c(this,gt).disablePluginForRoom(this.id,i);break}case J.disablePluginForPeers:{c(this,gt).disablePluginForPeers(this.id,n.peerIds,i);break}case J.storeInsertKeys:{c(this,gt).storeInsertKeys(this.id,n.store,n.insertKeys,i);break}case J.storeGetKeys:{c(this,gt).storeGetKeys(this.id,n.store,n.getKeys,i);break}case J.storeDeleteKeys:{c(this,gt).storeDeleteKeys(this.id,n.store,n.deleteKeys,i);break}case J.storeDelete:{c(this,gt).storeDelete(this.id,n.store,i);break}case Fe.chatMessage:{const{messagePayload:o,peerIds:a}=n;if(!c(this,Ps)){this.sendIframeEvent({type:Fe.chatMessage,uuid:r.uuid,payload:{error:"Chat is disabled for this room."}});return}try{yield c(this,Ps).sendMessage(o,a),this.sendIframeEvent({type:Fe.chatMessage,uuid:r.uuid,payload:{success:!0}})}catch(d){this.sendIframeEvent({type:Fe.chatMessage,uuid:r.uuid,payload:{error:d}})}break}case Fe.getPeer:{let o;const{peerId:a}=n,d=ne(V({},c(this,Yt)),{isRecorder:(e=c(this,Yt).permissions)==null?void 0:e.isRecorder,isHidden:c(this,Yt).permissions.hiddenParticipant,stageStatus:c(this,Yt).stageStatus});a?(o=c(this,Rs).joined.get(n.peerId),c(this,Yt).id===a&&(o=d)):o=d,this.sendIframeEvent({type:Fe.getPeer,payload:{peer:o&&ya(o)},uuid:r.uuid});break}case Fe.getPeers:{const o=c(this,Rs).joined.toArray().map(a=>ya(a));this.sendIframeEvent({type:Fe.getPeers,payload:{peers:o},uuid:r.uuid});break}case Fe.getPluginInitiator:{this.sendIframeEvent({type:Fe.getPluginInitiator,payload:{enabledBy:this.enabledBy},uuid:r.uuid});break}case Fe.getDisplayTitle:{this.sendIframeEvent({type:Fe.getDisplayTitle,payload:{displayTitle:c(this,Ni,Ds).meetingTitle},uuid:r.uuid});break}case Fe.getRoomName:{this.sendIframeEvent({type:Fe.getRoomName,payload:{roomName:c(this,Ni,Ds).roomName},uuid:r.uuid});break}case Fe.customPluginEventToParent:{this.emit(r.payload.eventName,r.payload.data);break}}})}sendData(t){this.active&&(l.info("DytePlugin::SendData",{plugin:{id:this.id,name:this.name,data:{eventName:t.eventName}}}),this.sendIframeEvent({type:Fe.sendData,uuid:"",payload:t}))}removePluginView(t="default"){var e;const{iframe:r,listener:n}=(e=this.iframes.get(t))!=null?e:{};(r||n)&&(navigator.isReactNative?r.props.onMessage=void 0:window.removeEventListener("message",n),this.iframes.delete(t))}addPluginView(t,e="default"){var r;if(!c(this,As))throw l.error("DytePlugin::addPluginView::no_auth_token_set_for_plugin"),new C("No auth token set for plugin.");if(!t)throw l.error("DytePlugin::addPluginView::iframe_was_not_provided"),new C("Iframe was not provided.");this.removePluginView(e);const n=t,i=new URL(this.baseURL),s={auth:c(this,As),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:c(this,Ms).getValue("apiBase"),pluginId:this.id,roomName:(r=c(this,Ni,Ds).roomName)!=null?r:"",displayTitle:c(this,Ni,Ds).meetingTitle};if(Object.keys(s).forEach(o=>{i.searchParams.set(o,s[o])}),n.src=i.href,n.allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",n.title=e,navigator.isReactNative)n.props.onMessage=o=>{this.handleIframeMessage(JSON.parse(o.nativeEvent.data))},this.iframes.set(e,{iframe:n});else{const o=a=>u(this,null,function*(){a.source===t.contentWindow&&(yield this.handleIframeMessage(a.data))});window.addEventListener("message",o),this.iframes.set(e,{iframe:n,listener:o})}}setActive(t){var e,r;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:(r=this.config)==null?void 0:r.views})}activateForSelf(){return u(this,null,function*(){const t=je(),e=yield t.authorizePlugin(this.id);T(this,As,e),T(this,Kr,new Date);try{const r=yield t.getPluginConfig(this.baseURL);this.config=r}catch(r){l.error("DytePlugin::activateForSelf",{error:r})}this.setActive(!0),this.emit("enabled")})}deactivateForSelf(){Array.from(this.iframes.keys()).forEach(t=>{this.removePluginView(t)}),T(this,Kr,void 0),this.iframes.clear(),this.setActive(!1),this.emit("closed")}enable(){return u(this,null,function*(){return this.activateForSelf()})}disable(){return this.deactivateForSelf()}activate(){return u(this,null,function*(){var t,e;this.active||(e=(t=c(this,Yt).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(c(this,gt).addPlugin(this.id,this.staggered),T(this,Kr,new Date),l.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}}))})}deactivate(){return u(this,null,function*(){var t,e;this.active&&(!((e=(t=c(this,Yt).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==c(this,Yt).id||(c(this,gt).removePlugin(this.id),l.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:c(this,Kr)?new Date().getTime()-c(this,Kr).getTime():0}}),T(this,Kr,void 0)))})}},gt=new WeakMap,Yt=new WeakMap,Rs=new WeakMap,Ps=new WeakMap,Kr=new WeakMap,As=new WeakMap,Ms=new WeakMap,Ni=new WeakSet,Ds=function(){return c(this,Ms).getValue("roomNodeClient")},xf);Ma([Ct({maxInvocations:5,period:1})],Li.prototype,"sendData",1),Ma([y.trace("DytePlugin.activatePlugin")],Li.prototype,"activate",1),Ma([y.trace("DytePlugin.deactivatePlugin")],Li.prototype,"deactivate",1),Li=Ma([dt("0600")],Li);var $e,xi;class Ff extends Map{constructor(e){const{onAddEvent:r,onDeleteEvent:n,onClearEvent:i}=e;super(),_(this,$e,void 0),_(this,xi,void 0),m(this,"onAddEvent"),m(this,"onDeleteEvent"),m(this,"onClearEvent"),T(this,$e,new Ci),this.onAddEvent=r,this.onDeleteEvent=n,this.onClearEvent=i,T(this,xi,new Map)}emit(e,...r){return c(this,$e).emit(e,...r)}on(e,r){return c(this,$e).on(e,r)}addListener(e,r){return c(this,$e).addListener(e,r)}off(e,r){return c(this,$e).off(e,r)}once(e,r){return c(this,$e).once(e,r)}prependListener(e,r){return c(this,$e).prependListener(e,r)}prependOnceListener(e,r){return c(this,$e).prependOnceListener(e,r)}removeListener(e,r){return c(this,$e).removeListener(e,r)}removeAllListeners(e){return c(this,$e).removeAllListeners(e)}listeners(e){return c(this,$e).listeners(e)}listenerCount(e){return c(this,$e).listenerCount(e)}getMaxListeners(){return c(this,$e).getMaxListeners()}setMaxListeners(e){return c(this,$e).setMaxListeners(e)}eventNames(){return c(this,$e).eventNames()}add(e,r=!0){return this.set(e.id,e,r)}set(e,r,n=!0){const i=super.set(e,r),s=(o,...a)=>{this.emit(o,r,...a)};return c(this,xi).set(e,s),r.on("*",s),n&&c(this,$e).emit(this.onAddEvent,r),i}delete(e,r=!0,n=!1){const i=this.get(e);if(!i)return!1;i.removeListener("*",c(this,xi).get(e));const s=super.delete(e);return n&&i.removeAllListeners(),r&&c(this,$e).emit(this.onDeleteEvent,i),s}clear(e=!0,r=!1){this.forEach(i=>{i.removeListener("*",c(this,xi).get(i.id)),r&&i.removeAllListeners()});const n=super.clear();return e&&c(this,$e).emit(this.onClearEvent),n}toArray(){return Array.from(this.values())}}$e=new WeakMap,xi=new WeakMap;class Uf extends Ff{constructor(){super({onAddEvent:"pluginAdded",onDeleteEvent:"pluginDeleted"})}add(e,r=!0){return super.add(e,r)}delete(e,r=!0,n=!1){return super.delete(e,r,n)}}var fA=Object.defineProperty,gA=Object.getOwnPropertyDescriptor,vA=(t,e,r,n)=>{for(var i=n>1?void 0:n?gA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&fA(e,r,i),i};let pl=class{constructor(){m(this,"all"),m(this,"active"),this.all=new Uf,this.active=new Uf}};pl=vA([dt("0600")],pl);var yA=Object.defineProperty,EA=Object.getOwnPropertyDescriptor,Da=(t,e,r,n)=>{for(var i=n>1?void 0:n?EA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&yA(e,r,i),i},Qt,Os,Oa,Vf;const Bf=(Vf=class{constructor(t,e,r,n){m(this,"plugins"),_(this,Qt,void 0),_(this,Os,void 0),_(this,Oa,void 0),T(this,Qt,e),T(this,Os,r),T(this,Oa,t),this.plugins=n,this.setupEvents()}static init(t,e,r,n,i,s,o){return u(this,null,function*(){const a=new pl;return e.forEach(d=>{const h=new Li(t,d,r,s,o,i);a.all.add(h)}),new Bf(t,r,n,a)})}getRoomPlugins(){return u(this,null,function*(){const{plugins:t}=yield c(this,Qt).getActivePlugins();yield Promise.all(t.map(e=>this.enablePlugin({id:e.pluginId,enabledBy:e.enabledBy})))})}enablePlugin(t){return u(this,arguments,function*({id:e,enabledBy:r}){const n=this.plugins.all.get(e);n&&(yield n.activateForSelf(),n.enabledBy=r)})}disablePlugin(t){return u(this,arguments,function*({id:e}){const r=this.plugins.all.get(e);r&&r.deactivateForSelf()})}sendIframeEvent(t,e,r,n){const i=this.plugins.all.get(e);i&&i.sendIframeEvent({type:t,uuid:r,payload:n})}broadcastIframeEvent(t,e){this.plugins.active.forEach(r=>{this.sendIframeEvent(t,r.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)}),b.onAsync(w.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){yield this.getRoomPlugins(),l.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to fetch plugins.")})),c(this,Qt).on(J.addPlugin,t=>u(this,null,function*(){var e;const r=t.pluginId;(e=this.plugins.all.get(r))!=null&&e.active||(yield this.enablePlugin({id:r,enabledBy:t.enabledBy}))})),c(this,Qt).on(J.removePlugin,t=>u(this,null,function*(){var e;const r=t.pluginId;(e=this.plugins.all.get(r))!=null&&e.active&&(yield this.disablePlugin({id:r}))})),[J.enablePluginForPeers,J.enablePluginForRoom].forEach(t=>{c(this,Qt).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{enabledBy:e.enabledBy})}))}),[J.disablePluginForPeers,J.disablePluginForRoom].forEach(t=>{c(this,Qt).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{disabledBy:e.disabledBy})}))}),[J.customPluginEventToPeers,J.customPluginEventToRoom].forEach(t=>{c(this,Qt).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{data:JSON.parse(new TextDecoder().decode(e.pluginData))})}))}),[J.storeInsertKeys,J.storeGetKeys,J.storeDeleteKeys].forEach(t=>{c(this,Qt).on(t,(e,r)=>u(this,null,function*(){var n;const i=(n=e.storeItems)==null?void 0:n.map(s=>{var o;return{timestamp:s.timestamp,peerId:s.peerId,payload:JSON.parse((o=s.payload)!=null&&o.length?new TextDecoder().decode(s.payload):"{}"),key:s.storeKey}});this.sendIframeEvent(t,e.pluginId,r,{storeName:e.storeName,storeItems:i})}))}),c(this,Qt).on(J.storeDelete,(t,e)=>u(this,null,function*(){this.sendIframeEvent(J.storeDelete,t.pluginId,e,{storeName:t.storeName})})),c(this,Os).on(De.sendMessageToPeers,t=>{const e=wr==null?void 0:wr.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(Fe.chatMessage,{message:e})}),c(this,Os).on(De.sendMessageToRoom,t=>{const e=wr==null?void 0:wr.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(Fe.chatMessage,{message:e})}),b.on(w.PEER_JOINED_INTERNAL,t=>{const e=ya(t);this.broadcastIframeEvent(Fe.peerJoined,e)}),b.on(w.PEER_CLOSED,t=>{this.broadcastIframeEvent(Fe.peerLeft,t)}),b.on(w.UPDATE_PEER_STAGE_STATUS,t=>{this.broadcastIframeEvent(Fe.peerStageStatusUpdate,t)}),c(this,Oa).subscribe("stageStatus",t=>{this.broadcastIframeEvent(Fe.stageStatusUpdate,t)})}},Qt=new WeakMap,Os=new WeakMap,Oa=new WeakMap,Vf);let Ns=Bf;Da([y.trace("PluginController.getRoomPlugins")],Ns.prototype,"getRoomPlugins",1),Da([y.trace("PluginController.enableForSelf")],Ns.prototype,"enablePlugin",1),Da([y.trace("PluginController.disableForSelf")],Ns.prototype,"disablePlugin",1),Da([y.trace("PluginController.setupEvents")],Ns.prototype,"setupEvents",1);var SA=Object.defineProperty,TA=Object.getOwnPropertyDescriptor,Ls=(t,e,r,n)=>{for(var i=n>1?void 0:n?TA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&SA(e,r,i),i},xs,Na,Fs,La,jf;let Ln=(jf=class extends Dt{constructor(t,e){super(),_(this,Fs),_(this,xs,void 0),_(this,Na,void 0),m(this,"recordingPeerIds",[]),m(this,"recordings",[]),T(this,Na,t),T(this,xs,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 u(this,null,function*(){if(!c(this,xs).permissions.canRecord)throw l.error("DyteRecording::start::permission_denied"),new C("User does not have permission to start recording");if((t==null?void 0:t.allowMultiple)!==!0&&(this.recordingState==="STARTING"||this.recordingState==="RECORDING"||this.recordingState==="STOPPING"))throw l.error("DyteRecording::start::recording_in_progress",{recording:{state:this.recordingState}}),new C(`Cant start recording, recordingState irregular: ${this.recordingState}`);try{const e=je(),{recording:r={}}=c(this,Na).getValue("defaults"),n=yield e.startRecording(r,t==null?void 0:t.allowMultiple);this.updateRecordings([...this.recordings,{id:n,state:"STARTING"}])}catch(e){throw l.error("DyteRecording::stop::recording_failed_to_start",{error:e}),new C("Error while starting recording")}})}stop(t){return u(this,null,function*(){yield ue(this,Fs,La).call(this,"stop",["RECORDING","PAUSED"],t)})}pause(t){return u(this,null,function*(){yield ue(this,Fs,La).call(this,"pause",["RECORDING"],t)})}resume(t){return u(this,null,function*(){yield ue(this,Fs,La).call(this,"resume",["PAUSED"],t)})}},xs=new WeakMap,Na=new WeakMap,Fs=new WeakSet,La=function(t,e,r){return u(this,null,function*(){if(!c(this,xs).permissions.canRecord)throw l.error("DyteRecording::stop::permission_denied"),new C("User does not have permission to stop recording");let n=[];if(r!==void 0){const i=this.recordings.find(s=>s.id===r);if(i===void 0)throw new C("Could not find the specified recording");if(e.includes(i.state)){l.error("DyteRecording::stop::recording_not_in_expected_state",{recording:{state:i.state}});return}n.push(i)}else n=this.recordings.filter(i=>e.includes(i.state));n.forEach(i=>u(this,null,function*(){const s=i.state;t==="stop"&&(i.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{yield je().updateRecording(i.id,t)}catch(o){throw l.error("DyteRecording::stop::recording_failed_to_stop",{error:o}),i.state!==s&&(i.state=s,this.emit("recordingUpdate",s)),new C("Error while stopping recording")}}))})},jf);Ls([y.trace("DyteRecording.start")],Ln.prototype,"start",1),Ls([y.trace("DyteRecording.stop")],Ln.prototype,"stop",1),Ls([y.trace("DyteRecording.stop")],Ln.prototype,"pause",1),Ls([y.trace("DyteRecording.stop")],Ln.prototype,"resume",1),Ln=Ls([dt("1000")],Ln);var kA=Object.defineProperty,_A=Object.getOwnPropertyDescriptor,bA=(t,e,r,n)=>{for(var i=n>1?void 0:n?_A(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&kA(e,r,i),i},ml;class Hf{constructor(e,r,n){m(this,"recording"),m(this,"room"),_(this,ml,void 0),T(this,ml,e),this.recording=new Ln(e,r),this.room=n,this.setupEvents()}setupEvents(){b.on(w.ROOM_STATE,e=>{e.activeRecordings.length!==0?this.recording.updateRecordings(e.activeRecordings.map(r=>({id:r.recordingId,state:r.recordingStatus}))):this.recording.recordings.length&&this.recording.updateRecordings([])}),this.room.on(j.recordingStarted,e=>{let r=!1;const n=[...this.recording.recordings];n.forEach(i=>{i.id===e.recordingId&&(r=!0,i.state="RECORDING")}),r===!1&&n.push({id:e.recordingId,state:"RECORDING"}),this.recording.updateRecordings(n)}),this.room.on(j.recordingPaused,e=>{const r=[...this.recording.recordings];r.forEach(n=>{n.id===e.recordingId&&(n.state="PAUSED")}),this.recording.updateRecordings(r)}),this.room.on(j.recordingStopped,e=>{const r=[...this.recording.recordings.filter(n=>n.id!==e.recordingId)];this.recording.updateRecordings(r)})}}ml=new WeakMap,bA([y.trace("RecordingController.setupEvents")],Hf.prototype,"setupEvents",1);class wA{static hasFeature(e){var r;return(r=K.hasFeature(e))!=null?r:!1}static getFeatureValue(e){return K.getValue(e)}static getAllFeatures(){return K.getAllFlags()}}class fl{constructor(e,r,n){m(this,"logger"),m(this,"features"),m(this,"browserSpecs"),m(this,"callStats"),this.logger=e,this.features=r,this.browserSpecs=ye,this.callStats=n}static init(e){return new fl(l,wA,e)}}class gl{constructor(e){m(this,"internals"),this.internals=e}static init(){return u(this,null,function*(){const e=fl.init(B);return new gl(e)})}}var CA=Object.defineProperty,IA=Object.getOwnPropertyDescriptor,Ot=(t,e,r,n)=>{for(var i=n>1?void 0:n?IA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&CA(e,r,i),i},et,ut,Ke,Cr,Xt,xa,vl;class It extends Ci{constructor(e,r,n=$f,i=!0){super(),_(this,et,void 0),_(this,ut,void 0),_(this,Ke,void 0),_(this,Cr,void 0),_(this,Xt,void 0),_(this,xa,void 0),_(this,vl,void 0),m(this,"audioUpdateInProgress"),m(this,"videoUpdateInProgress"),T(this,vl,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,T(this,et,new Yf(e,r)),T(this,ut,new zA(c(this,et),void 0,n)),T(this,Ke,new rM(c(this,et),void 0,n)),T(this,Xt,new ZA(c(this,et))),T(this,Cr,new QA(c(this,et))),T(this,xa,i),c(this,ut).on("trackMuted",this.onAudioTrackMuted.bind(this)),c(this,ut).on("trackChanged",this.onAudioTrackChanged.bind(this)),c(this,Ke).on("trackChanged",this.onVideoTrackChanged.bind(this)),c(this,Ke).on("trackEnded",this.onVideoTrackEnded.bind(this)),c(this,Xt).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}onVisibilityChange(){B.tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?B.browserBackgrounded():B.browserForegrounded()}repopulateAvailableDevices(){return u(this,null,function*(){return!0})}setupStreams(e){return u(this,arguments,function*({audio:r,video:n}){var i;let s,o;if(r&&n)try{const a=yield c(this,et).getAudioAndVideoTrack();s=a.audioTrack,o=a.videoTrack}catch(a){l.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:a})}if(!s&&r)try{s=yield c(this,et).getAudioTrack(!1)}catch(a){l.error("LocalMediaHandler::init::Failed to get audio track",{error:a})}if(!o&&n)try{o=yield c(this,et).getVideoTrack()}catch(a){l.error("LocalMediaHandler::init::Failed to get video track",{error:a})}yield c(this,ut).setMediaTrack(s),yield c(this,Ke).setMediaTrack(o);try{yield c(this,Cr).setupSpeaker()}catch(a){}if(o){const a=yield this.getDeviceById(o.getSettings().deviceId);B.onSafeInitialization(()=>{B.selectedDevice("VIDEO",a)})}if(s){const a=yield this.getDeviceById(s.getSettings().deviceId);B.onSafeInitialization(()=>{B.selectedDevice("AUDIO",a)})}(i=c(this,Cr).currentDevice)!=null&&i.deviceId&&B.onSafeInitialization(()=>{B.selectedDevice("SPEAKER",c(this,Cr).currentDevice)}),c(this,et).onDeviceChange((a,d,h)=>{this.onDeviceChange(d,h)})})}getCurrentDevices(){return{audio:c(this,ut).currentDevice,video:c(this,Ke).currentDevice,speaker:c(this,Cr).currentDevice}}get permissions(){return c(this,et).permissions}getAllDevices(){return c(this,et).getAvailableDevices()}getDeviceById(e,r){return c(this,et).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return c(this,ut).mediaTrack}get audioTrack(){return c(this,ut).transformedMediaTrack}get audioEnabled(){return c(this,ut).trackEnabled}enableAudio(){return u(this,null,function*(){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{yield c(this,ut).unmuteTrack()}catch(e){}finally{this.audioUpdateInProgress=!1}}})}disableAudio(){c(this,ut).muteTrack()}getAudioDevices(e){return c(this,et).getAudioInputDevices(e)}setAudioDevice(e){return u(this,null,function*(){yield c(this,ut).setDevice(e),e!=null&&e.deviceId&&B.onSafeInitialization(()=>{B.selectedDevice("AUDIO",e)}),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}setupSpeaker(){return c(this,Cr).setupSpeaker()}setSpeakerDevice(e){return u(this,null,function*(){yield c(this,Cr).setupSpeaker(e),e!=null&&e.deviceId&&B.onSafeInitialization(()=>{B.selectedDevice("SPEAKER",e)}),this.emit("DEVICE_CHANGE",{device:e})})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return c(this,Ke).mediaTrack}get videoTrack(){return c(this,Ke).transformedMediaTrack}get videoEnabled(){return c(this,Ke).trackEnabled}enableVideo(){return u(this,null,function*(){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{yield c(this,Ke).unmuteTrack()}catch(e){}finally{this.videoUpdateInProgress=!1}}})}disableVideo(){c(this,Ke).disableTrack()}getVideoDevices(e){return c(this,et).getVideoInputDevices(e)}setVideoDevice(e){return u(this,null,function*(){yield c(this,Ke).setDevice(e),e!=null&&e.deviceId&&B.onSafeInitialization(()=>{B.selectedDevice("VIDEO",e)}),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}updateVideoConstraints(e){return u(this,null,function*(){yield c(this,Ke).updateConstraints(e)})}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:c(this,Xt).audioMediaTrack,video:c(this,Xt).videoMediaTrack}}get screenShareEnabled(){return c(this,Xt).trackEnabled}enableScreenShare(){return u(this,null,function*(){yield c(this,Xt).enableScreenShare()})}disableScreenShare(){return u(this,null,function*(){c(this,Xt).disableScreenShare()})}updateScreenshareConstraints(e){return u(this,null,function*(){yield c(this,Xt).updateConstraints(e)})}getSpeakerDevices(e){return c(this,et).getAudioOutputDevices(e)}addAudioMiddleware(e){return c(this,ut).addMiddleware(e)}removeAudioMiddleware(e){return c(this,ut).removeMiddleware(e)}addVideoMiddleware(e){return c(this,Ke).addMiddleware(e)}removeVideoMiddleware(e){return c(this,Ke).removeMiddleware(e)}setVideoMiddlewareGlobalConfig(e){return c(this,Ke).setVideoMiddlewareGlobalConfig(e)}destruct(){c(this,ut).disableTrack(),c(this,Ke).disableTrack(),c(this,Ke).terminateMiddlewareWebWorker(),c(this,Xt).disableScreenShare(),c(this,et).destruct()}onDeviceChange(e,r){return u(this,null,function*(){var n,i;this.emit("DEVICE_LIST_UPDATED",e),!(r||!c(this,xa))&&((n=e==null?void 0:e.added)==null||n.forEach(s=>u(this,null,function*(){var o;s&&!$f(s)&&(s.kind==="audioinput"&&((o=this.audioTrack)==null?void 0:o.enabled)===!0?yield this.setAudioDevice(s):s.kind==="audiooutput"&&(yield this.setSpeakerDevice(s)))})),(i=e==null?void 0:e.removed)==null||i.forEach(s=>u(this,null,function*(){var o;if(s.kind==="audiooutput"&&((o=this.getCurrentDevices().speaker)==null?void 0:o.deviceId)===s.deviceId){const a=(yield this.getSpeakerDevices()).find(d=>d.deviceId!==s.deviceId);a&&(yield this.setSpeakerDevice(a))}})))})}removeAllTracks(){this.destruct()}removeDocumentEventListeners(){return u(this,null,function*(){document.removeEventListener("visibilitychange",this.onVisibilityChange)})}}et=new WeakMap,ut=new WeakMap,Ke=new WeakMap,Cr=new WeakMap,Xt=new WeakMap,xa=new WeakMap,vl=new WeakMap,Ot([y.trace("MediaHandler.setupStreams")],It.prototype,"setupStreams",1),Ot([y.trace("MediaHandler.enableAudio")],It.prototype,"enableAudio",1),Ot([y.trace("MediaHandler.disableAudio")],It.prototype,"disableAudio",1),Ot([y.trace("MediaHandler.setAudioDevice")],It.prototype,"setAudioDevice",1),Ot([y.trace("MediaHandler.enableVideo")],It.prototype,"enableVideo",1),Ot([y.trace("MediaHandler.disableVideo")],It.prototype,"disableVideo",1),Ot([y.trace("MediaHandler.setVideoDevice")],It.prototype,"setVideoDevice",1),Ot([y.trace("MediaHandler.updateVideoConstraints")],It.prototype,"updateVideoConstraints",1),Ot([y.trace("MediaHandler.enableScreenShare")],It.prototype,"enableScreenShare",1),Ot([y.trace("MediaHandler.disableScreenShare")],It.prototype,"disableScreenShare",1),Ot([y.trace("MediaHandler.updateScreenshareConstraints")],It.prototype,"updateScreenshareConstraints",1),Ot([y.trace("MediaHandler.destruct")],It.prototype,"destruct",1),Ot([y.trace("MediaHandler.onDeviceChange")],It.prototype,"onDeviceChange",1);var yl=(t=>(t.NotAllowedError="NotAllowedError",t.NotReadableError="NotReadableError",t.NO_DEVICES_AVAILABLEError="NO_DEVICES_AVAILABLEError",t.AbortError="AbortError",t))(yl||{});function Wf(t,e,r){switch(!0){case ye.isChromiumBased():switch(e){case"NotAllowedError":return r.includes("by system")?"SYSTEM_DENIED":t==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case ye.isSafari():switch(e){case"NotReadableError":return"DENIED";default:return"COULD_NOT_START"}case ye.isFirefox():switch(e){case"NO_DEVICES_AVAILABLEError":case"NotReadableError":return"SYSTEM_DENIED";case"NotAllowedError":return"DENIED";case"AbortError":default:return"COULD_NOT_START"}default:return"COULD_NOT_START"}}const RA=["virtual","emulator","krisp","solstice conference","teams","manycam","blackHole"];function $f(t){const e=t.label.toLowerCase();return ye._bowser.getOSName()==="macOS"&&e.includes("iphone")?(l.log("isVirtualDevice::ignore_macos_continuity"),!0):RA.some(r=>e.includes(r))}function PA(t,e){return u(this,null,function*(){if(!(t!=null&&t.length))return e;const r=new AudioContext,n=yield Promise.all(t==null?void 0:t.map(o=>o(r))),i=r.createMediaStreamSource(new MediaStream([e])),s=r.createMediaStreamDestination();try{let o=i;for(let a=0;a<n.length;a+=1)o.connect(n[a]),o=n[a];o.connect(s)}catch(o){return l.error("getTransformedAudioTrack::middleware_execution_failed",{error:o}),e}return s.stream.getAudioTracks()[0]})}var Fi;class AA{constructor(){_(this,Fi,void 0)}terminateMiddlewareWebWorker(){if(c(this,Fi))try{Pu(c(this,Fi)),T(this,Fi,void 0)}catch(e){l.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}getTransformedVideoTrack(e,r,n){return u(this,null,function*(){if(!(e!=null&&e.length))return r;const i=document.createElement("canvas"),s=yield Promise.all(e==null?void 0:e.map(p=>p({canvas:i,WorkerTimers:Yv})));if(n.disablePerFrameCanvasRendering)return i.captureStream().getVideoTracks()[0];const o=document.createElement("video"),a=new MediaStream;a.addTrack(r);const d=i.getContext("2d");o.srcObject=a,o.autoplay=!0,this.terminateMiddlewareWebWorker();const h=()=>u(this,null,function*(){if(r.enabled===!1||r.readyState==="ended"){this.terminateMiddlewareWebWorker(),o.remove(),i.remove();return}try{d.drawImage(o,0,0);for(let p=0;p<s.length;p+=1)typeof s[p]=="function"&&(yield s[p](i,d))}catch(p){l.error("getTransformedVideoTrack::middleware_execution_failed",{error:p})}});try{o.play()}catch(p){}return o.addEventListener("play",()=>{i.width=o.width||r.getSettings().width,i.height=o.width||r.getSettings().height,T(this,Fi,Au(h,50))},!1),i.captureStream().getVideoTracks()[0]})}}Fi=new WeakMap;const Gf={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}}},Jf={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"}]},MA={320:[{rid:"q",maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"}],640:[{rid:"h",maxBitrate:7e5,maxFramerate:30,scalabilityMode:"L1T1"}],1280:[{rid:"h",maxBitrate:14e5,maxFramerate:30,scalabilityMode:"L1T1"}]},qf={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"}]};var Q=(t=>(t.WEBCAM="webcam",t.MIC="mic",t.SCREENSHARE_VIDEO="screenshare_video",t.SCREENSHARE_AUDIO="screenshare_audio",t))(Q||{});const DA=G_(),Ui=dr(DA.config.media);function OA(t){var e,r;const n={};return t.audio&&(n.audio={enableStereo:(e=t.audio.enableStereo)!=null?e:!1,enableHighBitrate:(r=t.audio.enableHighBitrate)!=null?r:!1}),n.video=t.video.quality,n}var Vi,El;class NA{constructor(e,r){_(this,Vi,void 0),_(this,El,void 0),m(this,"getScreenShareConstraints",()=>{var n,i,s,o,a,d,h,p,f;const g=(n=c(this,Vi))==null?void 0:n.screenshare,E=(s=(i=g==null?void 0:g.width)==null?void 0:i.max)!=null?s:1920,v=(a=(o=g==null?void 0:g.height)==null?void 0:o.max)!=null?a:1080,R=(h=(d=g==null?void 0:g.frameRate)==null?void 0:d.max)!=null?h:5;let A=(f=(p=g==null?void 0:g.frameRate)==null?void 0:p.ideal)!=null?f:5;const L=g==null?void 0:g.displaySurface,F=g==null?void 0:g.selfBrowserSurface;K.getValue(X.VAL_MIN_FRAMERATE)&&(A=parseInt(K.getValue(X.VAL_MIN_FRAMERATE),10));let W={width:{max:E},height:{max:v},frameRate:{ideal:A,max:R}};if(K.hasFeature(X.SCREENSHARE_CONSTRAINTS)){const H=K.getValue(X.SCREENSHARE_CONSTRAINTS);W=JSON.parse(H)}return L!==void 0&&["monitor","browser","window"].includes(L)&&(W=ne(V({},W),{displaySurface:L})),F!==void 0&&(W=ne(V({},W),{selfBrowserSurface:F})),{audio:!0,video:W}}),m(this,"getAudioConstraints",n=>{var i,s,o,a,d,h,p,f;const g={},E=(i=c(this,Vi))==null?void 0:i.audio,v=E!=null&&E.enableStereo?2:1;return ye.isFirefox()||ye.isWebKitBased()?(g.audio={deviceId:n,autoGainControl:(s=E==null?void 0:E.autoGainControl)!=null?s:!0,echoCancellation:(o=E==null?void 0:E.echoCancellation)!=null?o:!0,noiseSuppression:(a=E==null?void 0:E.noiseSupression)!=null?a:!0,channelCount:v},g):(g.audio={},g.audio.optional=[n?{sourceId:n}:{sourceId:"default"},{channelCount:v},{echoCancellation:(d=E==null?void 0:E.echoCancellation)!=null?d:!0},{googEchoCancellation:(h=E==null?void 0:E.echoCancellation)!=null?h:!0},{googAutoGainControl:(p=E==null?void 0:E.autoGainControl)!=null?p:!0},{googNoiseSuppression:(f=E==null?void 0:E.noiseSupression)!=null?f:!0},{googHighpassFilter:!0}],g)}),m(this,"getVideoConstraints",n=>{var i,s,o;const a={},d=(i=c(this,Vi))==null?void 0:i.video;let h=Gf.vga;if(typeof d=="string"?h=Gf[d]:d!==void 0&&(h.height.ideal=d.height.ideal,h.width.ideal=d.width.ideal),h.frameRate={ideal:(o=(s=h.frameRate)==null?void 0:s.ideal)!=null?o:24},ye.isChromiumBased()&&(h.frameRate.max=30),K.hasFeature(X.VIDEO_CONSTRAINTS)){const p=K.getValue(X.VIDEO_CONSTRAINTS);h=JSON.parse(p)}return a.video=h,typeof a.video=="boolean"||(n?a.video.deviceId={exact:n}:a.video.facingMode="user"),a}),T(this,El,e),T(this,Vi,r)}getUpdatedVideoConstraints(e){return e}}Vi=new WeakMap,El=new WeakMap;class Kf extends Error{constructor(e,r,n){super(r),m(this,"constraints"),m(this,"name"),this.name=e,this.constraints=n}}class LA{constructor(){m(this,"permissions"),this.permissions={audio:"NOT_REQUESTED",video:"NOT_REQUESTED",screenshare:"NOT_REQUESTED"}}getAudioInputDevices(e){return u(this,null,function*(){let r=e;return e||(r=yield this.getAvailableDevices()),r.filter(n=>n.kind==="audioinput")})}getVideoInputDevices(e){return u(this,null,function*(){let r=e;return e||(r=yield this.getAvailableDevices()),r.filter(n=>n.kind==="videoinput")})}getAudioOutputDevices(e){return u(this,null,function*(){let r=e;return e||(r=yield this.getAvailableDevices()),r.filter(n=>n.kind==="audiooutput")})}}var xA=Object.defineProperty,FA=Object.getOwnPropertyDescriptor,Zt=(t,e,r,n)=>{for(var i=n>1?void 0:n?FA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&xA(e,r,i),i},Us,Ir,Sl,zf;let Nt=(zf=class extends LA{constructor(t,e){super(),m(this,"availableDevices"),_(this,Us,void 0),_(this,Ir,void 0),_(this,Sl,void 0),T(this,Sl,t),T(this,Ir,new NA(t,e)),T(this,Us,new AbortController),this.availableDevices=[],this.getAvailableDevices()}get constraintsBuilder(){return c(this,Ir)}destruct(){return u(this,null,function*(){var t;(t=c(this,Us))==null||t.abort()})}handlePermissionErrors(t,e){const r=Wf(t,e.name,e.message);return this.permissions[t]=r,b.emit(w.MEDIA_PERMISSION_ERROR,{message:r,constraints:e.constraints,kind:t}),r}getAudioAndVideoTrack(){return u(this,null,function*(){const t={audio:c(this,Ir).getAudioConstraints().audio,video:c(this,Ir).getVideoConstraints().video};try{l.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(t)});const e=yield navigator.mediaDevices.getUserMedia(t);l.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(t)});const r=e.getAudioTracks()[0];let n=e.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",K.hasFeature(X.OBS_QUALITY)&&n.label.includes("OBS Virtual")){const i=(yield this.getVideoInputDevices()).find(s=>s.label.includes("OBS Virtual"));n=yield this.getVideoTrack(i.deviceId)}return b.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),b.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:r,videoTrack:n}}catch(e){throw l.error("WebMediaInterface.getAudioAndVideoTrack",{error:e}),new C("Couldnt fetch audio and video track")}})}getAudioTrack(t,e){return u(this,null,function*(){let r=yield this.getAudioInputDevices();if(r.length===0)throw this.permissions.audio="NO_DEVICES_AVAILABLE",b.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new C("No audio devices available");const n=i=>u(this,null,function*(){let s;try{r=r.filter(a=>a.deviceId!==i),s=c(this,Ir).getAudioConstraints(i),l.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(s)});const o=(yield navigator.mediaDevices.getUserMedia(s)).getAudioTracks()[0];return l.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(s)}),o}catch(o){const a=Wf("audio",o.name,o.message),d=new Kf(o.name,o.message,s);if(a==="COULD_NOT_START"){const h=r.shift();if(!h)throw d;return n(h.deviceId)}throw d}});try{const i=yield n(e);return i.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",b.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),i}catch(i){throw i.constraints&&this.handlePermissionErrors("audio",i),new C(i.message,"1601")}})}handleGUMError(t,e,r){return u(this,null,function*(){throw this.handlePermissionErrors(t,new Kf(e.name,e.message,r)),l.error(`WebMediaInterface.get${t}Tracks Error while fetching ${t} tracks`,{error:e}),new C(`Couldnt fetch ${t} tracks`)})}getScreenShareTracks(){return u(this,null,function*(){let t=c(this,Ir).getScreenShareConstraints(),e;try{l.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(t)}),B.screenShareRequested(),e=yield navigator.mediaDevices.getDisplayMedia(t),l.info("getDisplayMediaWithoutTimeout::received_display_media",{constraints:JSON.stringify(t)})}catch(r){if(r.name===yl.NotReadableError&&ye.isChromiumBased()&&K.hasFeature(X.SCREEENSHARE_CONSTRAINTS_RETRY))try{t={video:!0},e=yield navigator.mediaDevices.getDisplayMedia(t),l.info("getDisplayMediaWithoutTimeout::received_display_media_retry",{constraints:JSON.stringify(t)})}catch(n){yield this.handleGUMError("screenshare",r,t)}else yield this.handleGUMError("screenshare",r,t)}return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",b.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.screenshare,kind:"screenshare"})),{audioTrack:e.getAudioTracks()[0],videoTrack:e.getVideoTracks()[0]}})}getCurrentDeviceLabel(t){return u(this,null,function*(){const e=yield this.getDevice(t||"default");return e==null?void 0:e.label})}getVideoTrack(t){return u(this,null,function*(){const e=K.hasFeature(X.OBS_QUALITY),r=yield this.getCurrentDeviceLabel(t),n=r&&r.includes("OBS Virtual"),{video:i}=c(this,Ir).getVideoConstraints(t);let s={},o;e&&n&&typeof i!="boolean"?s={deviceId:i.deviceId}:s=i;try{if((yield this.getVideoInputDevices()).length===0)throw this.permissions.video="NO_DEVICES_AVAILABLE",b.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new C("No video devices available");[o]=(yield navigator.mediaDevices.getUserMedia({video:s})).getVideoTracks(),l.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(s)})}catch(a){if(a.name===yl.NotReadableError&&ye.isChromiumBased()&&K.hasFeature(X.SCREEENSHARE_CONSTRAINTS_RETRY))try{s=!0,[o]=(yield navigator.mediaDevices.getUserMedia({video:s})).getVideoTracks(),l.info("getUserMediaWithoutTimeout::received_user_media_retry",{constraints:JSON.stringify(s)})}catch(d){yield this.handleGUMError("video",d,s)}else yield this.handleGUMError("video",a,s)}if(e&&n&&typeof i!="boolean"&&typeof i.width=="object"){const{width:a,height:d}=o.getSettings(),{ideal:h}=i.width;o.applyConstraints({width:{ideal:h},height:{ideal:Math.floor(d*h/a)},frameRate:i.frameRate})}return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",b.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),o})}getAvailableDevices(){return u(this,null,function*(){try{const t=yield navigator.mediaDevices.enumerateDevices();return this.availableDevices=t,t}catch(t){throw l.error("enumerate_devices_failed",{error:t}),new C("Failed to get available devices")}})}getAvailableDevicesByKind(t){return u(this,null,function*(){try{return(yield navigator.mediaDevices.enumerateDevices()).filter(({kind:e})=>t===e)}catch(e){throw l.error("enumerate_devices_failed",{error:e}),new C("Failed to get available devices by kind")}})}getDevice(t){return u(this,null,function*(){try{return(yield navigator.mediaDevices.enumerateDevices()).filter(e=>e.deviceId===t)[0]}catch(e){throw l.error("enumerate_devices_failed",{error:e}),new C("Failed to get device")}})}onDeviceChange(t){return u(this,null,function*(){ye.supportsDeviceChangeEvent()&&navigator.mediaDevices.addEventListener("devicechange",e=>u(this,null,function*(){var r,n;const i=p=>`${p.kind}-${p.deviceId}`,s=this.availableDevices,o=new Set(s.map(p=>i(p))),a=yield this.getAvailableDevices(),d=new Set(a.map(p=>i(p))),h={added:a.filter(p=>!o.has(i(p))),removed:s.filter(p=>!d.has(i(p))),devices:a};if((r=h.added)!=null&&r.length||(n=h.removed)!=null&&n.length){l.info("repopulated_full_device_list",{devices:JSON.stringify(a)});const p=[...h.added,...h.removed];B.onSafeInitialization(()=>u(this,null,function*(){p.some(f=>f.kind==="audioinput")&&B.devices("AUDIO",a==null?void 0:a.filter(f=>f.kind==="audioinput")),p.some(f=>f.kind==="videoinput")&&B.devices("VIDEO",a==null?void 0:a.filter(f=>f.kind==="videoinput")),p.some(f=>f.kind==="audiooutput")&&B.devices("SPEAKER",a==null?void 0:a.filter(f=>f.kind==="audiooutput"))})),t(e,h,!1)}}),{signal:c(this,Us).signal})})}},Us=new WeakMap,Ir=new WeakMap,Sl=new WeakMap,zf);Zt([y.trace("WebMediaInterface.destruct")],Nt.prototype,"destruct",1),Zt([y.trace("WebMediaInterface.handlePermissionErrors")],Nt.prototype,"handlePermissionErrors",1),Zt([y.trace("WebMediaInterface.getAudioAndVideoTrack")],Nt.prototype,"getAudioAndVideoTrack",1),Zt([y.trace("WebMediaInterface.getAudioTrack")],Nt.prototype,"getAudioTrack",1),Zt([y.trace("WebMediaInterface.getScreenShareTracks")],Nt.prototype,"getScreenShareTracks",1),Zt([y.trace("WebMediaInterface.getVideoTrack")],Nt.prototype,"getVideoTrack",1),Zt([y.trace("WebMediaInterface.getAvailableDevices")],Nt.prototype,"getAvailableDevices",1),Zt([y.trace("WebMediaInterface.getAvailableDevicesByKind")],Nt.prototype,"getAvailableDevicesByKind",1),Zt([y.trace("WebMediaInterface.getDevice")],Nt.prototype,"getDevice",1),Zt([y.trace("WebMediaInterface.onDeviceChange")],Nt.prototype,"onDeviceChange",1),Nt=Zt([dt("1600")],Nt);const Yf=Nt,Tl={setItem:(t,e)=>{try{localStorage.setItem(t,e)}catch(r){l.error("LocalStorage::setItem::crashed",{error:r,localStorage:{key:t,value:e}})}},getItem:t=>{try{return localStorage.getItem(t)}catch(e){l.error("LocalStorage::getItem::crashed",{error:e,localStorage:{key:t}})}return null}},UA=(t=0)=>new Promise(e=>setTimeout(e,t)),VA=(t,e,r)=>{const n=typeof r=="number"?r:250,i=t.createMediaStreamSource(e),s=t.createAnalyser();s.fftSize=2048,i.connect(s);const o=new Uint8Array(s.fftSize);let a=!1;setTimeout(()=>{a=!0},n);function d(){return a?Promise.resolve(!0):(s.getByteTimeDomainData(o),o.some(h=>h!==128&&h!==0)?Promise.resolve(!1):UA().then(d))}return d().then(h=>(i.disconnect(),h),h=>{throw i.disconnect(),h})},BA=typeof AudioContext!="undefined"?AudioContext:null;class kl{constructor(e){m(this,"_AudioContext"),m(this,"audioContext"),m(this,"_audioContextRefContainers");const r=V({AudioContext:BA},e);Object.defineProperties(this,{_AudioContext:{value:r.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:kl}})}getOrCreate(e){if(!this._audioContextRefContainers.has(e)&&(this._audioContextRefContainers.add(e),this._AudioContext&&!this.audioContext))try{this.audioContext=new this._AudioContext}catch(r){}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 Qf=new kl,jA=3,HA=250;function WA(t){const e={},r=Qf.getOrCreate(e);let n=jA;function i(){return n-=1,VA(r,t.srcObject,HA).then(s=>s?n>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{Qf.release(e)})}function Xf(t){return u(this,null,function*(){const e=new Audio,r=new MediaStream;r.addTrack(t),e.srcObject=r;let n=!1;try{const i=e.play();i&&(yield i),n=yield WA(e),n&&l.info("checkIfAudioTrackIsSilent::silence_detected")}catch(i){l.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:i})}finally{e.pause(),e.remove()}return n})}var $A=Object.defineProperty,GA=Object.getOwnPropertyDescriptor,JA=(t,e,r,n)=>{for(var i=n>1?void 0:n?GA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&$A(e,r,i),i};let _l=class extends Ci{constructor(t,e,r){super(),m(this,"constructorName",this.constructor.name),m(this,"userSelectedDevice"),m(this,"mediaInterface"),m(this,"isNonPreferredDevice"),m(this,"_mediaTrack"),m(this,"transformedMediaTrack"),m(this,"middlewares",[]),m(this,"currentDevice"),this.mediaInterface=t,e&&this.setMediaTrack(e),this.userSelectedDevice=void 0,this.isNonPreferredDevice=r,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 u(this,null,function*(){const e=r=>{l.error(`${this.constructorName}.setMediaTrack.error`,{error:r})};try{this.disableTrack()}catch(r){e(r)}this._mediaTrack=yield this.conditionallyChangeTrack(t),yield this.setTransformedTrack();try{this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(r){e(r)}})}get trackEnabled(){return!!this.mediaTrack&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}muteTrack(){if(!this.mediaTrack){l.warn("BaseMediaHandler.muteTrack Tried muting with no track present");return}this.transformedMediaTrack&&(this.transformedMediaTrack.enabled=!1),this.mediaTrack.enabled=!1}unmuteTrack(){return u(this,null,function*(){try{this.mediaTrack?this.mediaTrack.enabled=!0:yield this.enableTrack(!1)}catch(t){throw l.error(`${this.constructorName}.unmuteTrack.error`,{error:t}),this.disableTrack(),new C("Failed to unmute track")}})}setCurrentDevice(){return u(this,null,function*(){var t;if(!this.mediaTrack){this.currentDevice=void 0;return}((t=this.currentDevice)==null?void 0:t.deviceId)!==this.mediaTrack.getSettings().deviceId&&(this.currentDevice=yield this.mediaInterface.getDevice(this.mediaTrack.getSettings().deviceId))})}addMiddleware(t){return u(this,null,function*(){if(ye.isWebKitBased()&&!K.hasFeature(X.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 l.error("While adding middleware",{error:e}),this.removeMiddleware(t),{success:!1,message:e==null?void 0:e.message}}})}removeMiddleware(t){return u(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(r){return l.error("While removing middleware",{error:r}),{success:!1,message:r==null?void 0:r.message}}return{success:!1,message:"No such middleware was found. Skipping."}})}addMediaTrackListeners(){var t,e,r;this.mediaTrack&&(l.info(`${this.constructorName}.addMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),this.mediaTrack.addEventListener("ended",this.onTrackEnded),this.mediaTrack.addEventListener("mute",this.onTrackMuted))}removeMediaTrackListeners(){var t,e,r;this.mediaTrack&&(l.info(`${this.constructorName}.removeMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),l.info(`${this.constructorName}.removeMediaTrackListeners`),this.mediaTrack.removeEventListener("ended",this.onTrackEnded),this.mediaTrack.removeEventListener("mute",this.onTrackMuted))}};_l=JA([dt("1600")],_l);const Zf=_l;var qA=Object.defineProperty,KA=Object.getOwnPropertyDescriptor,bl=(t,e,r,n)=>{for(var i=n>1?void 0:n?KA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&qA(e,r,i),i};const wl="[Dyte]nonSilentDeviceLabels";class Fa extends Zf{setDevice(e){return u(this,null,function*(){if(!e)throw l.warn("AudioMediaHandler.setDevice No device received"),new C("No device received!","1603");if(e.kind!=="audioinput")throw l.warn("AudioMediaHandler.setDevice Received non audio device"),new C("Non audio device received while setting device!","1603");try{const r=this.trackEnabled;this.userSelectedDevice=e.deviceId,yield this.setMediaTrack(yield this.mediaInterface.getAudioTrack(!r,e.deviceId))}catch(r){throw l.error("AudioMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new C(r.message,"1604")}})}enableTrack(e){return u(this,null,function*(){if(this.trackEnabled){l.warn("AudioMediaHandler.enableTrack Track already enabled!");return}const r=yield this.mediaInterface.getAudioTrack(e,this.userSelectedDevice);yield this.setMediaTrack(r)})}setTransformedTrack(e){return u(this,null,function*(){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=yield PA(this.middlewares,this.mediaTrack),this.emit("trackChanged")}catch(n){l.error("AudioMediaHandler.setTransformedTrack",{error:n}),this.transformedMediaTrack=this.mediaTrack}})}onTrackEnded(){return u(this,null,function*(){l.info("AudioMediaHandler.TrackEnded"),this.emit("trackEnded");const e=this.mediaTrack.enabled;this.disableTrack(),yield this.enableTrack(!e),yield this.setTransformedTrack(),this.emit("trackChanged")})}onTrackMuted(){l.info("AudioMediaHandler.TrackMuted"),this.emit("trackMuted")}conditionallyChangeTrack(e){return u(this,null,function*(){var r;if(!e||this.userSelectedDevice)return e;let n=e;const i=yield this.mediaInterface.getAudioInputDevices(),s=this.isNonPreferredDevice?i.filter(d=>d&&!this.isNonPreferredDevice(d)):i;if(!(s!=null&&s.length))return n;s.find(d=>d.deviceId===e.getSettings().deviceId)||(n.stop(),l.info("localmediahandler::setupstreams::found_audio_non_preferred"),n=yield this.mediaInterface.getAudioTrack(!1,s[0].deviceId));const o=JSON.parse(Tl.getItem(wl));if(o!=null&&o.devices.some(d=>d.label===n.label))return n;if(!(yield Xf(n))){const d=(r=o==null?void 0:o.devices.concat({label:n.label}))!=null?r:[{label:n.label}];return Tl.setItem(wl,JSON.stringify({devices:d})),n}l.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const a=n.getSettings().deviceId;return s.filter(d=>d.deviceId!==a).some(d=>u(this,null,function*(){if(n=yield this.mediaInterface.getAudioTrack(!1,d.deviceId),!(yield Xf(n))){const h=o.devices.concat({label:n.label});return Tl.setItem(wl,JSON.stringify({devices:h})),l.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return l.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1})),n})}}bl([y.trace("AudioMediaHandler.setTransformedTrack")],Fa.prototype,"setTransformedTrack",1),bl([y.trace("AudioMediaHandler.onTrackEnded")],Fa.prototype,"onTrackEnded",1),bl([y.trace("AudioMediaHandler.conditionallyChangeTrack")],Fa.prototype,"conditionallyChangeTrack",1);const zA=Fa;var Vs;class YA{constructor(e){_(this,Vs,void 0),m(this,"currentDevice"),T(this,Vs,e)}setupSpeaker(e){return u(this,null,function*(){var r;if(!(c(this,Vs)instanceof Yf))return;let n=e;if(e||([n]=yield c(this,Vs).getAvailableDevicesByKind("audiooutput")),!n)throw new C("No speaker found");((r=this.currentDevice)==null?void 0:r.deviceId)!==n.deviceId&&(this.currentDevice=n,document.querySelectorAll("audio").forEach(i=>u(this,null,function*(){if(typeof i.sinkId!="undefined"&&this.currentDevice.deviceId&&i.sinkId!==this.currentDevice.deviceId)try{yield i.setSinkId(this.currentDevice.deviceId)}catch(s){}})))})}}Vs=new WeakMap;const QA=YA;class XA extends Ci{constructor(e){super(),m(this,"mediaInterface"),m(this,"audioMediaTrack"),m(this,"videoMediaTrack"),this.mediaInterface=e}get trackEnabled(){return!!this.videoMediaTrack}enableScreenShare(){return u(this,null,function*(){var e,r;try{const{audioTrack:n,videoTrack:i}=yield this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=n,this.videoMediaTrack=i,this.addMediaTrackListeners(),((r=(e=this.mediaInterface)==null?void 0:e.permissions)==null?void 0:r.screenshare)==="ACCEPTED")return;this.mediaInterface.permissions&&(this.mediaInterface.permissions.screenshare="ACCEPTED",b.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch(n){}})}disableScreenShare(){var e,r;this.removeMediaTrackListeners(),(e=this.audioMediaTrack)==null||e.stop(),(r=this.videoMediaTrack)==null||r.stop(),this.videoMediaTrack=void 0,this.audioMediaTrack=void 0}updateConstraints(e){return u(this,null,function*(){if(!this.videoMediaTrack)throw new C("No media track enabled!");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new C("update constraints not supported for non web clients","1100");try{this.videoMediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),this.addMediaTrackListeners()}catch(n){l.error("ScreenShareHandler.updateConstraints.error",{error:n})}})}addMediaTrackListeners(){var e;(e=this.videoMediaTrack)==null||e.addEventListener("ended",this.onTrackEnded.bind(this))}removeMediaTrackListeners(){var e;(e=this.videoMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded)}onTrackEnded(){this.emit("trackEnded")}}const ZA=XA;var eM=Object.defineProperty,tM=Object.getOwnPropertyDescriptor,Ua=(t,e,r,n)=>{for(var i=n>1?void 0:n?tM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&eM(e,r,i),i},Bs,Va;class js extends Zf{constructor(e,r,n){super(e,r,n),_(this,Bs,void 0),_(this,Va,{disablePerFrameCanvasRendering:!1}),T(this,Bs,new AA)}setDevice(e){return u(this,null,function*(){if(!e)throw l.warn("VideoMediaHandler.setDevice No device received"),new C("No device received!");if(e.kind!=="videoinput")throw l.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new C("Non video device received while setting video device!");if(this.userSelectedDevice=e.deviceId,!(this.mediaTrack&&this.mediaTrack.enabled)){l.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(r){throw l.error("VideoMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new C("Failed to change device")}})}enableTrack(){return u(this,null,function*(){if(this.trackEnabled){l.warn("VideoMediaHandler.enableTrack Track already enabled!");return}yield this.setMediaTrack(yield this.mediaInterface.getVideoTrack(this.userSelectedDevice))})}setTransformedTrack(e){return u(this,null,function*(){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=yield c(this,Bs).getTransformedVideoTrack(this.middlewares,this.mediaTrack,c(this,Va)),this.emit("trackChanged")}catch(n){l.error("VideoMediaHandler.setTransformedTrack",{error:n}),this.transformedMediaTrack=this.mediaTrack}})}setVideoMiddlewareGlobalConfig(e){return u(this,null,function*(){T(this,Va,e)})}updateConstraints(e){return u(this,null,function*(){if(!this._mediaTrack)throw new C("No media track enabled!");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new C("update constraints not supported for non web clients","1100");try{this._mediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),yield this.setTransformedTrack(),this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(n){l.error("VideoMediaHandler.updateConstraints.error",{error:n})}})}terminateMiddlewareWebWorker(){c(this,Bs).terminateMiddlewareWebWorker()}onTrackEnded(){return u(this,null,function*(){l.info("VideoMediaHandler.TrackEnded"),this.disableTrack(),this.emit("trackEnded")})}onTrackMuted(){l.info("VideoMediaHandler.TrackMuted"),this.emit("trackMuted")}conditionallyChangeTrack(e){return u(this,null,function*(){if(!e||this.userSelectedDevice)return e;let r=e;const n=yield this.mediaInterface.getVideoInputDevices(),i=this.isNonPreferredDevice?n.filter(s=>!this.isNonPreferredDevice(s)):n;return!(i!=null&&i.length)||window.FAST_DYTE||i.find(s=>s.deviceId===e.getSettings().deviceId)||(r.stop(),l.info("localmediahandler::setupstreams::found_video_non_preferred"),r=yield this.mediaInterface.getVideoTrack(i[0].deviceId)),r})}}Bs=new WeakMap,Va=new WeakMap,Ua([y.trace("VideoMediaHandler.setTransformedTrack")],js.prototype,"setTransformedTrack",1),Ua([y.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],js.prototype,"setVideoMiddlewareGlobalConfig",1),Ua([y.trace("VideoMediaHandler.onTrackEnded")],js.prototype,"onTrackEnded",1),Ua([y.trace("VideoMediaHandler.conditionallyChangeTrack")],js.prototype,"conditionallyChangeTrack",1);const rM=js,eg=dr(Ld());var jt,Bi,Ba,Hs;const Ws=class{constructor(t){if(_(this,jt,void 0),_(this,Bi,void 0),_(this,Ba,void 0),_(this,Hs,void 0),!t)throw new C("Could not load preset.");T(this,jt,t.config),T(this,Ba,t.name),T(this,Bi,t.ui||dr(Ld().ui)),T(this,Hs,t.permissions.plugins.config)}static fromResponse(t){return new Ws(t)}static default(){return new Ws(eg)}static init(t,e=!0){return!t||e?new Ws(eg):new Ws(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:c(this,Bi).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return c(this,jt).viewType}get maxVideoStreams(){return c(this,jt).maxVideoStreams}get maxScreenShareCount(){return c(this,jt).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(c(this,Hs)).filter(t=>c(this,Hs)[t].disabled)}get designTokens(){return c(this,Bi).designTokens}get configDiff(){return c(this,Bi).configDiff}get mediaConstraints(){var t,e,r,n,i,s,o,a,d,h,p,f,g,E,v,R,A,L,F,W,H,I,S,P;return{audio:{enableStereo:(n=(r=(e=(t=c(this,jt))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?n:Ui.audio.enableStereo,enableHighBitrate:(a=(o=(s=(i=c(this,jt))==null?void 0:i.media)==null?void 0:s.audio)==null?void 0:o.enableHighBitrate)!=null?a:Ui.audio.enableHighBitrate},video:{quality:(f=(p=(h=(d=c(this,jt))==null?void 0:d.media)==null?void 0:h.video)==null?void 0:p.quality)!=null?f:Ui.video.quality,frameRate:(R=(v=(E=(g=c(this,jt))==null?void 0:g.media)==null?void 0:E.video)==null?void 0:v.frameRate)!=null?R:Ui.video.frameRate},screenshare:{quality:(W=(F=(L=(A=c(this,jt))==null?void 0:A.media)==null?void 0:L.screenshare)==null?void 0:F.quality)!=null?W:Ui.screenshare.quality,frameRate:(P=(S=(I=(H=c(this,jt))==null?void 0:H.media)==null?void 0:I.screenshare)==null?void 0:S.frameRate)!=null?P:Ui.screenshare.frameRate}}}get name(){return c(this,Ba)}};let nM=Ws;jt=new WeakMap,Bi=new WeakMap,Ba=new WeakMap,Hs=new WeakMap;var iM=Object.defineProperty,sM=Object.getOwnPropertyDescriptor,tg=(t,e,r,n)=>{for(var i=n>1?void 0:n?sM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&iM(e,r,i),i},$s;class Cl extends Dt{constructor(e){super(),_(this,$s,void 0),m(this,"state","IDLE"),m(this,"playbackUrl"),m(this,"viewerCount"),T(this,$s,e),this.viewerCount=0}setLivestreamState(e){const r=this.state;this.state=e,r!==e&&this.emitCurrentLivestreamState()}emitCurrentLivestreamState(){this.emit("livestreamUpdate",this.state)}start(){return u(this,null,function*(){if(!c(this,$s).permissions.canLivestream)throw l.error("DyteLivestream::start::permission_denied"),new C("User does not have permission to start livestreaming");this.setLivestreamState("STARTING");try{const e=yield je().startLivestreaming();this.playbackUrl=e}catch(e){throw l.error("DyteRecording::stop::livestream_failed_to_start",{error:e}),this.setLivestreamState("IDLE"),new C("Error while starting livestream")}})}stop(){return u(this,null,function*(){if(!c(this,$s).permissions.canLivestream)throw l.error("DyteLivestream::stop::permission_denied"),new C("User does not have permission to stop livestreaming");if(this.state!=="LIVESTREAMING")throw l.error("DyteLivestream::stop::inconsistent_state"),new C("Livestream not started yet");try{this.setLivestreamState("STOPPING"),yield je().stopLivestreaming()}catch(e){throw l.error("DyteLivestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new C("Error while stopping livestream")}})}}$s=new WeakMap,tg([y.trace("livestream.start")],Cl.prototype,"start",1),tg([y.trace("livestream.stop")],Cl.prototype,"stop",1);var oM=Object.defineProperty,aM=Object.getOwnPropertyDescriptor,cM=(t,e,r,n)=>{for(var i=n>1?void 0:n?aM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&oM(e,r,i),i},Gs,xn;class rg{constructor(e,r){m(this,"livestream"),_(this,Gs,void 0),_(this,xn,void 0),this.livestream=new Cl(e),T(this,xn,r),this.setupEvents()}fetchInitialLivestreamingState(){return u(this,null,function*(){const e=je(),{status:r,playbackUrl:n}=yield e.getActiveLivestream();this.livestream.playbackUrl=n,r==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING")})}setupEvents(){c(this,xn).on(j.startedLivestream,e=>{this.livestream.playbackUrl=e.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING")}),c(this,xn).on(j.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),c(this,xn).on(j.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),c(this,xn).on(j.roomPeerCount,e=>{this.livestream.viewerCount=e.count,this.livestream.emit("viewerCountUpdate",e.count)}),b.on(w.PEER_JOINED_INTERNAL,e=>u(this,null,function*(){var r;((r=e.flags)==null?void 0:r.hiddenParticipant)===!0&&e.recorderType==="LIVESTREAMER"&&(T(this,Gs,e.id),this.livestream.setLivestreamState("LIVESTREAMING"))})),b.on(w.PEER_CLOSED,e=>{e.id===c(this,Gs)&&(T(this,Gs,void 0),this.livestream.setLivestreamState("IDLE"))}),b.onAsync(w.LEAVE_MEDIA_ROOM,()=>u(this,null,function*(){this.livestream.playbackUrl||(l.info("Fetching livestreaming state on leave stage"),yield this.fetchInitialLivestreamingState())})),b.on(w.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){try{yield this.fetchInitialLivestreamingState()}catch(e){l.error("Error: LivestreamController.fetchLivestream")}}))}}Gs=new WeakMap,xn=new WeakMap,cM([y.trace("LivestreamController.setupEvents")],rg.prototype,"setupEvents",1);var dM=Object.defineProperty,lM=Object.getOwnPropertyDescriptor,Js=(t,e,r,n)=>{for(var i=n>1?void 0:n?lM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&dM(e,r,i),i};const ng={maxInvocations:1,period:200},Il={maxInvocations:5,period:1e3};var vt,Fn,Un,Rl,ig;class ji{constructor({name:e,socketHandler:r,meetingId:n}){_(this,Rl),m(this,"name",""),_(this,vt,{}),_(this,Fn,""),_(this,Un,void 0),m(this,"volatile"),m(this,"listeners",{}),this.name=e,T(this,Un,r),T(this,Fn,n)}set(e,r,n=!0,i=!1){return u(this,null,function*(){c(this,vt)[e]=r,n&&c(this,Un).storeInsertKeys(c(this,Fn),this.name,[{key:e,payload:r}]),i&&(this.listeners[e]&&this.listeners[e].forEach(s=>s({[e]:c(this,vt)[e]})),this.listeners["*"]&&this.listeners["*"].forEach(s=>s({[e]:c(this,vt)[e]})))})}bulkSet(e){return u(this,null,function*(){e.forEach(({key:r,payload:n})=>{c(this,vt)[r]=n}),c(this,Un).storeInsertKeys(c(this,Fn),this.name,e)})}update(e,r,n=!0){return u(this,null,function*(){ue(this,Rl,ig).call(this,e,r,n)})}delete(e,r=!0,n=!1){return u(this,null,function*(){if(c(this,vt)[e]&&delete c(this,vt)[e],r)return c(this,Un).storeDeleteKeys(c(this,Fn),this.name,[{key:e}]);n&&(this.listeners[e]&&(this.listeners[e].forEach(i=>i({[e]:void 0})),delete this.listeners[e]),this.listeners["*"]&&this.listeners["*"].forEach(i=>i({[e]:void 0})))})}bulkDelete(e){return u(this,null,function*(){return e.forEach(({key:r})=>{c(this,vt)[r]&&delete c(this,vt)[r]}),c(this,Un).storeDeleteKeys(c(this,Fn),this.name,e)})}get(e){if(c(this,vt)[e])return c(this,vt)[e]}getAll(){return c(this,vt)}subscribe(e,r){if(this.listeners[e]){this.listeners[e].push(r);return}this.listeners[e]=[r]}unsubscribe(e){this.listeners[e]&&delete this.listeners[e]}populate(e){T(this,vt,e)}}vt=new WeakMap,Fn=new WeakMap,Un=new WeakMap,Rl=new WeakSet,ig=function(t,e,r=!0){let n;const i=c(this,vt)[t],s=Object.prototype.toString.call(e),o=Object.prototype.toString.call(i);if(s!==o){this.set(t,e);return}switch(o){case"[object Array]":n=[...i,...e];break;case"[object Object]":n=V(V({},i),e);break;case"[object Map]":n=new Map([...i,...e]);break;case"[object Set]":n=new Set([...i,...e]);break;default:n=e;break}this.set(t,n,r)},Js([Ct(Il)],ji.prototype,"set",1),Js([Ct(ng)],ji.prototype,"bulkSet",1),Js([Ct(Il)],ji.prototype,"update",1),Js([Ct(Il)],ji.prototype,"delete",1),Js([Ct(ng)],ji.prototype,"bulkDelete",1);var Hi,Wi,ja,Pl,Ha,Vn,Al,sg;class uM{constructor(e,r){_(this,ja),_(this,Al),m(this,"stores",new Map),_(this,Hi,void 0),_(this,Wi,""),_(this,Ha,void 0),_(this,Vn,new Map),T(this,Hi,r),T(this,Wi,e.getValue("meetingId")),T(this,Ha,e),ue(this,Al,sg).call(this)}create(e){const r=new ji({name:e,socketHandler:c(this,Hi),meetingId:c(this,Wi)});return c(this,Hi).storeGetKeys(c(this,Wi),e,[]),new Promise((n,i)=>{const s=setTimeout(()=>i(Error("Failed")),3e3);c(this,Vn).set(e,{rejectTimeout:s,resolve:n,store:r})})}}Hi=new WeakMap,Wi=new WeakMap,ja=new WeakSet,Pl=function(){return c(this,Ha).getValue("peerId")},Ha=new WeakMap,Vn=new WeakMap,Al=new WeakSet,sg=function(){[J.storeInsertKeys,J.storeGetKeys,J.storeDeleteKeys].forEach(t=>{c(this,Hi).on(t,e=>u(this,null,function*(){var r,n;if(e.pluginId!==c(this,Wi))return;const i=(r=e.storeItems)==null?void 0:r.map(o=>{var a;return{timestamp:o.timestamp,peerId:o.peerId,payload:JSON.parse((a=o.payload)!=null&&a.length?new TextDecoder().decode(o.payload):"{}"),key:o.storeKey}});if(t===J.storeGetKeys){const o=c(this,Vn).get(e.storeName),a=this.stores.get(e.storeName)||(o==null?void 0:o.store);c(this,Vn).get(e.storeName)&&(this.stores.set(e.storeName,o.store),o.resolve(a),clearTimeout(o.rejectTimeout),c(this,Vn).delete(e.storeName)),i.forEach(d=>{a.set(d.key,d.payload,!1,!1)});return}const s=this.stores.get(e.storeName)||((n=c(this,Vn).get(e.storeName))==null?void 0:n.store);s!==void 0&&(t===J.storeInsertKeys&&i.forEach(({key:o,peerId:a,payload:d})=>{a===c(this,ja,Pl)&&t!==J.storeGetKeys||s.set(o,d,!1,!0)}),t===J.storeDeleteKeys&&i.forEach(({key:o,peerId:a})=>{a!==c(this,ja,Pl)&&s.delete(o,!1,!0)}))}))})};function Bn(t){var e,r,n,i,s,o,a,d,h,p,f,g,E;return t?{media:{audio:{enabled:t.audioEnabled,trackId:(e=t.audioTrack)==null?void 0:e.id,permission:"mediaPermissions"in t?(r=t.mediaPermissions)==null?void 0:r.audio:null},video:{enabled:t.videoEnabled,trackId:(n=t.videoTrack)==null?void 0:n.id,permission:"mediaPermissions"in t?(i=t.mediaPermissions)==null?void 0:i.video:null},screenshare:{enabled:t.screenShareEnabled,permission:"mediaPermissions"in t?(s=t.mediaPermissions)==null?void 0:s.screenshare:null,audio:{enabled:(a=(o=t.screenShareTracks)==null?void 0:o.audio)==null?void 0:a.enabled,trackId:(h=(d=t.screenShareTracks)==null?void 0:d.audio)==null?void 0:h.id},video:{enabled:(f=(p=t.screenShareTracks)==null?void 0:p.video)==null?void 0:f.enabled,trackId:(E=(g=t.screenShareTracks)==null?void 0:g.video)==null?void 0:E.id}}}}:{}}var hM=Object.defineProperty,pM=Object.getOwnPropertyDescriptor,$i=(t,e,r,n)=>{for(var i=n>1?void 0:n?pM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&hM(e,r,i),i};const mM=.8,fM=1.2;var qs,Ks,Wa,jn,Gi,zr,$a,Hn,Yr,Ml,Ga,Dl,Ol,og,ag;let Rr=(ag=class extends Dt{constructor(t,e,r,n){super(),_(this,jn),_(this,Ga),_(this,Ol),m(this,"id"),m(this,"userId"),m(this,"name"),m(this,"picture"),m(this,"isHost"),m(this,"customParticipantId"),m(this,"flags"),m(this,"device"),m(this,"videoTrack"),m(this,"audioTrack"),m(this,"screenShareTracks"),m(this,"videoEnabled"),m(this,"audioEnabled"),m(this,"screenShareEnabled"),m(this,"producers"),m(this,"manualProducerConfig"),_(this,qs,void 0),m(this,"supportsRemoteControl",!1),_(this,Ks,void 0),m(this,"presetName"),_(this,Wa,void 0),_(this,zr,void 0),_(this,$a,void 0),_(this,Hn,new Map),_(this,Yr,1),_(this,Ml,cr(H=>{if(!this.videoTrack)return;const{clientWidth:I,clientHeight:S}=H,{width:P,height:N}=this.videoTrack.getSettings();if(!P||!N)return;const ce=N/S,Le=P/I,$=Math.max(ce,Le);$>fM&&c(this,Yr)===1?(T(this,Yr,0),b.emit(w.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:c(this,Yr)})):$<mM&&c(this,Yr)===0&&(T(this,Yr,1),b.emit(w.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:c(this,Yr)}))},2e3)),T(this,Wa,t);const{id:i,userId:s,displayName:o,device:a,picture:d,isHost:h,flags:p,clientSpecificId:f,stageStatus:g,customParticipantId:E,audioMuted:v,audioTrack:R,videoEnabled:A=!1,videoTrack:L,producers:F,metadata:W}=e;this.id=i,this.userId=s,this.name=o,this.device=a,this.picture=d,this.isHost=h,this.flags=p,this.manualProducerConfig=jd,T(this,Ks,g!=null?g:"ON_STAGE"),this.customParticipantId=E!=null?E:f,this.audioEnabled=!v,this.audioTrack=R,this.videoEnabled=A,this.videoTrack=L,this.screenShareTracks={audio:void 0,video:void 0},this.producers=F!=null?F:[],this.presetName=W==null?void 0:W.preset_name,T(this,qs,!1),T(this,zr,r),T(this,$a,n),this.setupEvents()}get clientSpecificId(){return this.customParticipantId}get stageStatus(){return c(this,Ks)}get roomJoined(){var t;return((t=c(this,jn,Gi))==null?void 0:t.roomJoined)===!0}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(l.info("DyteParticipant::setVideoEnabled::videoUpdate",V({},Bn(this))),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(l.info("DyteParticipant::setAudioEnabled::audioUpdate",V({},Bn(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",ue(this,Ol,og))}pin(){return u(this,null,function*(){if(!this.roomJoined)throw new C("Can`t pin participant without joining room");if(!c(this,zr).permissions.pinParticipant)throw new C("You do not have permission to pin participants.");return c(this,jn,Gi).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!this.roomJoined)throw new C("Can`t unpin participant without joining room");if(!c(this,zr).permissions.pinParticipant)throw new C("You do not have permission to unpin participants.");return c(this,jn,Gi).pinPeer(null)})}setIsPinned(t,e=!0){T(this,qs,t);const r=t?"pinned":"unpinned";e&&this.emit(r,this)}disableAudio(){return u(this,null,function*(){const t=this.id;if(l.info("DyteParticipant::disable_audio",{dyteParticipant:{id:t}}),!this.roomJoined)throw new C("Can`t disable participant audio without joining room");if(c(this,zr).permissions.canDisableParticipantAudio)return c(this,jn,Gi).disableAudio(t);throw l.error("DyteParticipant::unauthorized_disable_audio",{dyteParticipant:{id:t}}),new C("Unauthorized: User does not have permission to disable participant audio.")})}kick(){return u(this,null,function*(){const t=this.id;if(l.info("DyteParticipant::kick",{dyteParticipant:{id:t}}),!this.roomJoined)throw new C("Can`t kick participant without joining room");if(c(this,zr).permissions.kickParticipant){yield b.emitAsync(w.KICK_PEER,{peerId:t});return}throw l.error("DyteParticipant::unauthorized_kick",{dyteParticipant:{id:t}}),new C("Unauthorized: User does not have permission to kick participants.")})}disableVideo(){return u(this,null,function*(){const t=this.id;if(l.info("DyteParticipant::disable_video",{dyteParticipant:{id:t}}),!this.roomJoined)throw new C("Can`t disable participant video without joining room");if(c(this,zr).permissions.canDisableParticipantVideo)return c(this,jn,Gi).disableVideo(t);throw l.error("DyteParticipant::unauthorized_disable_video",{dyteParticipant:{id:t}}),new C("Unauthorized: User does not have permission to disable participant video.")})}getPermissions(){return u(this,null,function*(){return c(this,$a).getUserPermissions(this.userId)})}setStageStatus(t){T(this,Ks,t),this.emit("stageStatusUpdate",this)}get isPinned(){return c(this,qs)}registerVideoElement(t){var e,r;let n;(r=(e=c(this,Hn).get(t))==null?void 0:e.observer)==null||r.disconnect(),"ResizeObserver"in window&&(n=new ResizeObserver(()=>c(this,Ml).call(this,t)),n.observe(t)),c(this,Hn).set(t,{observer:n}),ue(this,Ga,Dl).call(this,t)}deregisterVideoElement(t){var e,r;t.srcObject=void 0,(r=(e=c(this,Hn).get(t))==null?void 0:e.observer)==null||r.disconnect(),c(this,Hn).delete(t)}},qs=new WeakMap,Ks=new WeakMap,Wa=new WeakMap,jn=new WeakSet,Gi=function(){return c(this,Wa).getValue("roomNodeClient")},zr=new WeakMap,$a=new WeakMap,Hn=new WeakMap,Yr=new WeakMap,Ml=new WeakMap,Ga=new WeakSet,Dl=function(t){if(this.videoEnabled){if(this.videoTrack==null)return;const e=new MediaStream;e.addTrack(this.videoTrack),t.srcObject=e}else t.srcObject=void 0},Ol=new WeakSet,og=function(){Array.from(c(this,Hn).keys()).forEach(ue(this,Ga,Dl))},ag);$i([y.trace("DyteParticipant.disableAudio")],Rr.prototype,"disableAudio",1),$i([y.trace("DyteParticipant.kick")],Rr.prototype,"kick",1),$i([y.trace("DyteParticipant.disableVideo")],Rr.prototype,"disableVideo",1),$i([y.trace("DyteParticipant.getPermissions")],Rr.prototype,"getPermissions",1),$i([y.trace("DyteParticipant.setStageStatus")],Rr.prototype,"setStageStatus",1),Rr=$i([dt("1200")],Rr);class Ja extends Ff{constructor(e){const{onAddEvent:r="participantJoined",onDeleteEvent:n="participantLeft",onClearEvent:i="participantsCleared"}=e!=null?e:{};super({onAddEvent:r,onDeleteEvent:n,onClearEvent:i})}add(e,r=!0){return this.has(e.id)&&Object.is(this.get(e.id),e)===!1&&this.delete(e.id),super.add(e,r)}clear(e=!0,r=!1){return super.clear(e,r)}delete(e,r=!0,n=!1){return super.delete(e,r,n)}}var Wn;class gM extends Ci{constructor(){super(),_(this,Wn,void 0),T(this,Wn,new Map)}__set(e,r){return c(this,Wn).set(e,r)}__clear(){return c(this,Wn).clear()}get(e){return c(this,Wn).get(e)}toArray(){return Array.from(c(this,Wn).values())}}Wn=new WeakMap;function vM(t,e=2){return t.replace(/[^\u00BF-\u1FFF\u2C00-\uD7FF\w\s]/g,"").trim().split(/\s+/).slice(0,e).map(r=>r.charAt(0)).join("").toUpperCase()}const cg=1080,dg=1920,yM=(t,e,r,n,i,s)=>{let o=.5,a=.5;const d=i,h=s,p=Math.min(r/d,n/h);let f=d*p,g=h*p,E,v,R,A,L=1;return f<r&&(L=r/f),Math.abs(L-1)<1e-14&&g<n&&(L=n/g),f*=L,g*=L,R=d/(f/r),A=h/(g/n),E=(d-R)*o,v=(h-A)*a,E<0&&(E=0),v<0&&(v=0),R>d&&(R=d),A>h&&(A=h),[E,v,R,A,t,e,r,n]};var pr,zs,yt,Qr,Oe,Xr,Zr,er,ze;class EM extends Dt{constructor(e,r){super(),_(this,pr,void 0),_(this,zs,void 0),_(this,yt,void 0),_(this,Qr,void 0),_(this,Oe,{height:cg,width:dg}),_(this,Xr,{brand:"#2160FD",background:"#141414",videoBackground:"#191919",textOnBrand:"#EEEEEE"}),_(this,Zr,void 0),_(this,er,{}),_(this,ze,void 0),m(this,"cleanupEventListeners",()=>{c(this,zs).unsubscribe("stageStatus",this.handlePipMediaControls),c(this,ze).removeListener("videoUpdate",this.onSelfVideoUpdateListener),c(this,ze).removeListener("audioUpdate",this.onSelfAudioUpdateListener),c(this,ze).removeListener("roomLeft",this.disable)}),m(this,"enablePipMediaControls",()=>{this.mountAudioEvents(),this.mountVideoEvents()}),m(this,"onSelfVideoUpdateListener",({videoEnabled:n})=>{this.updateMediaSession("CAMERA",n)}),m(this,"onSelfAudioUpdateListener",({audioEnabled:n})=>{this.updateMediaSession("MIC",n)}),m(this,"handlePipMediaControls",n=>{n==="ON_STAGE"?this.enablePipMediaControls():this.unmountEvents()}),m(this,"eventCallback",n=>{n==="CAMERA"&&(c(this,ze).videoEnabled?c(this,ze).disableVideo():c(this,ze).enableVideo(),this.emit("cameraToggled")),n==="MIC"&&(c(this,ze).audioEnabled?c(this,ze).disableAudio():c(this,ze).enableAudio(),this.emit("micToggled")),n==="END"&&(b.emit(w.PIP_HANGUP),this.cleanupEventListeners(),this.emit("hangup"),this.cleanup())}),m(this,"unmountEvents",()=>{navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("togglemicrophone",void 0),navigator.mediaSession.setActionHandler("togglecamera",void 0))}),m(this,"animate",()=>{c(this,er)!==void 0&&this.paintCanvas(),c(this,Zr)!==void 0&&T(this,Zr,requestAnimationFrame(()=>this.animate()))}),m(this,"disable",()=>{this.cleanupEventListeners(),cancelAnimationFrame(c(this,Zr)),document.body.removeChild(c(this,yt)),T(this,Zr,void 0),document.exitPictureInPicture()}),T(this,zs,e),T(this,ze,r),T(this,Xr,{brand:r.config.designTokens.colors.brand[500],background:r.config.designTokens.colors.background[1e3],videoBackground:r.config.designTokens.colors.videoBg,textOnBrand:r.config.designTokens.colors.textOnBrand})}createVideoContainer(){T(this,yt,document.createElement("div")),c(this,yt).style.width="0.1px",c(this,yt).style.height="0.1px",c(this,yt).style.overflow="hidden",c(this,yt).style.position="absolute",c(this,yt).style.bottom="0",c(this,yt).style.right="0",c(this,yt).style.opacity="0",c(this,yt).appendChild(c(this,Qr))}setupEventListeners(){c(this,zs).subscribe("stageStatus",this.handlePipMediaControls),c(this,ze).addListener("videoUpdate",this.onSelfVideoUpdateListener),c(this,ze).addListener("audioUpdate",this.onSelfAudioUpdateListener),c(this,ze).addListener("roomLeft",this.disable)}createCanvas(){const e=document.createElement("canvas");e.height=c(this,Oe).height,e.width=c(this,Oe).width,T(this,pr,e)}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||c(this,ze).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||c(this,ze).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const e=Object.values(c(this,er)),r=e.filter(n=>n.pinned);return r.length===1?r:e}drawEmptyTile(e,r,n,i,s){if(c(this,pr)===void 0)return;const o=c(this,pr).getContext("2d"),a=c(this,pr).width,d=4,h=4,p=r-d*2,f=n-d*2,g=Math.floor(a/p),E=Math.floor(e/g),v=e%g*(p+d)+d,R=E*(f+d)+d;o.fillStyle=c(this,Xr).videoBackground,o.strokeStyle=c(this,Xr).brand,o.beginPath(),o.moveTo(v+h,R),o.arcTo(v+p,R,v+p,R+h,h),o.arcTo(v+p,R+f,v+p-h,R+f,h),o.arcTo(v,R+f,v,R+f-h,h),o.arcTo(v,R,v+h,R,h),o.closePath(),o.fill(),o.stroke();const A=p/6,L=p/2+v,F=f/2+R;if(o.save(),(i||s)&&(o.beginPath(),o.arc(L,F,A,0,Math.PI*2),o.fillStyle=c(this,Xr).brand,o.fill()),i&&(o.fillStyle=c(this,Xr).textOnBrand,o.font=`${A/2}px sans-serif`,o.textAlign="center",o.textBaseline="middle",o.fillText(i,L,F)),s){const W=new Image;W.src=s,W.onload=()=>{o.drawImage(W,L-A,F-A,A*2,A*2),o.restore()}}}drawGrid(e,r,n){if(c(this,pr)===void 0)return;const i=c(this,pr).getContext("2d");i.fillStyle=c(this,Xr).background,i.fillRect(0,0,c(this,Oe).width,c(this,Oe).height);const s=this.getSources();let o=0,a=0;for(;o<c(this,Oe).height-5;){let d=0;for(;d<c(this,Oe).width-5&&a<n;){const h=s[a].element;if(s[a].enabled){const[p,f,g,E,v,R,A,L]=yM(d,o,e,r,h.videoWidth,h.videoHeight);i.drawImage(h,p,f,g,E,v,R,A,L)}else this.drawEmptyTile(a,e,r,s[a].displayText);a+=1,d+=e}o+=r}}calcGridElemSize(e){switch(e){case 0:case 1:return[c(this,Oe).width,c(this,Oe).height];case 2:return[Math.floor(c(this,Oe).width/2),c(this,Oe).height];case 3:case 4:return[Math.floor(c(this,Oe).width/2),Math.floor(c(this,Oe).height/2)];case 5:case 6:return[Math.floor(c(this,Oe).width/3),Math.floor(c(this,Oe).height/2)];case 7:case 8:case 9:return[Math.floor(c(this,Oe).width/3),Math.floor(c(this,Oe).height/3)];default:return[Math.floor(c(this,Oe).width/3),Math.floor(c(this,Oe).height/2)]}}paintCanvas(){const e=this.getSources().length,[r,n]=this.calcGridElemSize(e);this.drawGrid(r,n,e)}isSupported(){return!!window.chrome&&document.pictureInPictureEnabled}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),c(this,yt))try{document.body.removeChild(c(this,yt))}catch(e){}this.removeAllSources(),T(this,pr,void 0),T(this,Qr,void 0),T(this,Zr,void 0)}init({height:e,width:r}={}){this.createCanvas(),this.setupMediaSessionEvents();const n=document.createElement("video");T(this,Oe,{height:e!=null?e:cg,width:r!=null?r:dg}),n.height=c(this,Oe).height,n.width=c(this,Oe).width,n.autoplay=!0,n.muted=!0,n.srcObject=c(this,pr).captureStream(24),T(this,Qr,n),c(this,Qr).onloadedmetadata=()=>{try{this.emit("pipStarted"),c(this,Qr).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch(i){this.emit("pipEnded")}},this.createVideoContainer(),this.paintCanvas()}updateMediaSession(e,r){navigator.mediaSession!==void 0&&(e==="CAMERA"&&navigator.mediaSession.setCameraActive!==void 0&&navigator.mediaSession.setCameraActive(r),e==="MIC"&&navigator.mediaSession.setMicrophoneActive!==void 0&&navigator.mediaSession.setMicrophoneActive(r))}enableSource(e){c(this,er)[e]!==void 0&&(c(this,er)[e].enabled=!0)}disableSource(e){c(this,er)[e]!==void 0&&(c(this,er)[e].enabled=!1)}addSource(e,r,n,i=!1,s=void 0){i&&this.removePinnedSource(),c(this,er)[e]={id:e,element:r,enabled:n,pinned:i,displayText:s?vM(s):void 0}}removeSource(e){delete c(this,er)[e]}removePinnedSource(){const[e]=this.getSources();e&&this.removeSource(e.id)}removeAllSources(){T(this,er,{})}enable(){this.setupEventListeners(),this.updateMediaSession("CAMERA",c(this,ze).videoEnabled),this.updateMediaSession("MIC",c(this,ze).audioEnabled),document.body.appendChild(c(this,yt)),T(this,Zr,requestAnimationFrame(()=>this.animate())),c(this,Qr).requestPictureInPicture()}}pr=new WeakMap,zs=new WeakMap,yt=new WeakMap,Qr=new WeakMap,Oe=new WeakMap,Xr=new WeakMap,Zr=new WeakMap,er=new WeakMap,ze=new WeakMap;var $n={},qa={},SM=Lu&&Lu.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(qa,"__esModule",{value:!0}),qa.Logger=void 0;const Ji=SM(or),qi="awaitqueue";class TM{constructor(e){e?(this._debug=(0,Ji.default)(`${qi}:${e}`),this._warn=(0,Ji.default)(`${qi}:WARN:${e}`),this._error=(0,Ji.default)(`${qi}:ERROR:${e}`)):(this._debug=(0,Ji.default)(qi),this._warn=(0,Ji.default)(`${qi}:WARN`),this._error=(0,Ji.default)(`${qi}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}}qa.Logger=TM,Object.defineProperty($n,"__esModule",{value:!0});var Ki=$n.AwaitQueue=$n.AwaitQueueRemovedTaskError=$n.AwaitQueueStoppedError=void 0;const kM=qa,en=new kM.Logger;class Nl extends Error{constructor(e){super(e!=null?e:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Nl)}}$n.AwaitQueueStoppedError=Nl;class Ka extends Error{constructor(e){super(e!=null?e:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Ka)}}$n.AwaitQueueRemovedTaskError=Ka;class _M{constructor(){this.pendingTasks=new Map,this.nextTaskId=0,this.stopping=!1}get size(){return this.pendingTasks.size}push(e,r){return u(this,null,function*(){if(r=r!=null?r:e.name,en.debug(`push() [name:${r}]`),typeof e!="function")throw new TypeError("given task is not a function");if(r)try{Object.defineProperty(e,"name",{value:r})}catch(n){}return new Promise((n,i)=>{const s={id:this.nextTaskId++,task:e,name:r,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:o=>{if(s.completed)return;s.completed=!0,this.pendingTasks.delete(s.id),en.debug(`resolving task [name:${s.name}]`),n(o);const[a]=this.pendingTasks.values();a&&!a.executedAt&&this.execute(a)},reject:o=>{if(!s.completed&&(s.completed=!0,this.pendingTasks.delete(s.id),en.debug(`rejecting task [name:${s.name}]: %s`,String(o)),i(o),!this.stopping)){const[a]=this.pendingTasks.values();a&&!a.executedAt&&this.execute(a)}}};this.pendingTasks.set(s.id,s),this.pendingTasks.size===1&&this.execute(s)})})}stop(){en.debug("stop()"),this.stopping=!0;for(const e of this.pendingTasks.values())en.debug(`stop() | stopping task [name:${e.name}]`);this.stopping=!1}remove(e){en.debug(`remove() [taskIdx:${e}]`);const r=Array.from(this.pendingTasks.values())[e];if(!r){en.debug(`stop() | no task with given idx [taskIdx:${e}]`);return}r.reject(new Ka)}dump(){const e=Date.now();let r=0;return Array.from(this.pendingTasks.values()).map(n=>({idx:r++,task:n.task,name:n.name,enqueuedTime:n.executedAt?n.executedAt-n.enqueuedAt:e-n.enqueuedAt,executionTime:n.executedAt?e-n.executedAt:0}))}execute(e){return u(this,null,function*(){if(en.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{const r=yield e.task();e.resolve(r)}catch(r){e.reject(r)}})}}Ki=$n.AwaitQueue=_M;var za;class lg{constructor(){m(this,"meetingTitle"),m(this,"roomName"),m(this,"roomUUID"),_(this,za,void 0),m(this,"context"),m(this,"authToken"),m(this,"maxPreferredStreams"),m(this,"roomJoined")}get peerId(){return this.context.getValue("peerId")}get sfuHandler(){return c(this,za)}get socketState(){return{state:void 0,reconnected:!1,reconnectionAttempt:void 0}}get mediaState(){return c(this,za).transportState}reconnect(){throw new C("Method not implemented.")}partialJoinRoom(e,r,n=!1,i=void 0){return u(this,null,function*(){throw new C("Method not implemented.")})}joinRoom(e,r){return u(this,arguments,function*(n,i,s={},o=!1,a=!1){throw new C("Method not implemented.")})}leaveRoom(){return u(this,null,function*(){throw new C("Method not implemented.")})}reset(e=!0){throw new C("Method not implemented")}handleSocketCallbacks(e){return u(this,null,function*(){throw new C("Method not implemented.")})}handleSockets(e,r){return u(this,null,function*(){throw new C("Method not implemented.")})}shareMic(e){return u(this,null,function*(){throw new C("Method not implemented.")})}shareWebcam(e){return u(this,null,function*(){throw new C("Method not implemented.")})}shareScreen(e){return u(this,null,function*(){throw new C("Method not implemented.")})}unmuteSelf(){return u(this,null,function*(){throw new C("Method not implemented.")})}muteSelf(){return u(this,null,function*(){throw new C("Method not implemented.")})}pauseWebcam(){return u(this,null,function*(){throw new C("Method not implemented.")})}disableScreenShare(){return u(this,null,function*(){throw new C("Method not implemented.")})}acceptWaitingRequest(e){return u(this,null,function*(){throw new C("Method not implemented.")})}rejectWaitingRequest(e){return u(this,null,function*(){throw new C("Method not implemented.")})}muteAll(e){return u(this,null,function*(){throw new C("Method not implemented.")})}muteAllVideo(){return u(this,null,function*(){throw new C("Method not implemented.")})}disableAudio(e){return u(this,null,function*(){throw new C("Method not implemented.")})}disableVideo(e){return u(this,null,function*(){throw new C("Method not implemented.")})}kickAll(){return u(this,null,function*(){throw new C("Method not implemented.")})}kick(e){return u(this,null,function*(){throw new C("Method not implemented.")})}pinPeer(e){return u(this,null,function*(){throw new C("Method not implemented.")})}getConsumers(){throw new C("Method not implemented.")}stopAllProducers(){throw new C("Method not implemented.")}activatePeers(e){return u(this,null,function*(){throw new C("Method not implemented.")})}deactivatePeers(e){return u(this,null,function*(){throw new C("Method not implemented.")})}switchConsumersToLayer(e,r){return u(this,null,function*(){throw new C("Method not implemented.")})}}za=new WeakMap;var Pr=(t=>(t.INITIALIZING="INITIALIZING",t.INITIALIZED="INITIALIZED",t.NOT_INITIALIZED="NOT_INITIALIZED",t))(Pr||{});class ug extends _t.EventEmitter{}class Gn extends _t.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}safeEmit(e,...r){const n=this.listenerCount(e);try{return this.emit(e,...r)}catch(i){return l.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:i}),Boolean(n)}}safeEmitAsPromise(e,...r){return u(this,null,function*(){const n={}.EVENT_PROMISE_TIMEOUT?parseInt({}.EVENT_PROMISE_TIMEOUT,10):1e4;return this.safeEmitAsPromiseWithTimeout(e,n,...r)})}safeEmitAsPromiseWithTimeout(e,r,...n){return u(this,null,function*(){return new Promise((i,s)=>{setTimeout(s,r,"event request timeout");try{this.emit(e.toString(),...n,i,s)}catch(o){l.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:o}),s(o)}})})}}function bM(t,e){const r=new Error(e);return r.name=t,r}class Jn extends C{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Jn):this.stack=new Error(e).stack}}class it extends C{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,it):this.stack=new Error(e).stack}}var Ya,Qa,Xa,Za,Ar,ec,tc,mr,zi,rc,nc,ic,Ll,xl,hg,Fl,pg;class mg extends Gn{constructor({id:e,localId:r,producerId:n,producingPeerId:i,producingTransportId:s,handler:o,track:a,appData:d,paused:h,reuseTrack:p,rtpReceiver:f}){super(),_(this,ic),_(this,xl),_(this,Fl),m(this,"rtpReceiver"),m(this,"observer"),_(this,Ya,void 0),_(this,Qa,void 0),_(this,Xa,void 0),_(this,Za,void 0),_(this,Ar,void 0),_(this,ec,void 0),_(this,tc,void 0),_(this,mr,void 0),_(this,zi,void 0),_(this,rc,void 0),_(this,nc,void 0),T(this,Ya,e),T(this,Qa,r),T(this,tc,o),T(this,nc,d),T(this,rc,i),T(this,Za,s),T(this,Ar,!1),T(this,Xa,n),T(this,mr,a),T(this,zi,h!=null?h:!1),T(this,ec,p),this.observer=new Gn,this.rtpReceiver=f,ue(this,xl,hg).call(this)}get id(){return c(this,Ya)}get peerId(){return c(this,rc)}get localId(){return c(this,Qa)}get producerId(){return c(this,Xa)}get producingTransportId(){return c(this,Za)}get closed(){return c(this,Ar)}get kind(){return c(this,mr).kind}get track(){return c(this,mr)}get paused(){return c(this,zi)}get remotelyPaused(){return this.paused}get appData(){return c(this,nc)}close(e){c(this,Ar)||(l.debug("Consumer::close() with reason:",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,closureReason:e,kind:this.kind}}),T(this,Ar,!0),c(this,ec)||ue(this,Fl,pg).call(this),this.emit("close",e),this.observer.safeEmit("close",e))}getStats(){return u(this,null,function*(){if(c(this,Ar))throw new it("closed");return c(this,tc).getReceiverStats(this.localId)})}pause(){if(l.debug("consumer::pause()",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}),c(this,Ar)){l.error("consumer::pause() | Consumer closed",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}});return}T(this,zi,!0),c(this,mr).enabled=!1,this.observer.safeEmit("pause")}resume(){if(l.debug("consumer::resume()",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}),c(this,Ar)){l.error("Consumer::resume() | Consumer closed",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}});return}T(this,zi,!1),c(this,mr).enabled=!0,this.observer.safeEmit("resume")}}Ya=new WeakMap,Qa=new WeakMap,Xa=new WeakMap,Za=new WeakMap,Ar=new WeakMap,ec=new WeakMap,tc=new WeakMap,mr=new WeakMap,zi=new WeakMap,rc=new WeakMap,nc=new WeakMap,ic=new WeakSet,Ll=function(){l.debug('Consumer::track "ended" event',{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}),this.safeEmit("trackended"),this.observer.safeEmit("trackended")},xl=new WeakSet,hg=function(){c(this,mr).addEventListener("ended",ue(this,ic,Ll).bind(this))},Fl=new WeakSet,pg=function(){try{c(this,mr).removeEventListener("ended",ue(this,ic,Ll)),c(this,mr).stop()}catch(t){l.error("Consumer::destroyTrack()",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind},error:t})}};let wM=class extends mg{};const fg=t=>new Promise(e=>setTimeout(e,t));function fr(t,e){return u(this,null,function*(){return new Promise((r,n)=>u(this,null,function*(){const{strategy:i,maxRetryCount:s,delayTime:o}=V({strategy:"linear",maxRetryCount:3,delayTime:10},e);let a=0,d,h=!1;const p=f=>{h=!0,n(f)};for(;a<s;){try{const f=yield t(a,p);return r(f)}catch(f){if(d=f,h)break;if(a<s)i==="linear"?yield fg(o*(a+1)):i==="exponential"&&(yield fg(o*(a+Math.max(0,a-1))));else break}a+=1}return n(d)}))})}function sc(t){if(Promise.allSettled)return Promise.allSettled(t);const e=t.map(r=>r.then(n=>({status:"fulfilled",value:n})).catch(n=>({status:"rejected",reason:n})));return Promise.all(e)}function CM(t,e){return typeof t=="undefined"?e:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(t):JSON.parse(JSON.stringify(t))}function gg(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function Ul(t){return Math.random().toString(36).substring(2,2+t)}const oc=1;function vg(t){const e=t;return delete e.payload._bolt,e}function IM(t){return t.payload&&gg(t.payload)}function ac(t){var e,r;return IM(t)&&(r=(e=t.payload._bolt)==null?void 0:e.id)!=null?r:""}var qn;const Ys=class extends _t.EventEmitter{constructor(t,e,r){super(),m(this,"channel"),m(this,"queue"),m(this,"serverProtocolVersion"),_(this,qn,new Map),m(this,"respond",(n,i,s=!1)=>{let o;s?o=Ys.createErrorResponse(n,i):o=Ys.createResponse(n,i),this.channel.send(JSON.stringify(o))}),m(this,"notify",n=>{const i=Ys.createNotification(n);this.channel.send(JSON.stringify(i))}),m(this,"request",n=>u(this,null,function*(){const i=Ys.createRequest(n),s=new Promise((o,a)=>{const d=1e3*(5+.1*this.queue.size),{id:h}=i.payload._bolt,p={id:h,method:i.type,resolve:f=>{this.queue.delete(h)&&(clearTimeout(p.timer),o(f))},timer:setTimeout(()=>{this.queue.delete(h)&&a(new Error(`request timeout for message id: ${h}`))},d),cancel:f=>{this.queue.delete(h)&&(clearTimeout(p.timer),a(f))}};this.queue.set(h,p)});return this.channel.send(JSON.stringify(i)),s})),m(this,"send",n=>{const i=JSON.stringify(n),s=16384;if(i.length>s){const o=s-200,a=Math.ceil(i.length/o),d=[];for(let p=0;p<a;p+=1){const f=p*o,g=(p+1)*o;d.push(i.slice(f,g))}const h=gn();for(let p=0;p<a;p+=1){const f=d[p],g=JSON.stringify({id:h,count:a,chunkIndex:p,chunk:f});l.debug(`Sending message chunk over dc: ${g}`),this.channel.send(g)}}else l.debug(`Sending message over dc: ${i}`),this.channel.send(i)}),m(this,"processMessage",n=>{var i;c(this,qn).has(n.id)||c(this,qn).set(n.id,[]);const s=c(this,qn).get(n.id);if(s[n.chunkIndex]=n,(s==null?void 0:s.length)===n.count&&!s.some(o=>o===void 0)){const o=c(this,qn).get(n.id),a=o==null?void 0:o.reduce((h,p)=>h+p.chunk,"");c(this,qn).delete(n.id);const d=JSON.parse(a);if(!d.payload||!gg(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=(i=d.payload._bolt)==null?void 0:i.version,!this.processResponseMsg(d))return d}}),m(this,"processResponseMsg",n=>{const{id:i}=n.payload._bolt,s=this.queue.get(i);return s?(l.debug(`resolving pending request with id: ${i}, complete response: ${JSON.stringify(n)}`),n.type==="error"?s.cancel(vg(n)):s.resolve(vg(n)),!0):!1}),m(this,"processBoltHandshake",n=>{var i,s;return n.type==="_bolt"||n.type==="handshake"?(this.respond((s=(i=n.payload._bolt)==null?void 0:i.id)!=null?s:Ul(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1}),this.label=e,this.transportId=r,this.channel=t,this.queue=new Map}};let Qs=Ys;qn=new WeakMap,m(Qs,"createRequest",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:ne(V({},t.payload),{_bolt:{id:Ul(8),type:"REQUEST",version:oc}})}}),m(Qs,"createResponse",(t,e)=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:ne(V({},e.payload),{_bolt:{id:t,type:"RESPONSE",version:oc}})}}),m(Qs,"createNotification",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:ne(V({},t.payload),{bolt:{id:Ul(8),type:"NOTIFY",version:oc}})}}),m(Qs,"createErrorResponse",(t,e)=>({type:"error",payload:{error:e.message,_bolt:{id:t,type:"RESPONSE",version:oc}}}));const Vl="transport closed";class yg extends Gn{constructor({id:e,direction:r,handlerFactory:n,iceServers:i,iceTransportPolicy:s,proprietaryConstraints:o,additionalSettings:a,appData:d,config:h}){var p,f;super(),m(this,"awaitQueue"),m(this,"observer"),m(this,"id"),m(this,"serverId"),m(this,"closed",!1),m(this,"direction"),m(this,"maxSctpMessageSize"),m(this,"handler"),m(this,"connectionState","new"),m(this,"producers"),m(this,"consumers"),m(this,"datachannels"),m(this,"connected",!1),m(this,"eventsDCReadyPromise"),m(this,"eventsDCReadyPromiseResolver"),m(this,"eventsDCFailureTimer"),m(this,"transportConnectionPromise"),m(this,"consumerTrackEvents"),m(this,"unknownTracksMap"),m(this,"consumerTrackPool"),m(this,"appData"),l.debug(`constructor() [id: ${e}, direction: ${r}]`),this.id=e,this.direction=r;const g=CM(a,{});delete g.iceServers,delete g.iceTransportPolicy,delete g.bundlePolicy,delete g.rtcpMuxPolicy,delete g.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.consumerTrackPool=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new Ki,this.observer=new Gn,this.handler=n(),this.handler._enableHighBitrate=(p=h==null?void 0:h.enableHighBitrate)!=null?p:!1,this.handler._enableStereo=(f=h==null?void 0:h.enableStereo)!=null?f:!1,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:r,iceServers:i,iceTransportPolicy:s,additionalSettings:a,proprietaryConstraints:o}),this.appData=d||{},this.transportConnectionPromise=new Promise(E=>{this.observer.once("connected",()=>{E(!0)}),this.observer.once("disconnect",()=>{E(!1)}),this.observer.once("close",()=>{E(!1)})}),this.eventsDCReadyPromise=new Promise(E=>{this.eventsDCReadyPromiseResolver=E}),this.handler.on("@connectionstatechange",E=>{E!==this.connectionState&&(l.debug(`connection state changed to ${E}`),this.connectionState=E,E==="connected"&&(this.connected=!0,this.observer.emit("connected")),E==="disconnected"&&(this.connected=!1,this.observer.emit("disconnect")),(E==="failed"||E==="closed")&&(this.connected=!1,this.observer.emit("close")),this.closed||this.safeEmit("connectionstatechange",E))}),this.handler.on("@icecandidate",({candidate:E})=>{this.closed||this.safeEmit("icecandidate",E)}),this.handler.on("dc_open",E=>{let v=this.datachannels.get(E.label);v||(v||(v=new Qs(E,E.label,this.serverId),this.datachannels.set(E.label,v)),this.eventsDCFailureTimer=setTimeout(()=>{E.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",E.label))},5e3))}),this.handler.on("datachannel",(E,v)=>{E.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const R=this.datachannels.get(E.label);if(!R){l.error("unregistered datachannel for message",{rtcChannel:{label:E.label,message:v}});return}try{const A=JSON.parse(v);l.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:A.id,count:A.count,chunkIndex:A.chunkIndex,chunk:A.chunk,transprtId:this.serverId}});const L=R.processMessage(A);if(!L)return;l.debug(`datachannel message with id:${A.id} on transport:${this.serverId}complete - ${JSON.stringify(L)}`),this.emit(`datachannel:${E.label}`,R.label,L)}catch(A){l.error("error parsing message",{error:A})}})}get isConnected(){return this.transportConnectionPromise}setServerId(e){this.serverId=e}getDatachannel(e){return this.datachannels.get(e)}get isEventsDCReady(){return this.eventsDCReadyPromise}close(){this.closed||(l.debug("close()"),this.connected=!1,this.closed=!0,this.handler.close(),Array.from(this.producers.values()).forEach(e=>{e.close(Vl).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(Vl)}),this.consumers.clear(),this.consumerTrackPool.clear(),this.consumerTrackEvents.clear(),this.emit("close"),this.observer.emit("close"))}getStats(){return u(this,null,function*(){if(this.closed)throw new it("closed");return this.handler.getTransportStats()})}restartIce(){return u(this,null,function*(){if(l.debug("restartIce()"),this.closed)throw new it("closed");return this.handler.restartIce()})}updateIceServers(){return u(this,arguments,function*({iceServers:e}={}){if(l.debug("updateIceServers()"),this.closed)throw new it("closed");return this.handler.updateIceServers(e)})}setRemoteOffer(e){return u(this,null,function*(){yield this.setRemoteDescription(e);const r=yield this.handler.pc.createAnswer(),n=Kc(r.sdp);return n.media=n.media.map(i=>{if(i.type==="audio"){const s=V({},i),o=s.fmtp.find(a=>a.payload===111);return o&&(o.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}),r.sdp=ny(n),yield this.setLocalDescription(r),r})}sendErrorOverDC(e,r,n){const i=this.getDatachannel(e);if(!i)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});i.respond(r,n,!0)}sendResponseOverDC(e,r,n){const i=this.getDatachannel(e);if(!i)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});i.respond(r,n)}setRemoteDescription(e){return u(this,null,function*(){yield this.handler.pc.setRemoteDescription(e)})}setLocalDescription(e){return u(this,null,function*(){l.debug(`${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),yield this.handler.pc.setLocalDescription(e)})}createConsumerOverDC(e){return u(this,null,function*(){const r=this.getDatachannel("events");if(!r)throw bM("DC_NOT_READY","events datachannel not ready");if(e.length===0)throw new Error("one of producer id or publisher id is required");const n={type:"create_consumer",payload:{}};e.length===1?n.payload={producerId:e[0].producerId,publisherId:e[0].producingTransportId}:n.payload={publisherId:e[0].producingTransportId};const i=new Map;e.forEach(a=>i.set(a.producerId,a));const s=(yield r.request(n)).payload,o=new Map;return Object.entries(s).forEach(([a,d])=>{const h=i.get(d.producerId);if(!h){l.error(`unknown entry in create consumer response, producerId: ${d.producerId}`,{consumerState:d});return}o.set(d.producerId,{consumerId:a,producingTransportId:h.producingTransportId,kind:h.kind,paused:h.pause,streamId:d.streamId,trackId:d.trackId,screenShare:h.screenShare,appData:{}})}),l.info(`createConsumerOverDC::response ${JSON.stringify(s)}`),o})}}class Eg extends Gn{constructor({id:e,localId:r,track:n,stopTracks:i,disableTrackOnPause:s,zeroRtpOnPause:o,handler:a,appData:d,rtpSender:h}){super(),m(this,"_id"),m(this,"_localId"),m(this,"_closed",!1),m(this,"_handler"),m(this,"_track"),m(this,"_kind"),m(this,"_paused"),m(this,"_maxSpatialLayer"),m(this,"_stopTracks"),m(this,"_disableTrackOnPause"),m(this,"_zeroRtpOnPause"),m(this,"_appData"),m(this,"observer"),m(this,"rtpSender"),this._id=e,this._localId=r,this._track=n,this._kind=n.kind,this._paused=s?!n.enabled:!1,this._maxSpatialLayer=void 0,this._stopTracks=i,this._disableTrackOnPause=s,this._zeroRtpOnPause=o,this._appData=d||{},this._onTrackEnded=this._onTrackEnded.bind(this),this._handler=a,this.rtpSender=h,this.observer=new Gn,this._handleTrack()}get id(){return this._id}get localId(){return this._localId}get closed(){return this._closed}get kind(){return this._kind}get track(){return this._track}get paused(){return this._paused}get maxSpatialLayer(){return this._maxSpatialLayer}get appData(){return this._appData}set appData(e){throw new Error("cannot override appData object")}close(e){return u(this,null,function*(){if(this._closed)return;if(l.debug("Producer::close() with reason:"),this._closed=!0,this._destroyTrack(),e===Vl){this.observer.emit("close");return}const{offerSdp:r,callback:n}=yield this._handler.stopSending(this.localId);this.observer.emit("close");const{answer:i}=yield this.safeEmitAsPromise("close",{offer:r,reason:e});n(i)})}getStats(){return u(this,null,function*(){if(this._closed)throw new it("closed");return this._handler.getSenderStats(this.localId)})}pause(){l.debug("Producer::pause()",{producer:{id:this.id,appData:this.appData,kind:this.kind}}),this._closed&&l.error("Producer::pause() | Producer closed",{producer:{id:this.id,appData:this.appData,kind:this.kind}}),this._paused=!0,this._track&&this._disableTrackOnPause&&(this._track.enabled=!1),this._zeroRtpOnPause&&this._handler.replaceTrack(this.localId,null),this.observer.emit("pause")}resume(){if(l.debug("Producer::resume()",{producer:{id:this.id,appData:this.appData,kind:this.kind}}),this._closed){l.error("Producer::resume() | Producer closed",{producer:{id:this.id,appData:this.appData,kind:this.kind}});return}this._paused=!1,this._track&&this._disableTrackOnPause&&(this._track.enabled=!0),this._zeroRtpOnPause&&this._handler.replaceTrack(this.localId,this._track),this.observer.emit("resume")}replaceTrack(e){return u(this,arguments,function*({track:r}){if(l.debug("Producer::replaceTrack()",{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:r==null?void 0:r.id}}),this._closed){if(r&&this._stopTracks)try{r.stop()}catch(n){l.error("Producer::replaceTrack",{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:r==null?void 0:r.id},error:n})}throw new it("closed")}else if(r&&r.readyState==="ended")throw new it("track ended");if(r===this._track){l.debug("replaceTrack() | same track, ignored",{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:r==null?void 0:r.id}});return}(!this._zeroRtpOnPause||!this._paused)&&(yield this._handler.replaceTrack(this.localId,r)),this._destroyTrack(),this._track=r,this._handleTrack()})}setMaxSpatialLayer(e){return u(this,null,function*(){if(this._closed)throw new it("closed");if(this._kind!=="video")throw new Jn("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");yield this._handler.setMaxSpatialLayer(this.localId,e),this._maxSpatialLayer=e})}setRtpEncodingParameters(e){return u(this,null,function*(){if(this._closed)throw new it("closed");if(typeof e!="object")throw new TypeError("invalid params");yield this._handler.setRtpEncodingParameters(this.localId,e)})}_onTrackEnded(){l.debug('Producer::track "ended" event',{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:this.track.id}}),this.observer.emit("trackended"),this.safeEmit("trackended",this.track.id)}_handleTrack(){this._track&&this._track.addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(this._track)try{this._track.removeEventListener("ended",this._onTrackEnded),this._stopTracks&&this._track.stop()}catch(r){l.error("Producer::_destroyTrack",{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:(e=this._track)==null?void 0:e.id},error:r})}}}let RM=class extends Eg{},PM=class extends yg{consume(t){return u(this,null,function*(){const{producers:e,producingPeerId:r,consumeOverDC:n}=t;if(l.debug(`consume() peerId: ${r}, producers: ${JSON.stringify(e)}`),this.closed)throw new it("closed");if(this.direction!=="recv")throw new Jn("not a receiving Transport");if(typeof t.producingPeerId!="string")throw new TypeError("missing producingPeerId");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(!(yield this.isConnected))return Promise.reject(new Error("Transport not connected"));const i=[];let s;if(n)s=yield this.createConsumerOverDC(e);else{const o={producingPeerId:r};e.length===1&&(o.producerId=e[0].producerId);const{consumersMap:a}=yield this.safeEmitAsPromise("consume_peer",V({},o));s=a}return s.forEach((o,a)=>{const{consumerId:d,trackId:h,screenShare:p,paused:f,streamId:g,kind:E,appData:v,producingTransportId:R}=o;i.push(this.consumerCreationTask({consumerId:d,trackId:h,streamId:g,kind:E,producerId:a,producingPeerId:r,producingTransportId:R,paused:f,screenShare:p,appData:v}))}),sc(i)})}connect(){return u(this,null,function*(){try{const{offerSdp:t,callback:e}=yield this.handler.connect(),{answer:r}=yield this.safeEmitAsPromise("connect",{offer:t});if(yield e(r),!(yield this.isConnected))throw new Error("ice connection failed");if(!(yield this.isEventsDCReady))throw new Error("events datachannel not open")}catch(t){throw l.error("transport failed to connect:",t),t}})}_ontrack(t){const{track:e,transceiver:r,streams:n}=t;l.info(`track event received [trackId: ${e.id}]`);const i=`${n[0].id}:${e.kind}`;e.addEventListener("ended",()=>{l.info(`rtc consumer track ended [trackId: ${e.id}]`),this.consumerTrackPool.delete(e.id),this.unknownTracksMap.delete(i)}),this.consumerTrackPool.set(e.id,[e,r]);const s=this.consumerTrackEvents.get(i);s?(s(e,r),this.consumerTrackEvents.delete(i)):(l.warn(`track event handler not found ${i}`),this.unknownTracksMap.set(i,t))}consumerCreationTask(t){return u(this,arguments,function*({consumerId:e,producerId:r,producingPeerId:n,producingTransportId:i,streamId:s,trackId:o,paused:a,screenShare:d,appData:h,kind:p}){const f=`${s}:${p}`,g={consumerId:e,producerId:r,producingPeerId:n,producingTransportId:i,streamId:s,trackId:o,appData:h,kind:p,paused:a,screenShare:d,name:"consumer creation task error",message:"consumer creation failed"};return new Promise((E,v)=>{const R=setTimeout(()=>{this.consumerTrackEvents.delete(f),g.isTimedout=!0,v(g)},5e3),A=(W,H)=>{try{if(W.readyState==="ended")clearTimeout(R),v(g);else{const I=W;I.enabled=!0,this.handler.midTransceiverMap.set(H.mid,H);const S=new wM({id:e,localId:H.mid,track:I,paused:a,producerId:r,producingPeerId:n,producingTransportId:i,handler:this.handler,appData:ne(V({},h),{screenShare:d,peerId:n}),reuseTrack:!0,rtpReceiver:H.receiver});this.consumers.set(e,S),S.once("close",()=>{this.consumers.delete(S.id),this.handler.midTransceiverMap.delete(H.mid)}),l.info("consumer created for ",{consumer:{id:e,kind:p,appData:{screenShare:d},peerId:n,producerId:r}}),this.observer.emit("newconsumer",S),clearTimeout(R),E(S)}}catch(I){l.warn("error while creating consumer:",I),clearTimeout(R),v(g)}},L=this.consumerTrackPool.get(e);if((L==null?void 0:L.length)===2){A(L[0],L[1]);return}const F=this.unknownTracksMap.get(f);F?(this.unknownTracksMap.delete(f),A(F.track,F.transceiver)):this.consumerTrackEvents.set(f,A)})})}retryFailedConsumerCreationTasks(t){return u(this,null,function*(){return sc(t.map(e=>u(this,null,function*(){return fr(r=>u(this,null,function*(){return r>0&&l.warn(`retrying failed consumer creation task: ${JSON.stringify(e)}`),this.consumerCreationTask(V({},e))}))})))})}produce(){return u(this,arguments,function*({track:t,encodings:e,codecOptions:r,stopTracks:n=!0,disableTrackOnPause:i=!0,zeroRtpOnPause:s=!1,appData:o={}}={}){if(l.debug(`produce() [track:${t.id}]`),t){if(this.direction!=="send")throw new Jn("not a sending Transport");if(t.readyState==="ended")throw new it("track ended");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("produce")===0)throw new TypeError('no "produce" listener set into this transport');if(o&&typeof o!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!(yield this.isConnected))return Promise.reject(new Error("Transport not connected"));const{producerId:a,localId:d,rtpSender:h}=yield this.awaitQueue.push(()=>u(this,null,function*(){const{offerSdp:f,callback:g,sender:E,mid:v}=yield this.handler.send({track:t,encodings:e,codecOption:r,screenShare:o==null?void 0:o.screenShare}),{answer:R,producerId:A}=yield this.safeEmitAsPromise("produce",{offer:f,kind:t.kind,paused:i?!t.enabled:!1,appData:ne(V({},o||{}),{mid:v})}),L=yield g(R);return{producerId:A,localId:L,rtpSender:E}}),"producer"),p=new RM({id:a,localId:d,track:t,stopTracks:n,disableTrackOnPause:i,zeroRtpOnPause:s,appData:o,handler:this.handler,rtpSender:h});return this.producers.set(a,p),p.observer.on("close",()=>{this.producers.delete(p.id)}),this.emit("newproducer",p),this.observer.emit("newproducer",p),p})}};class Bl extends Gn{constructor(){super(),m(this,"_mapMidTransceiver",new Map),m(this,"_enableHighBitrate",!1),m(this,"_enableStereo",!1),this._mapMidTransceiver=new Map,this._enableHighBitrate=!1}get midTransceiverMap(){return this._mapMidTransceiver}}class jl extends Bl{constructor(){super(),m(this,"_direction"),m(this,"_pc"),m(this,"_sendWebStream",new MediaStream),m(this,"_sendScreenShareStream",new MediaStream),m(this,"_transportReady",!1)}static createFactory(){return()=>new jl}get name(){return"Chrome74"}get pc(){return this._pc}close(){if(l.debug("close()"),this._pc)try{this._pc.close()}catch(e){l.error("pc.close()",e)}}init({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,onTrackHandler:o}){this._direction=e,this._pc=new RTCPeerConnection(V({iceServers:r||[],iceTransportPolicy:n||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"},i),s),o&&this._pc.addEventListener("track",a=>{o(a)}),this._addEventListeners()}connect(){return u(this,null,function*(){const e=this._pc.createDataChannel("dyte"),r=yield this._pc.createOffer();return l.info(`connect offer: ${JSON.stringify(r)}`),yield this._pc.setLocalDescription(r),{offerSdp:r,callback:n=>u(this,null,function*(){l.debug(`Chrome74::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(n)}]`),yield this._pc.setRemoteDescription(n),e.close()})}})}updateIceServers(e){return u(this,null,function*(){l.debug("updateIceServers()");const r=this._pc.getConfiguration();r.iceServers=e,this._pc.setConfiguration(r)})}restartIce(){return u(this,null,function*(){l.debug("restartIce()");const e=yield this.pc.createOffer({iceRestart:!0});return l.debug(`restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:r=>u(this,null,function*(){l.info(`restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(r)}]`),yield this._pc.setRemoteDescription(r)})}})}getTransportStats(){return u(this,null,function*(){return this._pc.getStats()})}send(e){return u(this,arguments,function*({track:r,encodings:n,codecOption:i,screenShare:s}){var o;this._assertSendDirection(),l.debug(`send() [kind:${r.kind}, track.id:${r.id}]`);const a=this._pc.addTransceiver(r,{direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream],sendEncodings:n});if(!navigator.isReactNative){l.debug("creating new transceiver");const h=RTCRtpSender.getCapabilities(r.kind);l.info(`senders available params: ${JSON.stringify(h)}`);const p=[];if(i){const f=h.codecs.find(g=>g.mimeType.includes(i.name));if(i.parameters){l.info(`codecOption.parameters:${JSON.stringify(i.parameters)}`);const g=((o=f.sdpFmtpLine)==null?void 0:o.split(";"))||[];g.push(...i.parameters);const E=Array.from(new Set(g).values());f.sdpFmtpLine=E.join(";")}p.push(f)}l.info(`selected codecs: ${JSON.stringify(p)}`),a.setCodecPreferences(p)}const d=yield this._pc.createOffer();if(!this._transportReady)throw new Error("webrtc transport not connected");if(yield this._pc.setLocalDescription(d),i&&i.name==="opus"){const h=this._enableStereo,p=this._enableHighBitrate?h?128e3:64e3:h?64e3:32e3;d.sdp=d.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;usedtx=1${h?"":";stereo=1;sprop-stereo=1"};maxaveragebitrate=${p}`),d.sdp+=`a=rtcp-fb:111 nack\r
20
- `}return{offerSdp:d,callback:h=>u(this,null,function*(){return l.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),yield this._pc.setRemoteDescription(h),this.midTransceiverMap.set(a.mid,a),a.mid}),sender:a.sender,mid:a.mid}})}stopSending(e){return u(this,null,function*(){this._assertSendDirection(),l.debug(`stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.sender.replaceTrack(null),this._pc.removeTrack(r.sender),r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}replaceTrack(e,r){return u(this,null,function*(){this._assertSendDirection(),r?l.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):l.debug(`replaceTrack() [localId:${e}, no track]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");yield n.sender.replaceTrack(r)})}setMaxSpatialLayer(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,o)=>{o<=r?s.active=!0:s.active=!1}),yield n.sender.setParameters(i)})}setRtpEncodingParameters(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,o)=>{i.encodings[o]=V(V({},s),r)}),yield n.sender.setParameters(i)})}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}stopReceiving(e){return u(this,null,function*(){throw this._assertRecvDirection(),l.debug(`stopReceiving() [localId:${e}]`),Error("method not implemented")})}pauseReceiving(e){return u(this,null,function*(){throw this._assertRecvDirection(),l.debug(`pauseReceiving() [localId:${e}]`),Error("method not implemented")})}resumeReceiving(e){return u(this,null,function*(){throw this._assertRecvDirection(),l.debug(`resumeReceiving() [localId:${e}]`),Error("method not implemented")})}getReceiverStats(e){return u(this,null,function*(){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.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')}_generateOffer(){return u(this,null,function*(){const e=yield this._pc.createOffer();return yield this._pc.setLocalDescription(e),e})}_setAnswer(e){return u(this,null,function*(){l.debug(`setAnswer() | calling pc.setRemoteDescription() [answer:${JSON.stringify(e)}]`),yield this._pc.setRemoteDescription(e)})}_addEventListeners(){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:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this._pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),l.debug("negotiationneeded")}),this._pc.addEventListener("icegatheringstatechange",()=>{switch(this._pc.iceGatheringState){case"gathering":l.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":l.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidateerror",e=>{l.error("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this._pc.addEventListener("datachannel",e=>{l.info("data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{l.info("data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{l.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{l.error("data channel error: ",{rtcChannel:{label:e.channel.label}})},r.onmessage=n=>{this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(n.data)))}})}}class cc extends Bl{constructor(e){super(),m(this,"_direction"),m(this,"_pc"),m(this,"_sendWebStream",new MediaStream),m(this,"_sendScreenShareStream",new MediaStream),m(this,"_transportReady",!1),m(this,"supportsSendEncodings",!1),this.supportsSendEncodings=e.supportsSendEncodings}static createFactory(e){return()=>new cc(e)}get name(){return"Firefox60"}get pc(){return this._pc}close(){if(l.debug("Firefox60::close()"),this._pc)try{this._pc.close()}catch(e){l.error("Firefox60::pc.close()",{error:e})}}init({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,onTrackHandler:o}){l.debug("Firefox60::init()"),this._direction=e,this._pc=new RTCPeerConnection(V({iceServers:r||[],iceTransportPolicy:n||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"},i),s),o&&this._pc.addEventListener("track",a=>{o(a)}),this._addEventListeners()}connect(){return u(this,null,function*(){const e=this._pc.createDataChannel("dyte"),r=yield this._pc.createOffer();return l.info(`Firefox60::connect offer: ${JSON.stringify(r)}`),yield this._pc.setLocalDescription(r),{offerSdp:r,callback:n=>u(this,null,function*(){l.debug(`Firefox60::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(n)}]`),yield this._pc.setRemoteDescription(n),e.close()})}})}updateIceServers(e){return u(this,null,function*(){throw l.debug("Firefox60::updateIceServers()"),new Error("not supported")})}restartIce(){return u(this,null,function*(){l.debug("Firefox60::restartIce()");const e=yield this.pc.createOffer({iceRestart:!0});return l.debug(`Firefox60::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:r=>u(this,null,function*(){l.info(`Firefox60::restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(r)}]`),yield this._pc.setRemoteDescription(r)})}})}getTransportStats(){return u(this,null,function*(){return this._pc.getStats()})}send(e){return u(this,arguments,function*({track:r,encodings:n,screenShare:i}){this._assertSendDirection(),l.debug(`Firefox60::send() [kind:${r.kind}, track.id:${r.id}]`),l.debug("Firefox60::creating new transceiver");const s=this.supportsSendEncodings&&n!==void 0?{sendEncodings:n}:{},o=this._pc.addTransceiver(r,V({direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream]},s));if(!this.supportsSendEncodings&&n){n.reverse();const d=o.sender.getParameters();d.encodings=n,yield o.sender.setParameters(d)}const a=yield this._pc.createOffer();if(!this._transportReady)throw new Error("webrtc transport not connected");if(yield this._pc.setLocalDescription(a),r.kind==="audio"){const d=this._enableStereo,h=this._enableHighBitrate?d?128e3:64e3:d?64e3:32e3;a.sdp=a.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;usedtx=1${this.supportsSendEncodings?"":`${d?"":";stereo=1;sprop-stereo=1"};maxaveragebitrate=${h}`}`)}return{offerSdp:a,callback:d=>u(this,null,function*(){return l.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),yield this._pc.setRemoteDescription(d),this.midTransceiverMap.set(o.mid,o),o.mid}),sender:o.sender,mid:o.mid}})}stopSending(e){return u(this,null,function*(){this._assertSendDirection(),l.debug(`Firefox60::stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated transceiver not found");r.sender.replaceTrack(null),this._pc.removeTrack(r.sender),r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}replaceTrack(e,r){return u(this,null,function*(){this._assertSendDirection(),r?l.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):l.debug(`Firefox60::replaceTrack() [localId:${e}, no track]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");yield n.sender.replaceTrack(r)})}setMaxSpatialLayer(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters(),s=i.encodings.length-1-r;i.encodings.forEach((o,a)=>{a>=s?o.active=!0:o.active=!1}),yield n.sender.setParameters(i)})}setRtpEncodingParameters(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,o)=>{i.encodings[o]=V(V({},s),r)}),yield n.sender.setParameters(i)})}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}stopReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Firefox60::stopReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive",l.info(`Firefox60::active transcievers: ${JSON.stringify(this._pc.getTransceivers())}`);const n=yield this._pc.createOffer();return l.debug(`Firefox60::stopRecieving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`Firefox60::stopRecieving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}pauseReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Firefox60::pauseReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`pauseReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`pauseReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i)})}})}resumeReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Firefox60::resumeReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="recvonly";const n=yield this._generateOffer();return l.debug(`resumeReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`resumeReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i)})}})}getReceiverStats(e){return u(this,null,function*(){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.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')}_generateOffer(){return u(this,null,function*(){const e=yield this._pc.createOffer();return yield this._pc.setLocalDescription(e),e})}_setAnswer(e){return u(this,null,function*(){l.debug(`_setAnswer() | calling pc.setRemoteDescription() [answer:${JSON.stringify(e)}]`),yield this._pc.setRemoteDescription(e)})}_addEventListeners(){this._pc.addEventListener("datachannel",e=>{l.info("Firefox60::data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{l.info("Firefox60::data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{l.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{l.error("Firefox60::data channel error: ",{rtcChannel:{label:e.channel.label}})},r.onmessage=n=>u(this,null,function*(){const i=yield n.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(i)))})}),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:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this._pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),l.debug("Firefox60::negotiationneeded")}),this._pc.addEventListener("icegatheringstatechange",()=>{switch(this._pc.iceGatheringState){case"gathering":l.debug("Firefox60::icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":l.debug("Firefox60::icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidateerror",e=>{l.error("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})})}}class Hl extends Bl{constructor(){super(),m(this,"_direction"),m(this,"_pc"),m(this,"_sendWebStream",new MediaStream),m(this,"_sendScreenShareStream",new MediaStream),m(this,"_transportReady",!1)}static createFactory(){return()=>new Hl}get name(){return"Chrome74"}get pc(){return this._pc}close(){if(l.debug("Safari12::close()"),this._pc)try{this._pc.close()}catch(e){l.error("Safari12::pc.close()",e)}}init({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,onTrackHandler:o}){l.debug("Safari12::init()"),this._direction=e,this._pc=new RTCPeerConnection(V({iceServers:r||[],iceTransportPolicy:n||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"},i),s),o&&this._pc.addEventListener("track",a=>{o(a)}),this._addEventListeners()}connect(){return u(this,null,function*(){const e=this._pc.createDataChannel("dyte"),r=yield this._pc.createOffer();return l.info(`Safari12::connect offer: ${JSON.stringify(r)}`),yield this._pc.setLocalDescription(r),{offerSdp:r,callback:n=>u(this,null,function*(){l.debug(`Safari12::connect() | calling pc.setRemoteDescription() [answer: ${JSON.stringify(n)}]`),yield this._pc.setRemoteDescription(n),e.close()})}})}updateIceServers(e){return u(this,null,function*(){l.debug("Safari12::updateIceServers()");const r=this._pc.getConfiguration();r.iceServers=e,this._pc.setConfiguration(r)})}restartIce(){return u(this,null,function*(){l.debug("Safari12::restartIce()");const e=yield this.pc.createOffer({iceRestart:!0});return l.debug(`restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:r=>u(this,null,function*(){l.info(`restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(r)}]`),yield this._pc.setRemoteDescription(r)})}})}getTransportStats(){return u(this,null,function*(){return this._pc.getStats()})}send(e){return u(this,arguments,function*({track:r,encodings:n,codecOption:i,screenShare:s}){var o;this._assertSendDirection(),l.debug(`Safari12::send() [kind: ${r.kind}, track.id: ${r.id}]`),l.debug("Safari12::creating new transceiver");const a=this._pc.addTransceiver(r,{direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream],sendEncodings:n}),d=RTCRtpSender.getCapabilities(r.kind);l.info(`Safari12::senders available params: ${JSON.stringify(d)}`);const h=[];if(i){const f=d.codecs.find(g=>g.mimeType.includes(i.name));if(i.parameters){l.info(`Safari12::codecOption.parameters:, ${JSON.stringify(i.parameters)}`);const g=((o=f.sdpFmtpLine)==null?void 0:o.split(";"))||[];g.push(...i.parameters);const E=[...new Set(g).values()];f.sdpFmtpLine=E.join(";")}h.push(f)}l.info(`Safari12::selected codecs: ${JSON.stringify(h)}`),a.setCodecPreferences(h);const p=yield this._pc.createOffer();if(!this._transportReady)throw new Error("webrtc transport not connected");if(yield this._pc.setLocalDescription(p),r.kind==="audio"){const f=this._enableStereo,g=this._enableHighBitrate?f?128e3:64e3:f?64e3:32e3;p.sdp=p.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;usedtx=1${f?"":";stereo=1;sprop-stereo=1"};maxaveragebitrate=${g}`)}return{offerSdp:p,callback:f=>u(this,null,function*(){return l.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(f)}]`),yield this._pc.setRemoteDescription(f),this.midTransceiverMap.set(a.mid,a),a.mid}),sender:a.sender,mid:a.mid}})}stopSending(e){return u(this,null,function*(){this._assertSendDirection(),l.debug(`Safari12::stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.sender.replaceTrack(null),this._pc.removeTrack(r.sender),r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`Safari12::stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`Safari12::stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}replaceTrack(e,r){return u(this,null,function*(){this._assertSendDirection(),r?l.debug(`Safari12::replaceTrack() [localId:${e}, track.id:${r.id}]`):l.debug(`Safari12::replaceTrack() [localId:${e}, no track]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");yield n.sender.replaceTrack(r)})}setMaxSpatialLayer(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,o)=>{o<=r?s.active=!0:s.active=!1}),yield n.sender.setParameters(i)})}setRtpEncodingParameters(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,o)=>{i.encodings[o]=V(V({},s),r)}),yield n.sender.setParameters(i)})}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}receive(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`recieve() | calling pc.setLocalDescription() [answer:${JSON.stringify(e)}]`);const r=this._pc.getTransceivers().at(-1);return l.info("Safari12::Transceiver is now receiving"),this.midTransceiverMap.set(r.mid,r),{track:r.receiver.track,localId:r.mid}})}stopReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Safari12::stopReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive",l.info(`Safari12::active transcievers: ${JSON.stringify(this._pc.getTransceivers())}`);const n=yield this._pc.createOffer();return l.debug(`stopRecieving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`stopRecieving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}pauseReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Safari12::pauseReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`pauseReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`pauseReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i)})}})}resumeReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Safari12::resumeReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="recvonly";const n=yield this._generateOffer();return l.debug(`Safari12::resumeReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`Safari12::resumeReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i)})}})}getReceiverStats(e){return u(this,null,function*(){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.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')}_generateOffer(){return u(this,null,function*(){const e=yield this._pc.createOffer();return yield this._pc.setLocalDescription(e),e})}_setAnswer(e){return u(this,null,function*(){l.debug(`Safari12::_setAnswer() | calling pc.setRemoteDescription() [answer:${JSON.stringify(e)}]`),yield this._pc.setRemoteDescription(e)})}_addEventListeners(){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:l.warn("Safari12::unknown state");break}}),this._pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this._pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),l.debug("Safari12::negotiationneeded")}),this._pc.addEventListener("icegatheringstatechange",()=>{switch(this._pc.iceGatheringState){case"gathering":l.debug("Safari12::icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":l.debug("Safari12::icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:l.warn("Safari12::unknown state");break}}),this._pc.addEventListener("icecandidateerror",e=>{l.error("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this._pc.ondatachannel=e=>{l.info("Safari12::data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{l.info("Safari12::data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{l.warn("Safari12::data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{l.error("Safari12::data channel error: ",{rtcChannel:{label:e.channel.label}})},r.onmessage=n=>u(this,null,function*(){const i=String.fromCharCode(...new Uint8Array(n.data));this.safeEmit("datachannel",e.channel,i)})}}}function AM(){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){l.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return l.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=lu.getParser(t),r=e.getEngine();if(e.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(e.satisfies({chrome:">=70",chromium:">=70"}))return"Chrome70";if(e.satisfies({chrome:">=67",chromium:">=67"}))return"Chrome67";if(e.satisfies({chrome:">=55",chromium:">=55"}))return"Chrome55";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"}))return"Safari11";if(e.satisfies({"microsoft edge":">=11"})&&e.satisfies({"microsoft edge":"<=18"}))return"Edge11";if(r.name&&r.name.toLowerCase()==="blink"){const n=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);if(n){const i=Number(n[1]);return i>=74?"Chrome74":i>=70?"Chrome70":i>=67?"Chrome67":"Chrome55"}return"Chrome74"}if(r.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":"Safari11";l.warn("Device::this._detectDevice() | browser not supported");return}l.warn("Device::this._detectDevice() | unknown device")}class Sg{constructor({handlerName:e,handlerFactory:r}={}){if(m(this,"handlerFactory"),m(this,"_handlerName"),m(this,"_observer"),l.debug("constructor()"),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)l.debug(`Device::constructor() | handler given: ${e}`);else if(e=AM(),e)l.debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=jl.createFactory();break;case"Safari12":this.handlerFactory=Hl.createFactory();break;case"Firefox60":this.handlerFactory=cc.createFactory({supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=cc.createFactory({supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}const n=this.handlerFactory();this._handlerName=n.name,n.close(),this._observer=new _t}get handlerName(){return this._handlerName}createSendTransport({iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s,config:o}){return l.debug("Device::createSendTransport()"),this.createTransport({direction:"send",iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s,config:o})}createRecvTransport({iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s}){return l.debug("Device::createRecvTransport()"),this.createTransport({direction:"recv",iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s})}}let MM=class extends Sg{createTransport({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s,config:o}){const a=gn(),d=new PM({id:a,direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s,handlerFactory:this.handlerFactory,config:o});return this._observer.emit("newtransport",d),d}};var Et;class DM{constructor(e){_(this,Et,void 0),T(this,Et,e)}joinRoom(e,r,n=!1,i=null){return u(this,null,function*(){const s={roomUuid:e,displayName:r,prejoined:n};return i&&(s.location=i),(yield c(this,Et).sendMessagePromiseWithTimeout({event:ie.joinRoom,protobuf:Sm.toBinary(s),timeout:5e3})).payload})}connectTransport(e){return u(this,null,function*(){const r=(yield c(this,Et).sendMessagePromise(ie.createWebRTCTransport,vm.toBinary(e))).payload,{transportId:n,description:i}=Hd.fromBinary(r),s={sdp:i==null?void 0:i.sdp,type:i.type};return{transportId:n,answer:s}})}produce(e){return u(this,null,function*(){var r,n;const i=(yield c(this,Et).sendMessagePromise(ie.produce,bm.toBinary(e))).payload,s=Fm.fromBinary(i);return{answer:{sdp:(r=s==null?void 0:s.description)==null?void 0:r.sdp,type:(n=s==null?void 0:s.description)==null?void 0:n.type},producerId:s.producerId}})}consume(e){return u(this,null,function*(){const r=(yield c(this,Et).sendMessagePromise(ie.consume,_m.toBinary(e))).payload,{consumerIdsMap:{map:n}}=xm.fromBinary(r);return n})}closeProducer(e){return u(this,null,function*(){const r=(yield c(this,Et).sendMessagePromise(ie.closeProducer,Cm.toBinary(e))).payload,{description:n}=Um.fromBinary(r);return n})}closeConsumer(e){return u(this,null,function*(){return(yield c(this,Et).sendMessagePromise(ie.closeConsumer,Im.toBinary(e))).payload})}hostControlForPeer(e,r){return u(this,null,function*(){const n={audio:r==="audio",screeShare:!1,video:r==="video",participantId:e},i=(yield c(this,Et).sendMessagePromise(ie.hostControlPeer,Mm.toBinary(n))).payload;if(!i)return!1;const{status:s}=jm.fromBinary(i);return s==="success"})}hostControlForAll(e){return u(this,null,function*(){const r={audio:e==="audio",screenShare:!1,video:e==="video"},n=(yield c(this,Et).sendMessagePromise(ie.hostControlAllPeers,Dm.toBinary(r))).payload;if(!n)return!1;const{status:i}=Hm.fromBinary(n);return i==="success"})}kickAll(){return u(this,null,function*(){const e={},r=(yield c(this,Et).sendMessagePromise(ie.kickAll,Pm.toBinary(e))).payload;if(!r)return!1;const{status:n}=Bm.fromBinary(r);return n==="success"})}kickPeer(e){return u(this,null,function*(){const r=(yield c(this,Et).sendMessagePromise(ie.kickPeer,Rm.toBinary(e))).payload;if(!r)return!1;const{status:n}=Vm.fromBinary(r);return n==="success"})}changeDisplayName(e){return u(this,null,function*(){const r=(yield c(this,Et).sendMessagePromise(ie.changeDisplayName,Am.toBinary(e))).payload;if(!r)return!1;const{status:n}=Wm.fromBinary(r);return n==="success"})}notifySelfJoinComplete(){return u(this,null,function*(){const e={},r=(yield c(this,Et).sendMessagePromise(ie.selfJoinComplete,Tm.toBinary(e))).payload;return aa.fromBinary(r)})}}Et=new WeakMap;const OM=Error("task execution aborted");class NM{constructor(e,r){m(this,"id"),m(this,"executor"),m(this,"cancel"),this.id=e,this.executor=r}execute(){return u(this,null,function*(){return new Promise((e,r)=>{this.cancel=()=>r(OM),this.executor.then(n=>e(n))})})}}let Tg=0;const dc=new Map;class Yi{static execute(e){const r=Tg;Tg+=1;const n=new NM(r,e);return dc.set(r,n),{id:r,value:n.execute().finally(()=>dc.delete(r))}}static stop(e){const r=dc.get(e);r&&(r.cancel(),dc.delete(e))}}var st=(t=>(t.NEW="new",t.CONNECTING="connecting",t.RECONNECTING="reconnecting",t.DISCONNECTED="disconnected",t.CONNECTED="connected",t.FAILED="failed",t))(st||{}),Qi=(t=>(t[t.HIVE=1]="HIVE",t[t.ROOM_NODE=2]="ROOM_NODE",t[t.CF=3]="CF",t))(Qi||{});const LM=2e3;var tn;class xM extends ug{constructor(e,r){super(),m(this,"_device"),m(this,"_sendTransport"),m(this,"_recvTransport"),m(this,"_consumers"),m(this,"_producers"),m(this,"_producerStatus"),m(this,"_producerIdToConsumerIdMap"),m(this,"_socket"),m(this,"_socketHandler"),m(this,"_totalTransportReconnectionCount"),m(this,"_transportReconnectFailureCount"),m(this,"_consumerCreationFailureCount"),m(this,"_producerNotReadyFailureCount"),m(this,"_consumerNotBoundFailureCount"),m(this,"_transportDisconnectedTimer"),m(this,"_iceTransportPolicy","all"),m(this,"_transportConnectionFailCount",0),m(this,"lastConnectionTime",0),m(this,"transportConnectionStatus"),m(this,"transportState"),m(this,"transportDisconnected"),_(this,tn,void 0),T(this,tn,e),this._device=new MM({}),this._socket=r,this.transportState={consuming:{state:st.NEW,reconnected:!1},producing:{state:st.NEW,reconnected:!1}},this.transportDisconnected={consuming:!1,producing:!1},this._socketHandler=new DM(r),this.reset()}get socket(){return this._socket}get producers(){return this._producers}get consumers(){return this._consumers}get producerIdToConsumerIdMap(){return this._producerIdToConsumerIdMap}get hiveSocketHandler(){return this._socketHandler}get sendTransport(){return this._sendTransport}get recvTransport(){return this._recvTransport}reset(){this._producers=new Map,this._consumers=new Map,this._producerStatus=new Map,this._producerIdToConsumerIdMap=new Map,this.transportConnectionStatus=new Map,this._transportReconnectFailureCount=0,this._consumerCreationFailureCount=0,this._totalTransportReconnectionCount=0,this._producerNotReadyFailureCount=0,this._consumerNotBoundFailureCount=0,this._transportDisconnectedTimer={consuming:void 0,producing:void 0}}setupTransports(e,r){return u(this,null,function*(){const n=yield je().getICEServers().catch(s=>(l.warn(`failed to get iceservers from server: ${s.message}`),[])),i=e.map(s=>{var o,a,d,h,p,f,g,E;const v=this.transportConnectionStatus.get(s);if(v&&!r)return v;switch(v&&r&&Yi.stop(v.id),s){case"send":{const R=Yi.execute(this.createSendTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(o=c(this,tn).getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(h=(d=(a=c(this,tn).getValue("defaults").mediaConfiguration)==null?void 0:a.audio)==null?void 0:d.enableHighBitrate)!=null?h:!1,enableStereo:(g=(f=(p=c(this,tn).getValue("defaults").mediaConfiguration)==null?void 0:p.audio)==null?void 0:f.enableStereo)!=null?g:!1},iceTransportPolicy:this._iceTransportPolicy}));return this.transportConnectionStatus.set(s,R),R.value}case"recv":{const R=Yi.execute(this.createRecvTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(E=c(this,tn).getValue("modules").e2ee)==null?void 0:E.enabled},iceTransportPolicy:this._iceTransportPolicy}));return this.transportConnectionStatus.set(s,R),R.value}default:return l.warn(`What are you thinking when passing this transportType: ${s}?`,{transport:{type:s}}),Promise.reject(Error("TYPE_OF_TRANSPORT_UNKNOWN"))}});return Promise.all(i).finally(()=>{e.forEach(s=>{this.transportConnectionStatus.delete(s)})})})}stopAllTransports(){var e,r,n,i;l.info(" closing all the transports"),(e=this._sendTransport)==null||e.close(),(r=this._sendTransport)==null||r.removeAllListeners(),(n=this._recvTransport)==null||n.close(),(i=this._recvTransport)==null||i.removeAllListeners(),this._sendTransport=void 0,this._recvTransport=void 0,this.reset()}createSendTransport(e){return u(this,null,function*(){var r,n,i,s;if(this._sendTransport&&this._sendTransport.connected){l.info("sendTransport::already_exists_in_connected_state",{transport:{id:(r=this._sendTransport)==null?void 0:r.id,serverId:(n=this._sendTransport)==null?void 0:n.serverId,type:"send"}});return}l.info("sendTransport::initializing_transport",{transport:{id:(i=this._sendTransport)==null?void 0:i.id,serverId:(s=this._sendTransport)==null?void 0:s.serverId,type:"send"}});const o=this._device.createSendTransport(e);this._transportDisconnectedTimer.producing=void 0,l.info("sendTransport::initialized_transport",{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}}),this.handleTransport(o,!1),l.info("sendTransport::connecting_transport",{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}});try{yield fr((a,d)=>u(this,null,function*(){this.socket.isConnected||d(new Error("socket is not connected")),o.connectionState==="closed"&&d(new Error("transport is closed")),a>0&&l.debug(`retrying transport connect, count: ${a}`,{transport:{id:o.id,serverId:o.serverId,type:"send"}});try{yield o.connect()}catch(h){throw l.error(`failed to connect send transport: ${o.id}`,{error:h,transport:{id:o.id,serverId:o.serverId,type:"send"}}),h.message==="ice connection failed"&&d(h),h}}),{delayTime:100,strategy:"exponential",maxRetryCount:K.hasFeature(X.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),l.info("sendTransport::connected_transport",{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}}),this._transportReconnectFailureCount=Math.max(0,this._transportReconnectFailureCount-1),this._producerNotReadyFailureCount=0,this._sendTransport=o,B.onSafeInitialization(()=>{B.configureSendTransport(o)})}catch(a){throw l.error(`failed to connect send transport after retry:${o.id}`,{error:a,transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}}),o.close(),o.removeAllListeners(),this._transportReconnectFailureCount+=1,this.handleFailure(),a}})}createRecvTransport(e){return u(this,null,function*(){var r,n,i,s,o;if(this._recvTransport&&this._recvTransport.connected){l.info("recvTransport::already_exists_in_connected_state",{transport:{id:(r=this._recvTransport)==null?void 0:r.id,serverId:(n=this._recvTransport)==null?void 0:n.serverId,type:"recv"}});return}l.info("recvTransport::initializing_transport",{transport:{id:(i=this._recvTransport)==null?void 0:i.id,serverId:(s=this._recvTransport)==null?void 0:s.serverId,type:"recv"}});const a=this._device.createRecvTransport(ne(V({},e),{additionalSettings:ne(V({},(o=e.additionalSettings)!=null?o:{}),{rtcAudioJitterBufferMaxPackets:25,rtcAudioJitterBufferFastAccelerate:!0,rtcAudioJitterBufferMinDelayMs:20})}));this._transportDisconnectedTimer.consuming=void 0,l.info("recvTransport::initialized_transport",{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),this.handleTransport(a,!0),l.info("recvTransport::connecting_transport",{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}});try{yield fr((d,h)=>u(this,null,function*(){this.socket.isConnected||h(new Error("socket is not connected")),a.connectionState==="closed"&&h(new Error("transport is closed")),d>0&&l.debug(`retrying transport connect, count: ${d}`,{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}});try{yield a.connect()}catch(p){throw l.error(`fail to connect recv transport: ${a.id}`,{error:p,transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),p.message==="ice connection failed"&&h(p),p}}),{delayTime:100,strategy:"exponential",maxRetryCount:K.hasFeature(X.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),l.info("recvTransport::connected_transport",{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),this._transportReconnectFailureCount=Math.max(0,this._transportReconnectFailureCount-1),this._consumerCreationFailureCount=0,this._consumerNotBoundFailureCount=0,this.producerIdToConsumerIdMap.clear(),this._recvTransport=a,B.onSafeInitialization(()=>{B.configureRecvTransport(a)})}catch(d){throw l.error(`failed to connect recv transport after retry:${a.id}`,{error:d,transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),a.close(),a.removeAllListeners(),this._transportReconnectFailureCount+=1,this.handleFailure(),d}})}handleTransport(e,r){if(e.on("connect",(n,i,s)=>u(this,[n,i,s],function*({offer:o},a,d){try{const h={consuming:r,description:{sdp:o.sdp,type:o.type,target:r?Mt.SUBSCRIBER:Mt.PUBLISHER}},{transportId:p,answer:f}=yield this._socketHandler.connectTransport(h);e.setServerId(p),a({answer:f})}catch(h){l.error(`${r?"consumer":"producer"} transport connection error:`,{error:h,transport:{id:e==null?void 0:e.id,serverId:e==null?void 0:e.serverId,type:r?"recv":"send"}}),d(h)}})),e.on("connectionstatechange",n=>u(this,null,function*(){this.updateTransportState({state:n,direction:r?"consuming":"producing"}),l.info(`${r?"consumer":"producer"} transport connectionState:`,{transport:{id:e==null?void 0:e.id,serverId:e==null?void 0:e.serverId,type:r?"recv":"send",status:n}});const i=()=>{this._transportDisconnectedTimer[r?"consuming":"producing"]!==void 0&&(clearTimeout(this._transportDisconnectedTimer[r?"consuming":"producing"]),this._transportDisconnectedTimer[r?"consuming":"producing"]=void 0)};switch(n){case"connected":i(),this.lastConnectionTime=performance.now();break;case"disconnected":this._transportDisconnectedTimer[r?"consuming":"producing"]=setTimeout(()=>{this.triggerTransportReconnection(e,r)},LM);break;case"failed":if(e.closed)return;i(),this.triggerTransportReconnection(e,r);break}})),e.on("icecandidate",n=>u(this,null,function*(){l.debug("sending icecandidate:",{iceCandidate:n})})),e.on("datachannel:events",(n,i)=>u(this,null,function*(){var s,o;l.debug("got data channel message on event:",{rtcChannel:{label:n,message:i}});try{switch(i.type){case"negotiation":{this.negotiateOverDC(i,ac(i),n,e);break}case"handshake":{const a={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,ac(i),a);break}case"consumer_toggle":{this.handleConsumerToggle(i.payload);break}case"hub-disconnect":{l.debug(`media hub disconnected, full_reconnect: ${(s=i.payload)==null?void 0:s.full_reconnect}`),((o=i.payload)==null?void 0:o.full_reconnect)===!0&&this.emit("rejoin");break}case"error":{this.handleErrorOverDC(i.payload,e.id);break}default:l.warn(`unknown event received from hive node, event: ${i.type}`);break}}catch(a){l.error(`Unable to handle the incoming datachannel message on channel ${n}`)}})),e.on("dc_error",()=>{e.direction==="recv"&&(l.warn("events datachannel did not open in 5s"),this.handleFailure())}),e.on("negotiate",(n,i,s)=>u(this,[n,i,s],function*({description:o},a,d){try{const h={sdp:o==null?void 0:o.sdp,type:o==null?void 0:o.type},p=yield this.negotiate(e,h);a({answer:p})}catch(h){l.error("negotiate error:",{transport:{id:e.id,serverId:e.serverId,type:e.direction},error:h}),d(h)}})),!r){e.on("produce",(n,i,s)=>u(this,[n,i,s],function*({offer:o,kind:a,paused:d,appData:h},p,f){var g;const E=Kc(o.sdp).media.filter(R=>a==="video"?R.type==="video":R.type==="audio").at(-1).msid,v={description:{sdp:o.sdp,type:o.type,target:Mt.PUBLISHER},paused:d,kind:a,msid:E,appData:JSON.stringify(h),screenShare:(g=h.screenShare)!=null?g:!1};try{const{answer:R,producerId:A}=yield this._socketHandler.produce(v);p({answer:R,producerId:A})}catch(R){l.error("create producer error:",R),f(R)}}));return}e.on("consume_peer",(n,i,s)=>u(this,[n,i,s],function*({producingPeerId:o,producerId:a},d,h){l.info("consumePeer:",o);const p={producingPeerId:o,producerId:a};try{const f=yield this._socketHandler.consume(p);l.debug(`consumePeer response for ${o}:`,{consumerStateMap:f});const g=new Map;Object.entries(f).forEach(([E,v])=>{var R,A,L;let F={};try{F=JSON.parse(v.producerState.appData)}catch(W){}g.set(E,{consumerId:v.consumerId,trackId:(R=v.producerTrack)==null?void 0:R.trackId,streamId:v.producerTrack.streamId,kind:v.producerState.kind===wt.VIDEO?"video":"audio",appData:F,screenShare:(A=v.producerState)==null?void 0:A.screenShare,paused:(L=v.producerState)==null?void 0:L.pause})}),d({consumersMap:g})}catch(f){l.error("consumePeer error:",{error:f}),h(f)}})),e.on("consume",(n,i,s)=>u(this,[n,i,s],function*({producerId:o,producingPeerId:a},d,h){var p,f,g,E,v,R,A,L,F;const W={producingPeerId:a,producerId:o};try{const H=(yield this._socketHandler.consume(W))[o];let I={};try{I=JSON.parse((p=H.producerState)==null?void 0:p.appData)}catch(S){}l.info("consumer create response:",{consumer:{remotelyPaused:(f=H.producerState)==null?void 0:f.pause,producerId:(g=H.producerState)==null?void 0:g.producerId,kind:(v=(E=H.producerState)==null?void 0:E.kind)==null?void 0:v.toString(),appData:ne(V({},I),{screenShare:(R=H.producerState)==null?void 0:R.screenShare}),id:H.consumerId},consumerState:H}),d({consumerId:H.consumerId,screenShare:(A=H.producerState)==null?void 0:A.screenShare,trackId:(L=H.producerTrack)==null?void 0:L.trackId,streamId:H.producerTrack.streamId,kind:H.producerState.kind===wt.VIDEO?"video":"audio",paused:(F=H.producerState)==null?void 0:F.pause,appData:I})}catch(H){l.error("error during consuming on server:",H),h(H)}}))}createProducer(e,r,n){return u(this,null,function*(){var i;if(this._sendTransport===void 0||this._sendTransport.closed)return null;l.info("createProducer::initializing_producer",{producer:{id:"TO_BE_CREATED",kind:e,status:"initializing",appData:r==null?void 0:r.appData}});const s=this._producerStatus.get(e);if((s==null?void 0:s.trackId)===r.track.id&&(s==null?void 0:s.status)===Pr.INITIALIZING)return l.info("createProducer::producer getting initializing",{producer:{id:"GETTING_CREATED",status:"initializing",kind:e,appData:r==null?void 0:r.appData}}),null;this._producerStatus.set(e,{trackId:r.track.id,status:Pr.INITIALIZING});try{const o=yield this._sendTransport.produce(r);return(i=r.appData)!=null&&i.e2ee&&b.emit(w.E2EE_ACTIVE_PRODUCER,o),l.info("createProducer::initialized_producer",{producer:{id:o==null?void 0:o.id,kind:e,status:"producing",appData:r==null?void 0:r.appData}}),o.on("close",(a,d)=>u(this,[a,d],function*({offer:h,reason:p},f){l.info("producer::closing",{debuggingHint:p,producer:{id:o==null?void 0:o.id,kind:e,status:"closing",appData:r==null?void 0:r.appData}});const g={producerId:o.id,description:{sdp:h.sdp,type:h.type,target:Mt.PUBLISHER}};try{const E=yield this._socketHandler.closeProducer(g),v={sdp:E==null?void 0:E.sdp,type:E==null?void 0:E.type};l.info("producer::closed",{producer:{id:o==null?void 0:o.id,kind:e,status:"closed",appData:r==null?void 0:r.appData}}),f({answer:v})}catch(E){l.error("producer close error",E)}this._producerStatus.delete(e),this._producers.delete(e),n(),this.reconfigureWebcamLayers()})),o.on("trackended",()=>{l.info("producer::trackended",{producer:{id:o==null?void 0:o.id,kind:e,status:"UNKNOWN",appData:o==null?void 0:o.appData}}),[Q.MIC,Q.WEBCAM].includes(e)||n()}),this._producers.set(e,o),this._producerStatus.set(e,{trackId:r.track.id,status:Pr.INITIALIZED}),this.reconfigureWebcamLayers(),o.track}catch(o){throw this._producerStatus.set(e,{status:Pr.NOT_INITIALIZED,trackId:r.track.id}),l.error("createProducer::transport_initialization_failed",{producer:{id:"FAILED_TO_CREATE",kind:e,status:"failed",appData:r==null?void 0:r.appData,error:o}}),o}})}reconfigureWebcamLayers(){return u(this,null,function*(){if(!K.hasFeature(X.DISABLE_WEBCAM_LAYERS_ON_SCREENSHARE))return;const e=this.producers.get(Q.WEBCAM);e&&(yield this._switchProducerSpatialLayer(e,this.producers.get(Q.SCREENSHARE_VIDEO)?0:3))})}_switchProducerSpatialLayer(e,r){return u(this,null,function*(){try{l.debug("switching layer of webcam producer to:",{media:{video:{layer:r}},producer:{id:e.id,kind:e.kind,appData:e.appData}}),yield e.setMaxSpatialLayer(r)}catch(n){l.error("failed to switch spatial layer",{error:n})}})}_initConsumer(e){e&&(e.observer.on("close",r=>u(this,null,function*(){l.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),this._consumers.delete(e.id),b.emit(w.CONSUMER_CLOSED,{id:e.id})})),this._consumers.set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),b.emit(w.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId}))}createConsumer(e){return u(this,null,function*(){if(this._recvTransport===void 0||this._recvTransport.closed||!this._recvTransport.connected)return;const{producers:r,producingPeerId:n}=e;if(r.every(s=>this.getProducer(s.producerId))){l.warn("why are you creating a consumer for local producer?");return}const i=K.hasFeature(X.ENABLE_HIVE_CONSUME_OVER_DC);yield fr(s=>u(this,null,function*(){s>0&&l.debug(`retrying consume call, retryCount: ${s}`),(yield this._recvTransport.consume({producingPeerId:n,producers:r,consumeOverDC:i}).catch(o=>{throw l.error("failed to consume:",{error:o}),o})).forEach(o=>{o.status==="rejected"?(l.error("consumer creation task is failing",o.reason),this._consumerCreationFailureCount+=1,setTimeout(this.handleFailure.bind(this),0)):this._initConsumer(o.value)})})).catch(s=>{l.error("create consumer failed after retries",{error:s}),this._consumerCreationFailureCount+=1,this.handleFailure()})})}pauseProducer(e){return u(this,null,function*(){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.pause(),r.appData.e2ee&&b.emit(w.E2EE_INACTIVE_PRODUCER,r),l.info(`Paused the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})})}resumeProducer(e){return u(this,null,function*(){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.resume(),l.info(`Resumed the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})})}replaceTrack(e,r){return u(this,null,function*(){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}yield n.replaceTrack({track:r}),l.info(`Replaced track for the producer of type: ${n.kind}`,{producer:{id:n.id,kind:n.kind,appData:n.appData,trackId:r.id}})})}removeProducer(e,r){return u(this,null,function*(){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}r&&n.track.stop(),yield this.sendTransport.awaitQueue.push(n.close.bind(n),"producer").then(()=>{c(this,tn).getValue("modules").e2ee.enabled&&b.emit(w.E2EE_INACTIVE_PRODUCER,n)}).catch(i=>{l.error("failed to close producer on server",i)})})}pauseConsumer(e){return u(this,null,function*(){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}this.toggleConsumerOverDC(e,!0),l.info(`Paused the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})})}pauseConsumerOverSocket(e){return u(this,null,function*(){try{const r={consumerId:e.id,pause:!0};yield this.socket.sendMessagePromise(ie.toggleConsumer,oa.toBinary(r)),e.pause(),b.emit(w.CONSUMER_PAUSED,{id:e.id}),l.info(`Paused the consumer of type: ${e.kind} over socket`,{consumer:{id:e.id,kind:e.kind,appData:e.appData}})}catch(r){l.error("error on pausing consumer",{error:r,consumer:{id:e.id,kind:e.kind,appData:e.appData}})}})}toggleConsumerOverDC(e,r){return u(this,null,function*(){const n={type:"consumer_toggle",payload:{consumerId:e,mute:r}},i=this._recvTransport.getDatachannel("events");if(!i){l.warn("recvTransport:: events datachannel not found");return}yield i.request(n),l.info(`HiveSFUHandler::consumer toggled, consumerId: ${e}, muted: ${r}`)})}resumeConsumer(e){return u(this,null,function*(){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}if(!r.paused){l.warn(`consumer with id:${e} is not paused so not resuming`);return}try{const n={consumerId:e,pause:!1};yield this.socket.sendMessagePromise(ie.toggleConsumer,oa.toBinary(n)),r.resume(),b.emit(w.CONSUMER_RESUMED,{id:r.id}),l.info(`Resumed the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})}catch(n){l.error("error on resuming consumer",n)}})}closeConsumer(e,r){return u(this,null,function*(){return this.closeConsumers([e],r)})}closeConsumers(e,r=!1){return u(this,null,function*(){l.info(`Closing consumers: ${JSON.stringify(e)} with force: ${r}`);let n=!0;const i=e.filter(a=>this._consumers.get(a)?!0:(l.warn(`consumer with id: ${a} not found`),!1));if(!i.length)return;const s={consumerIds:i},o=()=>u(this,null,function*(){var a;return(a=this._recvTransport)==null?void 0:a.awaitQueue.push(()=>u(this,null,function*(){yield this._socketHandler.closeConsumer(s)}),"close_consumer").catch(d=>{l.warn("error on closing consumer:",{error:d}),n=r})});r?o():yield o(),n&&i.forEach(a=>{const d=this.consumers.get(a);this.producerIdToConsumerIdMap.delete(d.producerId),d.close(r?"force closed":void 0)})})}cleanupConsumers(e){return u(this,null,function*(){l.debug("cleaning up all consumers");const r=[];this._consumers.forEach(n=>{e?n.peerId===e&&r.push(n.id):r.push(n.id)}),this.closeConsumers(r,!0)})}stopAllProducers(){return u(this,null,function*(){l.info("stopping all available producers"),this._producers.forEach((e,r)=>{l.debug(`closing producer type: ${r}`,{producer:{id:e==null?void 0:e.id,kind:e.kind,appData:e.appData}}),e.close()})})}getProducer(e){return Array.from(this.producers.values()).filter(r=>r.id===e).at(0)}hasProducer(e){return this.getProducer(e)!==void 0}negotiate(e,r){return u(this,null,function*(){l.debug(`setting remote offer : ${JSON.stringify(r)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}});const n=yield e.setRemoteOffer(r),i={transportId:e.serverId,description:{sdp:n.sdp,type:n.type,target:Mt.SUBSCRIBER}};return l.debug(`sending renegotiate request: ${JSON.stringify(i)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),yield this.socket.sendMessagePromise(ie.renegotiateSessionDescription,ym.toBinary(i)),l.info("renegotiation done",{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),n})}negotiateOverDC(e,r,n,i){return u(this,null,function*(){const{sdp:s}=e.payload,o={sdp:s,type:"offer"};try{l.debug(`got offer over dc: ${s} for transport: ${i.id}`);const a=yield i.setRemoteOffer(o),d={type:"answer",payload:{type:a.type,sdp:a.sdp}};l.debug(`datachannel answer: ${JSON.stringify(d)}`),i.sendResponseOverDC(n,r,d)}catch(a){l.error("datachannel:events::Error:",a),a.code!=="DC_NOT_FOUND"&&i.sendErrorOverDC(n,r,a)}})}handleConsumerToggle(e){const{mute:r,trackId:n}=e;l.info(`consumer toggled for trackId: ${n} muted: ${r}`);const i=this.consumers.get(n);if(!i){l.warn(`consumer with trackId: ${n} not found`);return}i.paused!==r&&(l.debug("consumer state is not same",{consumer:{id:i.id,remotelyPaused:i.paused}}),r?(i.pause(),b.emit(w.CONSUMER_PAUSED,{id:i.id})):(i.resume(),b.emit(w.CONSUMER_RESUMED,{id:i.id})))}handleErrorOverDC(e,r){return u(this,null,function*(){l.error(`got error over dc: ${JSON.stringify(e)} for transport: ${r}`);const{type:n,error:i,id:s}=e;if(n==="consumer"){if(i==="bind-fail"){if(this._consumerNotBoundFailureCount>=2){this.handleFailure();return}this._consumerNotBoundFailureCount+=1;const o=this.consumers.get(s);if(!o)return;try{yield this.closeConsumer(o.id),yield this.createConsumer({producers:[{kind:o.kind,pause:o.paused,producerId:o.producerId,producingTransportId:o.producingTransportId,screenShare:o.appData.screenShare}],producingPeerId:o.peerId})}catch(a){l.error("failed to recreate consumer on downtrack bound failure,",{consumer:{id:o.id,producerId:o.producerId,kind:o.kind,appData:o.appData}})}}}else if(n==="producer")if(i==="ready-fail"){if(this._producerNotReadyFailureCount>=2){this.handleFailure();return}this._producerNotReadyFailureCount+=1;const[o]=Array.from(this.producers.entries()).find(a=>a[1].id===s);if(!o)return;yield this.removeProducer(o).catch(a=>{l.error("failed to remove ready-fail producer:",{error:a,producer:{id:s,kind:o,appData:null}})})}else i==="general-failure"&&(this.updateTransportState({state:st.RECONNECTING,direction:"producing"}),this.emit("reconnect_transport",this._sendTransport))})}handleFailure(){return u(this,null,function*(){if(this._transportReconnectFailureCount>0||this._totalTransportReconnectionCount>3){l.warn("transport failure detected"),K.hasFeature(X.ENABLE_HIVE_EXPERIMENTAL_FAIL_RECOVERY)&&(l.debug("rejoining room"),this.emit("rejoin"));return}(this._consumerCreationFailureCount>0||this._consumerNotBoundFailureCount>=2)&&(l.warn("consumer creation failure detected or consumer not bound failure increased"),K.hasFeature(X.ENABLE_HIVE_EXPERIMENTAL_FAIL_RECOVERY)&&(l.debug("reconnecting recv transport"),this._totalTransportReconnectionCount+=1,this.updateTransportState({state:st.RECONNECTING,direction:"consuming"}),this.emit("reconnect_transport",this._recvTransport))),this._producerNotReadyFailureCount>=2&&(l.warn("producer receiver not getting added needs to reconnect send transport"),this._totalTransportReconnectionCount+=1,this.updateTransportState({state:st.RECONNECTING,direction:"producing"}),this.emit("reconnect_transport",this._sendTransport))})}triggerTransportReconnection(e,r){l.info("triggerTransportReconnection:: reconnecting transport",{transport:{type:e.direction,id:e.id,serverId:e.serverId}});const n=K.hasFeature(X.ENABLE_HIVE_TRANSPORT_RECONNECTION_ON_ICE_FAILED),i=K.hasFeature(X.HIVE_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED);n&&(i&&this._socket.isConnected&&(performance.now()-this.lastConnectionTime>2e4&&(this._transportConnectionFailCount=0),this._transportConnectionFailCount>2&&(l.warn("Multiple disconnections, forcing relay"),this._iceTransportPolicy="relay"),this._transportConnectionFailCount+=1),this.updateTransportState({state:st.RECONNECTING,direction:r?"consuming":"producing"}),this.emit("reconnect_transport",e))}switchConsumersToLayer(e,r){return u(this,null,function*(){const n=this._recvTransport.getDatachannel("events");if(!n){l.warn("events datachannel not found");return}const i={type:"switch_consumer_layer",payload:{consumerIds:e,layer:r}};yield n.request(i),l.info(`HiveSFUHandler::consumer id: ${e} layer switched to ${r}`)})}updateTransportState(e){const{state:r,direction:n}=e;r==="disconnected"&&(this.transportDisconnected[n]=!0),this.transportState[n]={state:r,reconnected:r==="connected"?this.transportDisconnected[n]:this.transportState[n].reconnected},r==="connected"&&(this.transportDisconnected[n]=!1),b.emit(w.TRANSPORT_STATE_UPDATE,V({transport:n},this.transportState[n]))}}tn=new WeakMap;var FM=Object.defineProperty,UM=Object.getOwnPropertyDescriptor,de=(t,e,r,n)=>{for(var i=n>1?void 0:n?UM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&FM(e,r,i),i};const Kn={joinAttempted:!1},VM=3e3;var Ie,he,Mr,Xi,zn,Yn,lc,uc,hc,rn,Xs,tr,Dr,nn,kg;const _g=(kg=class extends lg{constructor(t,e){var r,n;super(),_(this,Dr),_(this,Ie,void 0),_(this,he,void 0),_(this,Mr,void 0),_(this,Xi,void 0),_(this,zn,void 0),_(this,Yn,void 0),_(this,lc,void 0),_(this,uc,void 0),_(this,hc,void 0),_(this,rn,void 0),_(this,Xs,void 0),_(this,tr,void 0),m(this,"legacyMode"),m(this,"roomNodeUrl"),m(this,"peerDisplayName"),m(this,"activatedProducingPeerIds"),m(this,"e2ee"),m(this,"partialJoinRoomPromise"),this.context=t;const{roomName:i,authToken:s,legacyMode:o,socketClient:a,meetingTitle:d}=e;this.roomJoined=!1,this.roomName=i,this.authToken=s,this.legacyMode=o,this.meetingTitle=d,T(this,Ie,a),T(this,Mr,!1),T(this,tr,void 0),T(this,he,new xM(t,a)),this.maxPreferredStreams=6,this.activatedProducingPeerIds=new Set,T(this,rn,new Set),T(this,Xi,!1),T(this,zn,0),T(this,Yn,new Ki),this.e2ee=(n=(r=t.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?n:!1,B.legacySwitch(o),this.handleSocketEvents(),this.handleSocketConnectionEvents(),this.handleSFUEvents(),this.handleCallstatsEvents(),T(this,lc,cr(()=>u(this,null,function*(){if(!Kn.joinAttempted)return;const{roomJoined:h}=yield this.joinRoom(this.peerDisplayName,this.roomUUID,{},!0,!0);h&&(b.emit(w.RESET_PRODUCER_STATE),b.emit(w.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3})),T(this,uc,cr(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports(["send"]),l.info("send transport reconected!"),b.emit(w.RESET_PRODUCER_STATE)}),1e3)),T(this,hc,cr(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports(["recv"]),l.info("recv transport reconnected!"),this.activatedProducingPeerIds=new Set,b.emit(w.REFRESH_GRID,!0)}),1e3))}get socketState(){return c(this,Ie).connectionState}get mediaState(){return c(this,he).transportState}static init(t,e){return u(this,null,function*(){const{legacyMode:r=!0,meetingId:n,authToken:i,meetingTitle:s,socket:o}=e;return new _g(t,{legacyMode:r,authToken:i,socketClient:o,roomName:n,meetingTitle:s})})}get sfuHandler(){return c(this,he)}get rejoinRoom(){return c(this,lc)}reset(t=!0){var e,r,n,i;(r=(e=c(this,he))==null?void 0:e.cleanupConsumers)==null||r.call(e),(i=(n=c(this,he))==null?void 0:n.stopAllProducers)==null||i.call(n),c(this,rn).clear(),this.activatedProducingPeerIds.clear(),t&&(c(this,Yn).stop(),this.sfuHandler.stopAllTransports(),this.sfuHandler.reset(),T(this,Yn,new Ki))}reconnectTransport(t){return u(this,null,function*(){l.info(`HiveNodeClient::Room joining state: ${c(this,Mr)}`),!(!t||c(this,Mr))&&(t.direction==="send"?yield c(this,uc).call(this,t):yield c(this,hc).call(this,t))})}setupTransports(t=!1){return u(this,null,function*(){yield c(this,he).setupTransports(["recv","send"],t)})}stopAllProducers(){return u(this,null,function*(){yield c(this,he).stopAllProducers()})}joinRoom(t,e){return u(this,arguments,function*(r,n,i={},s=!1,o=!1){Kn.joinAttempted=!0,T(this,Mr,!0),this.reset(s);const a=je().ipInfo;if(a!=null&&a.loc&&!c(this,Xs)){const h=a.loc.split(",");T(this,Xs,{latitude:parseFloat(h[0]),longitude:parseFloat(h[1])})}let d;try{return d=yield c(this,Yn).push(()=>this._joinRoom(r,n,i,o,c(this,Xs)),"joinRoom"),d}catch(h){d={roomJoined:!1}}return d.roomJoined||b.emit(w.ROOM_NODE_FAILED),d})}_partialJoinRoom(t,e,r=!1,n=void 0){return u(this,null,function*(){const i=je().ipInfo;let s=n;if(i!=null&&i.loc&&!n){const o=i.loc.split(",");s={latitude:parseFloat(o[0]),longitude:parseFloat(o[1])}}yield fr((o,a)=>(c(this,Ie).isConnected||a(new Error("socket is not connected")),o>0&&l.warn(`retrying sending join room request, count: ${o}`),this.sfuHandler.hiveSocketHandler.joinRoom(e,t,r,s).catch(d=>{throw l.error("failed to send join room request, error:",{error:d}),d})),{delayTime:1e3,strategy:"exponential",maxRetryCount:K.hasFeature(X.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),yield this.setupTransports(!0)})}partialJoinRoom(t,e,r=!1,n=void 0){return u(this,null,function*(){this.partialJoinRoomPromise=c(this,Yn).push(()=>this._partialJoinRoom(t,e,r,n))})}_joinRoom(t,e){return u(this,arguments,function*(r,n,i={},s=!1,o=null){this.peerDisplayName=r;try{return this.partialJoinRoomPromise?yield this.partialJoinRoomPromise:yield this._partialJoinRoom(r,n,s,o),K.hasFeature(X.INTERNAL_CALL_STATS)&&navigator.product!=="ReactNative"&&setTimeout(()=>u(this,null,function*(){const a={userId:this.context.getValue("userId"),peerId:this.peerId,displayName:r,roomUUID:n,roomViewType:"groupCall",roomName:this.roomName,deviceInfo:ne(V({},ye.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};B.roomJoined(a),i!=null&&i.audio?B.audioOn():B.audioOff(),i!=null&&i.video?B.videoOn():B.videoOff()})),{roomJoined:yield this.completeJoinRoom()}}catch(a){return l.error("error on sending join room request",{error:a}),{roomJoined:!1}}finally{this.partialJoinRoomPromise=void 0}})}completeJoinRoom(){return u(this,null,function*(){try{this.roomJoined=!0;const{maxPreferredStreams:t,roomState:e}=yield this.sfuHandler.hiveSocketHandler.notifySelfJoinComplete();return this.roomUUID=e.roomUuid,T(this,Xi,!0),T(this,Mr,!1),this.maxPreferredStreams=t!=null?t:6,b.emit(w.REFRESH_GRID,!0),!0}catch(t){return l.error("error on completing join room:",{error:t}),this.roomJoined=!1,!1}})}leaveRoom(){return u(this,null,function*(){c(this,he).stopAllTransports(),T(this,Xi,!1),Kn.joinAttempted=!1;const t={closeRoom:!1};c(this,Ie).sendMessagePromise(ie.leaveRoom,km.toBinary(t)).then(e=>{var r;(r=Lm.fromBinary(e.payload))!=null&&r.closed||l.warn("weird state on peer closed and should not happen")}).catch(e=>{l.error("error on sending leave room request",{error:e})}),B.callEnded(),y.destruct()})}getConsumers(){return c(this,he).consumers}activatePeers(t){return u(this,null,function*(){const e=t.map(({peerId:r,producers:n,force:i})=>{if(n.length===0)return Promise.resolve();if(i)return this.consumePeer(r,n,i);const s=[];return n.every(o=>{const a=this.sfuHandler.producerIdToConsumerIdMap.get(o.producerId);if(!a)return!1;const d=this.sfuHandler.consumers.get(a);return d&&!o.pause&&d.paused&&s.push(a),!0})?s.length>0?this.resumeConsumers(s):Promise.resolve():this.consumePeer(r,n)});yield Promise.all(e)})}deactivatePeers(t,e="default"){return u(this,null,function*(){if(l.info("deactivating producers",{producerInfo:{peerId:t.peerId,producers:t.producers}}),t.producers.some(r=>r.screenShare&&r.kind==="video")){l.debug("peer is screensharing can't deactivate");return}t.producers.forEach(({producerId:r,kind:n})=>{if(n==="audio"&&e!=="default"){l.debug("we don't want to deactive audio consumers");return}const i=this.sfuHandler.producerIdToConsumerIdMap.get(r);if(!i){l.warn(`consumer not found in deactivate producers: ${r}`);return}this.sfuHandler.closeConsumer(i)}),this.activatedProducingPeerIds.delete(t.peerId)})}createConsumer(t,e){return u(this,null,function*(){return this.sfuHandler.createConsumer({producingPeerId:t,producers:[e]})})}pauseConsumers(t){return u(this,null,function*(){t.forEach(e=>{this.sfuHandler.pauseConsumer(e)})})}resumeConsumers(t){return u(this,null,function*(){t.forEach(e=>{this.sfuHandler.resumeConsumer(e)})})}closeConsumers(t){return u(this,null,function*(){return t.forEach(e=>{this.activatedProducingPeerIds.delete(e)}),this.sfuHandler.closeConsumers(t)})}consumePeer(t,e,r){return u(this,null,function*(){if(l.info(`current activated Peer ids: ${JSON.stringify(Array.from(this.activatedProducingPeerIds.values()))}, forced?:${r}`),!this.activatedProducingPeerIds.has(t)||r)try{yield c(this,he).createConsumer({producingPeerId:t,producers:e}),this.activatedProducingPeerIds.add(t)}catch(n){l.error("consumePeer failed in HiveNodeClient.ts",{error:n})}else l.info(`not creating consumer for this peerId: ${t}`)})}shareWebcam(t){return u(this,null,function*(){if(t===void 0)return null;if(c(this,he).producers.has(Q.WEBCAM)){const n=c(this,he).producers.get(Q.WEBCAM);if(!n.closed&&!navigator.isReactNative)return yield n.replaceTrack({track:t}),yield this.resumeWebcam(),t;yield c(this,he).removeProducer(Q.WEBCAM)}const e={track:t,codecOptions:{name:"VP8"},appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1};if(K.hasFeature(X.ENABLE_HIVE_SIMULCAST)){let n=t.getConstraints().width;n in Jf||(n=320),e.encodings=Jf[n]}const r=()=>{l.info("Disabling video due to the producer closure"),this.disableWebcam()};return c(this,he).createProducer(Q.WEBCAM,e,r)})}shareScreen(t){return u(this,null,function*(){const{video:e,audio:r}=t;if(e===void 0)return;const n={track:e,codecOptions:{name:"VP8"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ye.isElectron()},stopTracks:!1};let i=()=>{l.info("Disabling screenShare due to the producer closure"),this.disableScreenShare()};if(yield c(this,he).createProducer(Q.SCREENSHARE_VIDEO,n,i),r){const s={track:r,codecOptions:{name:"opus"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ye.isElectron()},stopTracks:!1,zeroRtpOnPause:!0};i=()=>{},yield c(this,he).createProducer(Q.SCREENSHARE_AUDIO,s,i)}B.screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new it("track undefined");if(c(this,he).producers.has(Q.MIC)){const n=c(this,he).producers.get(Q.MIC);if(!n.closed&&!navigator.isReactNative){yield n.replaceTrack({track:t}),yield this.resumeMic();return}yield c(this,he).removeProducer(Q.MIC,!1)}const e={track:t,encodings:[{priority:"high"}],codecOptions:{name:"opus"},appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!0},r=()=>{l.info("Disabling audio due to the producer closure"),this.disableMic()};yield c(this,he).createProducer(Q.MIC,e,r)}catch(e){throw new C(e)}})}pauseMic(){const t=c(this,he).producers.get(Q.MIC);if(!t){l.error("pauseMic::could_not_find_mic_producer");return}if(t.paused){l.info("pauseMic::mic_producer_already_paused");return}t.pause();const e={producerId:t.id,pause:!0};c(this,Ie).sendMessage(ie.toggleProducer,$r.toBinary(e))}pauseWebcam(){return u(this,null,function*(){const t=c(this,he).producers.get(Q.WEBCAM);if(!t){l.error("pauseWebcam::could_not_find_webcam_producer");return}t.pause();const e={producerId:t.id,pause:!0};c(this,Ie).sendMessage(ie.toggleProducer,$r.toBinary(e))})}resumeMic(){return u(this,null,function*(){const t=c(this,he).producers.get(Q.MIC);if(!t){l.error("resumeMic::could_not_find_mic_producer");return}if(!t.pause){l.info("resumeMic::mic_producer_already_resumed");return}t.resume(),t.appData.e2ee&&b.emit(w.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,Ie).sendMessage(ie.toggleProducer,$r.toBinary(e))})}resumeWebcam(){return u(this,null,function*(){const t=c(this,he).producers.get(Q.WEBCAM);if(!t){l.error("resumeWebcam::could_not_find_webcam_producer");return}t.resume(),t.appData.e2ee&&b.emit(w.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,Ie).sendMessage(ie.toggleProducer,$r.toBinary(e))})}disableWebcam(){return u(this,null,function*(){yield c(this,he).removeProducer(Q.WEBCAM)})}disableMic(){return u(this,null,function*(){yield c(this,he).removeProducer(Q.MIC)})}disableScreenShare(){return u(this,null,function*(){l.info("screen_sharing_stopped"),B.screenShareStop(),yield c(this,he).removeProducer(Q.SCREENSHARE_VIDEO),yield c(this,he).removeProducer(Q.SCREENSHARE_AUDIO),c(this,rn).clear()})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}unmuteSelf(){return u(this,null,function*(){})}resetVideoProducers(t,e){return u(this,null,function*(){t&&(yield c(this,he).removeProducer(Q.WEBCAM,!1),this.shareWebcam(t)),e&&(yield c(this,he).removeProducer(Q.SCREENSHARE_VIDEO,!1),this.shareScreen({video:e}))})}changeDisplayName(t,e){return u(this,null,function*(){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!(yield this.sfuHandler.hiveSocketHandler.changeDisplayName(r)))throw new Error("failed to change display name!")})}kick(t){return u(this,null,function*(){const e={participantId:t};if(!(yield this.sfuHandler.hiveSocketHandler.kickPeer(e)))throw new Error("failed to kickout the participant!")})}kickAll(){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.kickAll()))throw new Error("failed to kickout all participant!")})}muteAll(t){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.hostControlForPeer(t,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(t){return u(this,null,function*(){const e={participantId:t!=null?t:""};try{yield c(this,Ie).sendMessagePromise(ie.globalPinPeer,wm.toBinary(e))}catch(r){l.error("Error in pinning peer:",{error:r})}})}validateScreenShare(t){return this.peerId===t.peerId&&this.sfuHandler.hasProducer(t.producerId)&&c(this,rn).add(t.consumerPeerId),c(this,rn).size}switchConsumersToLayer(t,e){return u(this,null,function*(){this.sfuHandler.switchConsumersToLayer(t,e)})}handleSocketEvents(){return u(this,null,function*(){c(this,Ie).on(ie.peerProducerCreateBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:r}=Gm.fromBinary(t);if(e===this.peerId)return;l.info(`producer created broadcast: ${e}, producer state: ${r}`),b.emit(w.NEW_PRODUCER,{peerId:e,producer:ne(V({},r),{kind:r.kind===wt.AUDIO?"audio":"video"})})}catch(e){l.error("error in peer-producer-create-broadcast",{error:e})}}),c(this,Ie).on(ie.peerProducerToggleBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:{kind:r,pause:n,producerId:i}}=Jm.fromBinary(t),s=r===wt.AUDIO?"audio":"video";if(l.info(`producer toggle broadcast: ${e}, producerId: ${i}, kind:${s}, paused:${n}`),e===this.peerId&&n){b.emit(s==="audio"?w.MUTE_ALL:w.MUTE_ALL_VIDEO);return}b.emit(w.PRODUCER_TOGGLE,{peerId:e,producerId:i,paused:n,kind:s}),Array.from(this.getConsumers().values()).filter(o=>o.producerId===i).forEach(o=>{o.paused!==n&&(l.debug(`consumer state mismatched for ${o.id}. updating consumer pause state ${o.paused} to ${n}`),n?(o.pause(),b.emit(w.CONSUMER_PAUSED,{id:o.id})):(o.resume(),b.emit(w.CONSUMER_RESUMED,{id:o.id})))})}catch(e){l.error("error in producer toggle broadcast handler",{error:e})}}),c(this,Ie).on(ie.peerLeaveBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e}=ca.fromBinary(t);if(e===this.peerId)return;l.info(`peer left broadcast:${e}`),c(this,rn).delete(e),this.sfuHandler.cleanupConsumers(e),b.emit(w.PEER_CLOSED,{id:e})}catch(e){l.error("error in peer left broadcast",{error:e})}}),c(this,Ie).on(ie.peerProducerCloseBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:{producerId:r}}=qm.fromBinary(t);if(e===this.peerId)return;l.info(`producer closed broadcast:${e}`),b.emit(w.PRODUCER_CLOSED,{peerId:e,producerId:r});const n=this.sfuHandler.producerIdToConsumerIdMap.get(r);if(!n){l.warn(`no consumer found for producer:${r}`);return}l.info(`closing consumer ${n}, producer id: ${r}`),this.sfuHandler.closeConsumer(n).then(()=>{l.info(`closed consumer: ${n}`),this.sfuHandler.producerIdToConsumerIdMap.delete(r),b.emit(w.CONSUMER_CLOSED,{id:n})}).catch(i=>{l.error("error closing consumer",{error:i})})}catch(e){l.error("error on producer close broadcast",{error:e})}}),c(this,Ie).on(ie.mediaRoomTerminationBroadcastResponse,()=>{!this.roomJoined&&!c(this,Mr)&&!c(this,Xi)||(l.warn("media hub termination broadcast received, rejoining room"),b.emit(w.ROOM_NODE_DISCONNECTED),this.rejoinRoom())})})}handleSocketConnectionEvents(){c(this,Ie).onStateEvent("connected",()=>u(this,null,function*(){l.info("SocketService::Connected to socket-edge"),c(this,tr)&&(clearTimeout(c(this,tr)),T(this,tr,void 0)),ue(this,Dr,nn).call(this,"connected")})),c(this,Ie).onStateEvent("disconnected",({code:t,reason:e})=>{l.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e}});const{consuming:r,producing:n}=this.mediaState;r.state!==st.CONNECTED||n.state!==st.CONNECTED?b.emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:Kn.joinAttempted}):T(this,tr,setTimeout(()=>{b.emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:Kn.joinAttempted}),T(this,tr,void 0)},VM)),ue(this,Dr,nn).call(this,"disconnected"),this.roomJoined=!1}),c(this,Ie).onStateEvent("reconnecting",()=>u(this,null,function*(){l.info("SocketService::Reconnecting to socket-edge"),ue(this,Dr,nn).call(this,"reconnecting")})),c(this,Ie).onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){l.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),ue(this,Dr,nn).call(this,"reconnectAttempt",e)})),c(this,Ie).onStateEvent("reconnectFailure",({attempt:t})=>{l.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),ue(this,Dr,nn).call(this,"reconnectFailure",t)}),c(this,Ie).onStateEvent("reconnected",()=>u(this,null,function*(){l.info("SocketService::Reconnected to socket-edge",{connectionState:Kn}),c(this,tr)&&(clearTimeout(c(this,tr)),T(this,tr,void 0)),b.emit(w.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:Kn.joinAttempted}),ue(this,Dr,nn).call(this,"reconnected")})),c(this,Ie).onStateEvent("failed",()=>u(this,null,function*(){l.info("SocketService::Failed to connect to socket-edge"),b.emit(w.SOCKET_SERVICE_FAILED),ue(this,Dr,nn).call(this,"failed"),this.roomJoined=!1}))}handleSFUEvents(){c(this,he).on("reconnect_transport",t=>u(this,null,function*(){try{yield this.reconnectTransport(t),l.info(`transport reconnected [id:${t.id}]`)}catch(e){l.error("error on reconnection transports",{error:e})}})),c(this,he).on("rejoin",t=>{if(c(this,zn)>3&&!t){l.warn("cannot rejoin more already rejoined 3 times");return}if(c(this,Mr)&&!t){l.warn("room joining in progress, cannot start rejoining");return}T(this,zn,c(this,zn)+1),l.warn(`rejoining the room because transports are failing. [rejoinCount: ${c(this,zn)}]`),this.roomJoined=!1,b.emit(w.ROOM_NODE_DISCONNECTED),this.rejoinRoom()})}handleCallstatsEvents(){B.onSafeInitialization(()=>{B.onConsumerScore(t=>{t.forEach((e,r)=>{const n=this.sfuHandler.consumers.get(r);n&&b.emit(w.CONSUMER_SCORE_UPDATE,{id:r,kind:n.kind,peerId:n.peerId,score:+(e*10).toFixed()})})}),B.onProducerScore(t=>{t.forEach((e,r)=>{const n=Array.from(this.sfuHandler.producers.values()).find(i=>i.id===r);n&&b.emit(w.PRODUCER_SCORE_UPDATE,{id:r,kind:n.kind,appData:n.appData,score:+(e*10).toFixed()})})})})}},Ie=new WeakMap,he=new WeakMap,Mr=new WeakMap,Xi=new WeakMap,zn=new WeakMap,Yn=new WeakMap,lc=new WeakMap,uc=new WeakMap,hc=new WeakMap,rn=new WeakMap,Xs=new WeakMap,tr=new WeakMap,Dr=new WeakSet,nn=function(t,e){let r;const{reconnected:n}=c(this,Ie).connectionState;switch(t){case"connected":r={state:"connected",reconnected:n,reconnectionAttempt:void 0};break;case"disconnected":r={state:"disconnected",reconnected:!1,reconnectionAttempt:0};break;case"reconnected":r={state:"connected",reconnected:!0,reconnectionAttempt:void 0};break;case"reconnecting":r={state:"reconnecting",reconnected:n,reconnectionAttempt:0};break;case"reconnectAttempt":r={state:"reconnecting",reconnected:n,reconnectionAttempt:e};break;case"failed":r={state:"failed",reconnected:n,reconnectionAttempt:void 0};break}r&&(b.emit(w.SOCKET_STATE_UPDATE,r),c(this,Ie).connectionState=r)},kg);let oe=_g;de([y.trace("HiveNodeClient.reset")],oe.prototype,"reset",1),de([y.trace("HiveNodeClient.reconnect")],oe.prototype,"reconnectTransport",1),de([y.trace("HiveNodeClient.setupTransport")],oe.prototype,"setupTransports",1),de([y.trace("HiveNodeClient.stopAllProducers")],oe.prototype,"stopAllProducers",1),de([y.trace("HiveNodeClient.joinRoom")],oe.prototype,"joinRoom",1),de([y.trace("HiveNodeClient.completeJoinRoom")],oe.prototype,"completeJoinRoom",1),de([y.trace("HiveNodeClient.leaveRoom")],oe.prototype,"leaveRoom",1),de([y.trace("HiveNodeClient.activatePeers")],oe.prototype,"activatePeers",1),de([y.trace("HiveNodeClient.deactivatePeers")],oe.prototype,"deactivatePeers",1),de([y.trace("HiveNodeClient.createConsumer")],oe.prototype,"createConsumer",1),de([y.trace("HiveNodeClient.pauseConsumers")],oe.prototype,"pauseConsumers",1),de([y.trace("HiveNodeClient.resumeConsumers")],oe.prototype,"resumeConsumers",1),de([y.trace("HiveNodeClient.closeConsumers")],oe.prototype,"closeConsumers",1),de([y.trace("HiveNodeClient.consumePeer")],oe.prototype,"consumePeer",1),de([y.trace("HiveNodeClient.shareWebcam")],oe.prototype,"shareWebcam",1),de([y.trace("HiveNodeClient.shareScreen")],oe.prototype,"shareScreen",1),de([y.trace("HiveNodeClient.shareMic")],oe.prototype,"shareMic",1),de([y.trace("HiveNodeClient.pauseMic")],oe.prototype,"pauseMic",1),de([y.trace("HiveNodeClient.pauseWebcam")],oe.prototype,"pauseWebcam",1),de([y.trace("HiveNodeClient.resumeMic")],oe.prototype,"resumeMic",1),de([y.trace("HiveNodeClient.resumeWebcam")],oe.prototype,"resumeWebcam",1),de([y.trace("HiveNodeClient.disableWebcam")],oe.prototype,"disableWebcam",1),de([y.trace("HiveClient.disableMic")],oe.prototype,"disableMic",1),de([y.trace("HiveClient.disableScreenShare")],oe.prototype,"disableScreenShare",1),de([y.trace("HiveNodeClient.muteSelf")],oe.prototype,"muteSelf",1),de([y.trace("HiveNodeClient.resetVideoProducers")],oe.prototype,"resetVideoProducers",1),de([y.trace("HiveNodeClient.changeDisplayName")],oe.prototype,"changeDisplayName",1),de([y.trace("HiveNodeClient.kickPeer")],oe.prototype,"kick",1),de([y.trace("HiveNodeClient.kickAllPeers")],oe.prototype,"kickAll",1),de([y.trace("HiveNodeClient.muteAll")],oe.prototype,"muteAll",1),de([y.trace("HiveNodeClient.muteAllVideo")],oe.prototype,"muteAllVideo",1),de([y.trace("HiveNodeClient.disableAudio")],oe.prototype,"disableAudio",1),de([y.trace("HiveNodeClient.disableVideo")],oe.prototype,"disableVideo",1),de([y.trace("HiveNodeClient.pinPeer")],oe.prototype,"pinPeer",1),de([y.trace("HiveNodeClient.validateScreenShare")],oe.prototype,"validateScreenShare",1),de([y.trace("HiveNodeClient.init")],oe,"init",1);class BM{constructor(){m(this,"_orderedArray"),m(this,"_map"),this._map=new Map,this._orderedArray=[]}add(e,r){if(!this._map.has(e))return this._map.set(e,{peerId:e,priority:r}),this._orderedArray.splice(Math.max(r-1,0),0,e),this.index(e);const n=this.index(e);this.delete(e);const i=this.add(e,r);return n!==i?i:-1}delete(e){if(this._map.has(e)){const r=this.index(e);this._map.delete(e),this._orderedArray.splice(r,1)}}index(e){return this._map.has(e)?this._orderedArray.indexOf(e):-1}[Symbol.iterator](){return this._orderedArray[Symbol.iterator]()}}class Wl{constructor(){m(this,"_activeSpeakerPeers"),m(this,"_compulsoryPeers"),this._activeSpeakerPeers=new BM,this._compulsoryPeers=new Set}add(e,r){if(r<0)return this._compulsoryPeers.add(e),0;if(this.compulsoryPeers.includes(e)&&(r>0||r===246267631)){if(l.info("DyteSelectedPeer::removing_compulsory_peer",{selectedPeer:{peerId:e}}),this._removeFromCompulsoryPeer(e),r===246267631)return-1}else if(r===229490415)return this.delete(e),-1;return this._activeSpeakerPeers.add(e,r)}delete(e){l.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 peerPriorities(){return Array.from(this._activeSpeakerPeers).map((e,r)=>r)}get activeSpeakerPeers(){return Array.from(this._activeSpeakerPeers)}_removeFromCompulsoryPeer(e){this._compulsoryPeers.delete(e)}}var jM=Object.defineProperty,HM=Object.getOwnPropertyDescriptor,Lt=(t,e,r,n)=>{for(var i=n>1?void 0:n?HM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&jM(e,r,i),i};const WM=["ACTIVE_GRID","PAGINATED","MANUAL"];var Zi,Ht,rr,Qn,Wt,bg;let St=(bg=class extends Dt{constructor(t,e,r,n){var i;super(),_(this,Ht),m(this,"waitlisted"),m(this,"joined"),m(this,"active"),m(this,"pinned"),m(this,"all"),m(this,"pip"),_(this,Zi,void 0),_(this,Qn,void 0),_(this,Wt,void 0),m(this,"viewMode"),m(this,"currentPage"),m(this,"lastActiveSpeaker"),m(this,"selectedPeers",new Wl),T(this,Zi,t),T(this,Qn,e),T(this,Wt,r),this.waitlisted=new Ja,this.joined=new Ja,this.active=new Ja,this.pinned=new Ja,this.selectedPeers=new Wl,this.all=new gM,this.viewMode="ACTIVE_GRID",this.currentPage=0,((i=n==null?void 0:n.pip)==null||i)&&(this.pip=new EM(t,e)),this.setupEvents()}get roomJoined(){var t;return((t=c(this,Ht,rr))==null?void 0:t.roomJoined)===!0}setupEvents(){b.on(w.E2EE_ACTIVE_CONSUMER,({peerId:t})=>{var e;((e=c(this,Zi).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(){return c(this,Ht,rr).maxPreferredStreams}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new C("0 <= Max active participants count limit <= 24");c(this,Ht,rr).maxPreferredStreams=t,c(this,Qn).roomJoined&&b.emit(w.REFRESH_GRID)}get pageCount(){if(this.viewMode==="PAGINATED"){const t=this.joined.toArray().filter(e=>e.stageStatus==="ON_STAGE");return Math.ceil(t.length/this.maxActiveParticipantsCount)}return 0}acceptWaitingRoomRequest(t){var e,r;if(!this.roomJoined)throw new C("Can`t accept waiting room request without joining room");const n=(r=(e=this.waitlisted.get(t))==null?void 0:e.userId)!=null?r:t;return c(this,Wt).acceptWaitingRoomRequest([n])}acceptAllWaitingRoomRequest(t){return u(this,null,function*(){const e=t.map(r=>{var n,i;return(i=(n=this.waitlisted.get(r))==null?void 0:n.userId)!=null?i:r});return c(this,Wt).acceptWaitingRoomRequest(e)})}rejectWaitingRoomRequest(t){return u(this,null,function*(){var e,r;if(!this.roomJoined)throw new C("Can`t reject waiting room request without joining room");const n=(r=(e=this.waitlisted.get(t))==null?void 0:e.userId)!=null?r:t;c(this,Wt).rejectWaitingRoomRequest([n])})}setViewMode(t){return u(this,null,function*(){if(l.info("DyteParticipants::set_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),!(e=>WM.includes(e))(t))throw l.error("DyteParticipants::setViewMode::invalid_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),new C(`Invalid view mode: ${t}. Try ACTIVE_GRID, PAGINATED or MANUAL.`);if(this.viewMode===t){l.info("DyteParticipants::setViewMode::view_mode_same_as_previous");return}if(t==="MANUAL"&&!(c(this,Ht,rr)instanceof oe))throw new C("Manual Subscription is not enabled for your Organization. Please contact support.");this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,b.emit(w.UPDATE_ACTIVE,{page:this.currentPage})):t==="ACTIVE_GRID"&&(this.currentPage=0,b.emit(w.UPDATE_ACTIVE)),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})})}subscribe(t){return u(this,null,function*(){if(this.viewMode!=="MANUAL")throw new C("Please activate MANUAL subscription mode first.");const e={},r=[],n=[];t.forEach(a=>{e[a.id]=!0;const d=this.active.get(a.id);if(!d)r.push(a);else{d.manualProducerConfig=a.producers;const h=p=>u(this,[p],function*({producers:f,config:g}){const E=[];f.forEach(v=>{const R=v.kind==="audio",A=v.kind==="video";(R&&(g.audio&&!v.screenShare||g.screenshareAudio&&v.screenShare)||A&&(g.video&&!v.screenShare||g.screenshareVideo&&v.screenShare))&&E.push(v.producerId),c(this,Ht,rr).closeConsumers(E)})});n.push(h({peerId:a.id,config:a.producers,producers:d.producers}))}});const i=[];this.active.forEach(a=>{if(e[a.id])return;const d=h=>u(this,null,function*(){const p={peerId:h.id,producers:h.producers};yield c(this,Ht,rr).deactivatePeers(p,"manual"),this.active.delete(h.id);const f=this.joined.get(h.id);f.manualProducerConfig=jd});i.push(d(a))}),yield Promise.all([...i,...n]);const s=(a,d)=>a.reduce((h,p)=>(!p.screenShare&&d[p.kind]&&h.push(p),p.screenShare&&(p.kind==="audio"&&d.screenshareAudio||p.kind==="video"&&d.screenshareVideo)&&h.push(p),h),[]),o=r.map(a=>{const d=this.joined.get(a.id);return this.active.add(d),d.manualProducerConfig=a.producers,{peerId:d.id,producers:s(d.producers,a.producers)}});yield c(this,Ht,rr).activatePeers(o),this.active.emit("participantsUpdate")})}unsubscribe(t){return u(this,null,function*(){if(this.viewMode!=="MANUAL")throw new C("Manual Subscription is not enabled for your Organization. Please contact support.");t.forEach(e=>u(this,null,function*(){const r=this.joined.get(e);if(!r)return;const n={peerId:r.id,producers:r.producers};r.manualProducerConfig=jd,yield c(this,Ht,rr).deactivatePeers(n,"manual"),this.active.delete(r.id)}))})}getPeerIdsForCurrentPage(){l.info("DyteParticipants::getPeerIdsForCurrentPage()",{pageNavigation:{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}});const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(o=>this.joined.has(o)),r=Array.from(this.pinned.keys()).filter(o=>!e.includes(o)),n=Array.from(this.joined.toArray().filter(o=>o.stageStatus==="ON_STAGE").map(o=>o.id)),i=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-r.length)),s=this.currentPage*(this.maxActiveParticipantsCount-e.length-r.length);return e.concat(r,n.slice(i,s))}setPage(t){return u(this,null,function*(){if(l.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 l.error("DyteParticipants::invalid_page_number"),new C(`Invalid page: ${t}. Page must be an integer and greater than 0 and less than or equal to .pageCount`);this.currentPage=t,b.emit(w.UPDATE_ACTIVE,{page:t}),this.emit("pageChanged",{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount})}})}disableAllAudio(t){return u(this,null,function*(){if(l.info("DyteParticipants::disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),!this.roomJoined)throw new C("Can`t disable all audio without joining room");if(c(this,Qn).permissions.canAllowParticipantAudio)return c(this,Ht,rr).muteAll(t);throw l.error("DyteParticipants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new C("Unauthorized: User does not have permission to disable peer audio.")})}disableAllVideo(){return u(this,null,function*(){if(l.info("DyteParticipants::disable_all_video"),!this.roomJoined)throw new C("Can`t disable all video without joining room");if(c(this,Qn).permissions.canAllowParticipantVideo)return c(this,Ht,rr).muteAllVideo();throw l.error("DyteParticipants::unauthorized_disable_all_video"),new C("Unauthorized: User does not have permission to disable peer video.")})}disableAudio(t){return u(this,null,function*(){this.joined.get(t).disableAudio()})}disableVideo(t){return u(this,null,function*(){this.joined.get(t).disableVideo()})}kick(t){return u(this,null,function*(){yield b.emitAsync(w.KICK_PEER,{peerId:t})})}kickAll(){return u(this,null,function*(){if(l.info("DyteParticipants::kick_all"),c(this,Zi).getValue("viewType")!=="LIVESTREAM"&&!this.roomJoined)throw new C("Can`t kick all without joining room");if(!c(this,Qn).permissions.kickParticipant)throw l.error("DyteParticipants::unauthorized_kick_all"),new C("Unauthorized: User does not have permission to kick peers.");c(this,Wt).kickAll()})}broadcastMessage(t,e,r){return u(this,null,function*(){if(l.info("DyteParticipants::broadcastMessage"),!this.roomJoined)throw new C("Can`t broadcast message without joining room");if(!(t!=null&&t.trim()))throw new C("`type` must be a non-empty string.");if(r){let n=[];"participantIds"in r?n=r.participantIds:n=this.joined.toArray().filter(i=>{var s;return(s=r.presetNames)==null?void 0:s.includes(i.presetName)}).map(i=>i.id),c(this,Wt).broadcastToPeers(t,n,e)}else c(this,Wt).broadcastMessage(t,e)})}getAllJoinedPeers(t,e,r){return u(this,null,function*(){return(yield c(this,Wt).getRoomPeers(t,e,r)).peers.map(gr.formatSocketServiceMessage)})}updatePermissions(t,e){return u(this,null,function*(){const r=this.joined.toArray().filter(i=>t.includes(i.id)).map(i=>i.userId),n=[...new Set(r)];c(this,Wt).updatePermissions(n,e)})}getParticipantsInMeetingPreJoin(){return u(this,null,function*(){return c(this,Wt).getRoomPeersNonPaginated()})}},Zi=new WeakMap,Ht=new WeakSet,rr=function(){return c(this,Zi).getValue("roomNodeClient")},Qn=new WeakMap,Wt=new WeakMap,bg);Lt([y.trace("DyteParticipants.setViewMode")],St.prototype,"setViewMode",1),Lt([y.trace("DyteParticipants.setPage")],St.prototype,"setPage",1),Lt([y.trace("DyteParticipants.disableAllAudio")],St.prototype,"disableAllAudio",1),Lt([y.trace("DyteParticipants.disableAllVideo")],St.prototype,"disableAllVideo",1),Lt([y.trace("DyteParticipants.disablePeerAudio")],St.prototype,"disableAudio",1),Lt([y.trace("DyteParticipants.disablePeerVideo")],St.prototype,"disableVideo",1),Lt([y.trace("DyteParticipants.kickPeer")],St.prototype,"kick",1),Lt([y.trace("DyteParticipants.kickAll")],St.prototype,"kickAll",1),Lt([y.trace("DyteParticipants.broadcastMessage"),Ct({maxInvocations:500,period:60})],St.prototype,"broadcastMessage",1),Lt([y.trace("DyteParticipants.getAllJoinedPeers"),Ct({maxInvocations:10,period:60})],St.prototype,"getAllJoinedPeers",1),Lt([y.trace("DyteParticipant.updatePermissions"),Ct({maxInvocations:1e3,period:60})],St.prototype,"updatePermissions",1),Lt([y.trace("DyteParticipants.getParticipantsInMeetingPreJoin")],St.prototype,"getParticipantsInMeetingPreJoin",1),St=Lt([dt("1200")],St);var $M=Object.defineProperty,GM=Object.getOwnPropertyDescriptor,Xn=(t,e,r,n)=>{for(var i=n>1?void 0:n?GM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&$M(e,r,i),i};class gr{constructor(e,r,n,i){m(this,"participants"),m(this,"self"),m(this,"selectedPeers",new Wl),m(this,"currentActiveGridParticipants",new Set),m(this,"maxSpatialLayerUpdates",new Map),m(this,"consumerPeerMap"),m(this,"roomSocketHandler"),m(this,"context"),m(this,"videoPeerConsumerMap",new Map),m(this,"updateConsumerSpatialLayers",cr(()=>{const s={},o=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(o.entries()).forEach(([a,d])=>{s[d]===void 0&&(s[d]={layer:d,consumerIds:[]}),s[d].consumerIds.push(a)}),Object.keys(s).forEach(a=>{const d=s[a];l.log(`Switching max spatial layer to ${d.layer}`,{consumerIds:d.consumerIds}),this.roomNodeClient.switchConsumersToLayer(d.consumerIds,d.layer)})},2e3)),m(this,"refreshGridParticipants",cr((s=!1)=>{const o=new Map,a=Array.from(this.participants.joined.toArray().filter(R=>R.stageStatus==="ON_STAGE").map(R=>(o.set(R.id,!0),R.id))),d=this.selectedPeers.peers,h=this.participants.pinned.toArray().reduce((R,A)=>(A.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(A.id):R.push(A.id),R),[]);if(this.participants.viewMode!=="ACTIVE_GRID"){l.warn("ParticipantController::refreshGridParticipants::not_refreshing_grid_in_not_active_grid_mode");return}const p=this.self.stageStatus==="ON_STAGE"?1:0,f=this.participants.maxActiveParticipantsCount-p,g=new Set(d.concat(h).filter(R=>R!==this.self.id&&o.has(R)));let E=Array.from(g);const v=f-g.size;if(v>=0){const R=a.filter(A=>!g.has(A)&&A!==this.self.id).slice(0,v);E=Array.from(g).concat(R)}else E=E.slice(0,f);this.updateActiveParticipants(E,s)},500,{trailing:!0,leading:!0})),this.context=e,this.roomSocketHandler=n,this.participants=new St(e,r,this.roomSocketHandler,i),this.self=r,this.consumerPeerMap=new Map,r.config.viewType!=="CHAT"&&this.setupEventsGlobal()}get roomJoined(){var e;return((e=this.roomNodeClient)==null?void 0:e.roomJoined)===!0}waitingRoomRequestHandler(e){const r=e.requests.filter(i=>!this.participants.waitlisted.toArray().find(s=>s.userId===i.userId)),n=this.participants.waitlisted.toArray().filter(i=>!e.requests.find(s=>s.userId===i.userId));r.forEach(i=>this.participants.waitlisted.add(new Rr(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},this.self,this.roomSocketHandler))),n.forEach(i=>this.participants.waitlisted.delete(i.id))}get maxPreferredStreams(){return this.participants.maxActiveParticipantsCount}updateActive(e){return u(this,arguments,function*({page:r}){if(r&&r!==0){const{compulsoryPeers:n}=this.selectedPeers,i=n.filter(p=>this.participants.joined.has(p)),s=Array.from(this.participants.pinned.keys()).filter(p=>!i.includes(p)),o=Array.from(this.participants.joined.toArray().filter(p=>p.stageStatus==="ON_STAGE").map(p=>p.id)),a=Math.max((r-1)*(this.roomNodeClient.maxPreferredStreams-i.length-s.length)),d=r*(this.roomNodeClient.maxPreferredStreams-i.length-s.length),h=i.concat(s,o.slice(a,d));this.updatePageParticipants(h)}else b.emit(w.REFRESH_GRID)})}updatePageParticipants(e){const r=new Set(e),n=new Map(this.participants.active);this.participants.active.forEach((s,o)=>{this.participants.active.delete(o,!r.has(o))}),r.forEach(s=>{if(!this.participants.joined.get(s)){l.warn("updatePageParticipants::participant_not_in_joined_list",{dyteParticipant:{id:s}});return}this.participants.active.add(this.participants.joined.get(s),!n.get(s))}),this.currentActiveGridParticipants=new Set(this.participants.active.keys()),Array.from(n.keys()).forEach(s=>{if(r.has(s))return;const o=this.participants.joined.get(s);if(!o)return;const a={producers:o.producers,peerId:o.id};this.roomNodeClient.deactivatePeers(a)});const i=[];return this.participants.active.forEach(s=>{const o={peerId:s.id,producers:s.producers};i.push(o)}),this.roomNodeClient.activatePeers(i),{activePeers:n,peerIdsSet:r}}computeActivateParticipants(e,r){const n=e.map((s,o)=>({peerId:s,priority:o+1})),i=r==null?void 0:r.map((s,o)=>({peerId:s,priority:-(o+1)}));n.push(...i!=null?i:[]),n.length>0&&this.updateActiveParticipantsWithPriorities(n)}fromSocketService(e){var r,n,i,s;const o={};return(r=e.flags)!=null&&r.hiddenParticipant&&(o.hidden_participant=(n=e.flags)==null?void 0:n.hiddenParticipant),((i=e.flags)==null?void 0:i.recorderType)!==void 0&&((s=e.flags)==null?void 0:s.recorderType)!=="NONE"&&(o.recorder=!0),new Rr(this.context,ne(V({},e),{flags:o,id:e.peerId,isHost:!1,videoEnabled:!1,audioMuted:!0,videoTrack:void 0,audioTrack:void 0,picture:e.displayPictureUrl,stageStatus:Pa(e.stageType)}),this.self,this.roomSocketHandler)}onMediaJoined(e,r){return u(this,null,function*(){if(!this.roomJoined||e===this.self.id)return;const n=this.participants.joined.get(e);if(!n){l.warn(`Recieved media.peerJoinedBroadcast for non-existent peer ${e}`);return}r.forEach(i=>{i.kind===wt.AUDIO&&!i.screenShare?n.setAudioEnabled(!i.pause):i.kind===wt.VIDEO&&!i.screenShare&&n.setVideoEnabled(!i.pause),n.producers.push(ne(V({},i),{producingTransportId:i.producingTransportId,kind:i.kind===wt.AUDIO?"audio":"video"}))})})}updateActiveParticipantsMapMinReplacement(e){if(!this.roomJoined){l.warn("Skipped::ParticipantController::updateActiveParticipants",{roomJoined:this.roomJoined});return}const r=Array.from(this.participants.active.keys()),n=new Map(this.participants.active),i={};e.forEach(o=>{i[o]=!0});const s=[];r.forEach((o,a)=>{(!i[o]||!this.participants.joined.get(o))&&s.push(a)}),e.forEach(o=>{n.get(o)||(r.length<e.length?r.push(o):r[s.shift()]=o)}),r.forEach((o,a)=>{i[o]||r.splice(a,1)}),Array.from(this.participants.active.keys()).forEach(o=>{this.participants.active.delete(o,!i[o])}),r.forEach(o=>{if(!this.participants.joined.get(o)){l.warn("updateActiveParticipants::participant_not_in_joined_list",{dyteParticipant:{id:o}});return}this.participants.active.add(this.participants.joined.get(o),!n.get(o))}),this.participants.active.emit("participantsUpdate")}updatePinnedParticipants(){this.participants.pinned.forEach(e=>{e.setIsPinned(!1),this.participants.pinned.delete(e.id)})}setupEventsGlobal(){this.roomSocketHandler.on(j.joinRoom,({peer:e})=>{if(!e.waitlisted){if(this.context.getValue("viewType")==="LIVESTREAM"&&e.stageType!==1)return;this.onParticipantJoined(this.fromSocketService(e))}}),this.roomSocketHandler.on(j.leaveRoom,e=>{this.selectedPeers.delete(e.peer.peerId),this.onParticipantLeave(e.peer.peerId)}),b.on(w.SOCKET_SERVICE_ROOM_JOINED,()=>{this.self.permissions.acceptWaitingRequests&&this.roomSocketHandler.getWaitingRoomRequests()}),b.on(w.SOCKET_SERVICE_DISCONNECTED,()=>{Array.from(this.participants.joined.keys()).forEach(e=>{this.participants.joined.delete(e)}),Array.from(this.participants.active.keys()).forEach(e=>{this.participants.active.delete(e)}),Array.from(this.participants.pinned.keys()).forEach(e=>{this.participants.pinned.delete(e)}),this.participants.currentPage=0,this.participants.viewMode="ACTIVE_GRID",this.participants.emit("viewModeChanged",{viewMode:"ACTIVE_GRID",currentPage:this.participants.currentPage,pageCount:this.participants.pageCount}),this.currentActiveGridParticipants=new Set}),b.on(w.CONSUMER_PAUSED,({id:e})=>{this.processConsumerPaused(e)}),b.on(w.CONSUMER_RESUMED,({id:e})=>{this.processConsumerResumed(e)}),b.on(w.NEW_CONSUMER,({id:e})=>{this.processNewConsumer(e)}),b.on(w.CONSUMER_CLOSED,({id:e})=>{this.processConsumerClosed(e)}),b.on(w.ROOM_MESSAGE,e=>u(this,[e],function*({payload:r,type:n,timestamp:i}){this.participants.emit("broadcastedMessage",{type:n,payload:r,timestamp:i})})),b.on(w.MESSAGE,e=>u(this,[e],function*({payload:r,type:n,timestamp:i}){n!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:n,payload:r,timestamp:i})})),b.on(w.LOW_CONSUMER_SCORE,({peerId:e,score:r,kind:n})=>{const i=this.participants.joined.get(e);i&&(i.emit("poorConnection",{score:r,kind:n}),this.participants.emit("poorConnection",{participantId:e,score:r,kind:n}))}),b.on(w.CONSUMER_SCORE_UPDATE,({score:e,kind:r,appData:n,peerId:i})=>{var s;const o=r==="video"&&((s=n==null?void 0:n.screenShare)!=null?s:!1),a=this.participants.joined.get(i);a&&(a.emit("mediaScoreUpdate",{kind:r,isScreenshare:o,score:e,participantId:i}),this.participants.emit("mediaScoreUpdate",{kind:r,isScreenshare:o,score:e,participantId:i}))}),b.onAsync(w.KICK_PEER,e=>u(this,[e],function*({peerId:r}){const n=this.participants.joined.get(r);yield this.roomNodeClient.kick(r),yield this.roomSocketHandler.kick(r),n?n.emit("kicked"):this.participants.joined.emit("kicked",{id:r})})),b.on(w.UPDATE_ACTIVE,(...e)=>u(this,[...e],function*({page:r}={}){yield this.updateActive({page:r})}))}onParticipantPinned(e){return u(this,null,function*(){if(!e){this.self.isPinned&&this.self.setIsPinned(!1),this.participants.pinned.size!==0&&this.updatePinnedParticipants();return}if(e===this.self.id){this.participants.pinned.size!==0&&this.updatePinnedParticipants(),this.self.setIsPinned(!0);return}const r=this.participants.joined.get(e);this.self.isPinned&&this.self.setIsPinned(!1),this.updatePinnedParticipants(),r.setIsPinned(!0),this.participants.pinned.add(r)})}onParticipantJoined(e){return u(this,null,function*(){var r,n,i;this.self.id!==e.id&&!((r=e.flags)!=null&&r.recorder)&&!((n=e.flags)!=null&&n.hidden_participant)&&!((i=e.flags)!=null&&i.hiddenParticipant)&&(this.participants.active.delete(e.id),this.participants.joined.add(e),this.participants.waitlisted.delete(e.id),e.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&b.emit(w.UPDATE_STAGE_REQUESTS,{request:{displayName:e.name,userId:e.userId,peerId:e.id},add:!0})),b.emit(w.PEER_JOINED_INTERNAL,e),!(this.self.config.viewType===We.Webinar&&e.stageStatus!=="ON_STAGE")&&(this.roomNodeClient===void 0||this.participants.active.size>=this.roomNodeClient.maxPreferredStreams||this.updateActive({page:this.participants.currentPage}))})}onParticipantLeave(e){return u(this,null,function*(){const r=this.participants.joined.get(e);this.participants.joined.delete(e,!0,!0),this.participants.pinned.delete(e,!0,!0),this.participants.waitlisted.delete(e,!0,!0),r&&r.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&b.emit(w.UPDATE_STAGE_REQUESTS,{request:{displayName:r.name,userId:r.userId,peerId:r.id},add:!1});const{currentPage:n}=this.participants,i=this.maxPreferredStreams*(n-1),s=this.participants.active.get(e);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({page:n})})}processMedia(e){var r;const n=this.roomNodeClient.getConsumers(),{peerId:i,kind:s,appData:o,remotelyPaused:a,track:d,producerId:h,rtpReceiver:p}=(r=n.get(e))!=null?r:{};if(!i)return l.warn("processMedia::Peer ID is undefined",{consumer:{id:e,kind:s,peerId:i,appData:{supportsRemoteControl:o==null?void 0:o.supportsRemoteControl,screenShare:o==null?void 0:o.screenShare},remotelyPaused:a,producerId:h}}),{};const f=o;return s==="video"&&f.screenShare!==!0&&this.videoPeerConsumerMap.set(i,e),l.info("ParticipantController::processMedia",{consumer:{id:e,peerId:i,kind:s,appData:f,remotelyPaused:a,producerId:h}}),this.consumerPeerMap.set(e,{type:s,peerId:i,appData:f,remotelyPaused:a,producerId:h}),{peerId:i,kind:s,appData:f,remotelyPaused:a,track:d,producerId:h,rtpReceiver:p}}processConsumerClosed(e){const{peerId:r,type:n,appData:i,remotelyPaused:s,producerId:o}=this.consumerPeerMap.get(e)||{},a=this.participants.joined.get(r);if(l.info("ParticipantController::processConsumerClosed",{consumer:{id:e,peerId:r,appData:i,kind:n,remotelyPaused:s,producerId:o}}),this.consumerPeerMap.delete(e),n==="video"&&i.screenShare!==!0&&this.videoPeerConsumerMap.delete(r),!a)return;const d=[];i&&i.screenShare?(a.setScreenShareEnabled(!1),B.consumerSharedMediaState(e,{screen:!1}),a.screenShareTracks.video&&d.push(a.screenShareTracks.video.id),a.screenShareTracks.audio&&d.push(a.screenShareTracks.audio.id),a.screenShareTracks={audio:void 0,video:void 0}):n==="audio"?(a.setAudioEnabled(!1),a.audioTrack&&d.push(a.audioTrack.id),B.consumerSharedMediaState(e,{audio:!1}),a.audioTrack=void 0):n==="video"&&(a.setVideoEnabled(!1),a.videoTrack&&d.push(a.videoTrack.id),B.consumerSharedMediaState(e,{video:!1}),a.videoTrack=void 0),i.e2ee&&d.forEach(h=>{b.emit(w.E2EE_INACTIVE_CONSUMER,{peerId:r,trackId:h})})}processConsumerResumed(e){const{peerId:r,kind:n,appData:i,track:s,remotelyPaused:o,producerId:a,rtpReceiver:d}=this.processMedia(e);if(!r)return;l.info("ParticipantController::processConsumerResumed",{consumer:{id:e,peerId:r,kind:n,appData:i,remotelyPaused:o,producerId:a}});const h=this.participants.joined.get(r);if(h){if(i.e2ee&&b.emit(w.E2EE_ACTIVE_CONSUMER,{peerId:r,rtpReceiver:d,track:s}),i.screenShare){n==="video"?h.screenShareTracks.video=s:n==="audio"&&(h.screenShareTracks.audio=s),h.setScreenShareEnabled(!0),B.consumerSharedMediaState(e,{screen:!0});return}n==="video"?(h.videoTrack=s,h.setVideoEnabled(!0),B.consumerSharedMediaState(e,{video:!0})):n==="audio"&&(h.audioTrack=s,h.setAudioEnabled(h.audioEnabled),B.consumerSharedMediaState(e,{audio:h.audioEnabled}))}}processConsumerPaused(e){l.info(`ParticipantController::processConsumerPaused called for consumerId: ${e}`);const{peerId:r,kind:n,track:i,appData:s,remotelyPaused:o,producerId:a}=this.processMedia(e);if(!r)return;l.info("ParticipantController::processConsumerPaused",{consumer:{id:e,peerId:r,kind:n,appData:s,remotelyPaused:o,producerId:a}});const d=this.participants.joined.get(r);d&&(i&&s.e2ee&&b.emit(w.E2EE_INACTIVE_CONSUMER,{peerId:r,trackId:i.id}),n==="video"?(d.videoTrack=i,d.setVideoEnabled(!1),B.consumerSharedMediaState(e,{video:!1})):n==="audio"&&(d.audioTrack=i,d.setAudioEnabled(d.audioEnabled),B.consumerSharedMediaState(e,{audio:d.audioEnabled})))}processNewConsumer(e){const{peerId:r,kind:n,remotelyPaused:i,track:s,appData:o,producerId:a,rtpReceiver:d}=this.processMedia(e);if(!r)return;l.info("ParticipantController::processNewConsumer",{consumer:{id:e,peerId:r,kind:n,remotelyPaused:i,appData:o,producerId:a}});const h=this.participants.joined.get(r);if(h){if(o.screenShare){n==="video"?h.screenShareTracks.video=s:n==="audio"&&(h.screenShareTracks.audio=s),(!i||this.self.permissions.isRecorder||K.hasFeature(X.SCREEENSHARE_ERR_HACK))&&h.setScreenShareEnabled(!0),o.supportsRemoteControl&&(h.supportsRemoteControl=!0),this.participants.broadcastMessage("screenshareConsumerCreated",{producerId:a,peerId:r,screenShare:!0,consumerId:e,consumerPeerId:this.self.id}),l.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:e,peerId:r,kind:n,remotelyPaused:i,appData:o,producerId:a}});return}n==="video"?(h.videoTrack=s,i||h.setVideoEnabled(!0),B.consumerSharedMediaState(e,{video:!i})):n==="audio"&&(h.audioTrack=s,i||h.setAudioEnabled(!0),B.consumerSharedMediaState(e,{audio:!i})),!i&&o.e2ee&&b.emit(w.E2EE_ACTIVE_CONSUMER,{peerId:r,rtpReceiver:d,track:s})}}static formatSocketServiceMessage(e){var r,n,i,s;if(!e)return;const o=Pa(e.stageType);return{id:e.peerId,userId:e.userId,name:e.displayName,displayName:e.displayName,stageType:o,customParticipantId:e.customParticipantId,presetId:e.presetId,picture:e.displayPictureUrl,waitlisted:e.waitlisted,stageStatus:o,metadata:{preset_name:(r=e.flags)==null?void 0:r.presetName},recorderType:(n=e.flags)==null?void 0:n.recorderType,flags:{hiddenParticipant:(i=e.flags)==null?void 0:i.hiddenParticipant,recorder:!!((s=e.flags)!=null&&s.recorderType)}}}updateActiveParticipants(e,r=!1){if(this.updateActiveParticipantsMapMinReplacement(e),!this.roomJoined)return;l.info("ParticipantController::updateActiveParticipants::updating_current_selected_peers",{debuggingHint:r?"Forcefully updating currentActiveGridParticipants set":null}),r&&(this.currentActiveGridParticipants=new Set);const n=new Set(e),i=[],s=[];if(this.currentActiveGridParticipants.forEach(a=>{n.has(a)||i.push(a)}),n.forEach(a=>{this.currentActiveGridParticipants.has(a)||s.push(a)}),this.currentActiveGridParticipants=n,s.length===0&&i.length===0)return;const o=[];i.forEach(a=>{const d=this.participants.joined.get(a);if(!d)return;const h={producers:d.producers,peerId:d.id};o.push(this.roomNodeClient.deactivatePeers(h))}),Promise.all(o).then(()=>{const a=[];s.forEach(d=>{const h=this.participants.active.get(d);if(!h){l.warn("peer is not in active map which is going to activate, should not happen",{dyteParticipant:{id:d}});return}const p={peerId:h.id,producers:h.producers,force:r};a.push(p)}),this.roomNodeClient.activatePeers(a)}).catch(a=>{l.info("Error on deactivating peers",a)})}onSelectedPeers(e,r){return u(this,null,function*(){if(this.participants.viewMode!=="ACTIVE_GRID")return;const n=e.map((s,o)=>({peerId:s,priority:o+1})),i=r==null?void 0:r.map((s,o)=>({peerId:s,priority:-(o+1)}));n.push(...i!=null?i:[]),n.length>0&&this.updateActiveParticipantsWithPriorities(n)})}updateActiveParticipantsWithPriorities(e,r=!1){if(!this.roomJoined){l.warn("Skipped::ParticipantController::updateActiveParticipantsWithPriorities",{roomJoined:this.roomJoined});return}let n=null;e.forEach(i=>{this.selectedPeers.add(i.peerId,i.priority),(n===null||i.priority<n.priority)&&(n=i)}),n&&n.peerId!==this.participants.lastActiveSpeaker&&(this.participants.lastActiveSpeaker=n.peerId,this.participants.emit("activeSpeaker",{peerId:n.peerId,volume:n.priority})),r&&this.refreshGridParticipants()}}Xn([y.trace("updateActiveParticipantsMapMinReplacement")],gr.prototype,"updateActiveParticipantsMapMinReplacement",1),Xn([y.trace("ParticipantController.setupEvents")],gr.prototype,"setupEventsGlobal",1),Xn([y.trace("ParticipantController.processMedia")],gr.prototype,"processMedia",1),Xn([y.trace("ParticipantController.processConsumerClosed")],gr.prototype,"processConsumerClosed",1),Xn([y.trace("ParticipantController.processConsumerResumed")],gr.prototype,"processConsumerResumed",1),Xn([y.trace("ParticipantController.processConsumerPaused")],gr.prototype,"processConsumerPaused",1),Xn([y.trace("ParticipantController.processNewConsumer")],gr.prototype,"processNewConsumer",1);var JM=Object.defineProperty,qM=Object.getOwnPropertyDescriptor,KM=(t,e,r,n)=>{for(var i=n>1?void 0:n?qM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&JM(e,r,i),i};class wg extends gr{get roomNodeClient(){return this.context.getValue("roomNodeClient")}constructor(e,r,n,i){super(e,r,n,i),this.setupEvents()}setupEvents(){this.roomSocketHandler.on(j.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),b.on(w.SOCKET_PEERS,e=>u(this,null,function*(){e==null||e.forEach(r=>this.onParticipantJoined(this.fromSocketService(r)))})),this.roomSocketHandler.on(se.peerJoinedBroadcast,({participant:e})=>this.onMediaJoined(e.peerId,e.producerStates)),this.roomSocketHandler.on(se.selfJoinComplete,({participants:e,selectedPeers:r,roomState:n})=>{e.forEach(o=>this.onMediaJoined(o.peerId,o.producerStates));const{audioPeers:i,compulsoryPeers:s}=r!=null?r:{};n.pinnedPeerIds.length!==0&&this.onParticipantPinned(n.pinnedPeerIds[0]),this.computeActivateParticipants(i!=null?i:[],s),b.emit(w.REFRESH_GRID,!0)}),b.on(w.MAX_SPATIAL_LAYER_CHANGE,({peerId:e,maxSpatialLayer:r})=>{const n=this.videoPeerConsumerMap.get(e);n&&(this.maxSpatialLayerUpdates.set(n,r),this.updateConsumerSpatialLayers())}),b.on(w.REFRESH_GRID,(e=!1)=>{this.participants.viewMode==="ACTIVE_GRID"&&cr(()=>{this.refreshGridParticipants(e)},500,{maxWait:1e3,leading:!0})()}),b.on(w.NEW_PRODUCER,({peerId:e,producer:r})=>{const n=this.participants.joined.get(e);if(!n){l.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:r==null?void 0:r.producerId,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}},dyteParticipant:{id:e}});return}n.producers.push(r),l.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}}),(r==null?void 0:r.kind)==="audio"||r!=null&&r.screenShare||this.currentActiveGridParticipants.has(e)?this.roomNodeClient.createConsumer(e,r).catch(i=>{l.error("ParticipantController::createConsumer failed",{error:i})}):l.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}})}),b.on(w.PRODUCER_CLOSED,({peerId:e,producerId:r})=>{const n=this.participants.joined.get(e);if(!n){l.warn("ParticipantController::NEW_PRODUCER::participant not found",{dyteParticipant:{id:e}});return}n.producers=n.producers.filter(i=>i.producerId!==r)}),b.on(w.PRODUCER_TOGGLE,({peerId:e,producerId:r,paused:n,kind:i})=>{const s=this.participants.joined.get(e);if(s){i==="audio"&&s.setAudioEnabled(!n);const o=s.producers.find(a=>a.producerId===r);o&&(o.pause=n)}}),this.roomSocketHandler.on(se.globalPeerPinBroadcast,({participantId:e})=>{if(!this.roomJoined)return;const r=e;this.onParticipantPinned(r);const n=this.participants.joined.get(r);this.roomNodeClient.activatePeers([{peerId:n.id,producers:n.producers}]).catch(i=>{l.error("unable to create consumers",{error:i})})}),this.roomSocketHandler.on(se.selectedPeer,({audioPeers:e,compulsoryPeers:r})=>{this.roomJoined&&this.onSelectedPeers(r.concat(e))}),this.roomSocketHandler.on(se.selectedPeerDiff,({entries:e})=>{if(!this.roomJoined||this.participants.viewMode!=="ACTIVE_GRID")return;const r=e.map(n=>({peerId:n.peerId,priority:n.priority}));this.updateActiveParticipantsWithPriorities(r,!0)})}}KM([y.trace("ParticipantController.setupEvents")],wg.prototype,"setupEvents",1);var zM=Object.defineProperty,YM=Object.getOwnPropertyDescriptor,QM=(t,e,r,n)=>{for(var i=n>1?void 0:n?YM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&zM(e,r,i),i};class Cg extends gr{get roomNodeClient(){return this.context.getValue("roomNodeClient")}constructor(e,r,n,i){super(e,r,n,i),this.setupEvents()}setupEvents(){this.roomSocketHandler.on(j.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),b.on(w.SOCKET_PEERS,e=>u(this,null,function*(){e==null||e.forEach(r=>{r.waitlisted||this.onParticipantJoined(this.fromSocketService(r))})})),this.roomSocketHandler.on(ie.peerJoinedBroadcast,({participant:e})=>this.onMediaJoined(e.peerId,e.producerStates)),this.roomSocketHandler.on(ie.selfJoinComplete,({participants:e,selectedPeers:r,roomState:n})=>{e.forEach(o=>this.onMediaJoined(o.peerId,o.producerStates));const{audioPeers:i,compulsoryPeers:s}=r!=null?r:{};n.pinnedPeerIds.length!==0&&this.onParticipantPinned(n.pinnedPeerIds[0]),this.computeActivateParticipants(i!=null?i:[],s),b.emit(w.REFRESH_GRID,!0)}),b.on(w.MAX_SPATIAL_LAYER_CHANGE,({peerId:e,maxSpatialLayer:r})=>{const n=this.videoPeerConsumerMap.get(e);n&&(this.maxSpatialLayerUpdates.set(n,r),this.updateConsumerSpatialLayers())}),b.on(w.REFRESH_GRID,(e=!1)=>{this.participants.viewMode==="ACTIVE_GRID"&&this.refreshGridParticipants(e)}),b.on(w.NEW_PRODUCER,({peerId:e,producer:r})=>{const n=this.participants.joined.get(e);if(!n){l.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:r==null?void 0:r.producerId,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}},dyteParticipant:{id:e}});return}if(n.producers.push(r),l.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}}),this.participants.viewMode==="MANUAL"){let i=!1;const s=r.kind==="audio",o=r.kind==="video",a=n.manualProducerConfig;(s&&(a.audio&&!r.screenShare||a.screenshareAudio&&r.screenShare)||o&&(a.video&&!r.screenShare||a.screenshareVideo&&r.screenShare))&&(i=!0),i?this.roomNodeClient.createConsumer(e,r):l.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}});return}(r==null?void 0:r.kind)==="audio"||r!=null&&r.screenShare||this.currentActiveGridParticipants.has(e)?this.roomNodeClient.createConsumer(e,r).catch(i=>{l.error("ParticipantController::createConsumer failed",{error:i})}):l.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}})}),b.on(w.PRODUCER_CLOSED,({peerId:e,producerId:r})=>{const n=this.participants.joined.get(e);if(!n){l.warn("ParticipantController::NEW_PRODUCER::participant not found",{dyteParticipant:{id:e}});return}n.producers=n.producers.filter(i=>i.producerId!==r)}),b.on(w.PRODUCER_TOGGLE,({peerId:e,producerId:r,paused:n,kind:i})=>{const s=this.participants.joined.get(e);if(s){i==="audio"&&s.setAudioEnabled(!n);const o=s.producers.find(a=>a.producerId===r);o&&(o.pause=n)}}),this.roomSocketHandler.on(ie.globalPeerPinBroadcast,e=>{let r;if(e&&(r=e.participantId),!this.roomJoined)return;const n=r;this.onParticipantPinned(n);const i=this.participants.joined.get(n);i&&this.roomNodeClient.activatePeers([{peerId:i.id,producers:i.producers}]).catch(s=>{l.error("unable to create consumers",{error:s})})}),this.roomSocketHandler.on(ie.selectedPeer,({audioPeers:e,compulsoryPeers:r})=>{this.roomJoined&&this.onSelectedPeers(r.concat(e))}),this.roomSocketHandler.on(ie.selectedPeerDiff,({entries:e})=>{if(!this.roomJoined||this.participants.viewMode!=="ACTIVE_GRID")return;const r=e.map(n=>({peerId:n.peerId,priority:n.priority}));this.updateActiveParticipantsWithPriorities(r,!0)})}}QM([y.trace("ParticipantController.setupEvents")],Cg.prototype,"setupEvents",1);const we=dr(Ld().permissions);var G,Zs,eo,$l,Rt,xt;const to=class extends Dt{constructor(t,e,r,n=!1){if(super(),_(this,Rt),_(this,G,void 0),_(this,Zs,void 0),_(this,eo,void 0),_(this,$l,i=>{const s=i,{chat:o,connectedMeetings:a,plugins:d,polls:h,media:p}=s,f=Ro(s,["chat","connectedMeetings","plugins","polls","media"]);let g=!1;o&&(i.chat.private&&jr(c(this,G).chat.private,i.chat.private),i.chat.public&&jr(c(this,G).chat.public,i.chat.public),g=!0,this.emit("chatUpdate")),a&&(g=!0,jr(c(this,G).connectedMeetings,i.connectedMeetings)),p&&(g=!0,jr(c(this,G).media,i.media)),d&&(jr(c(this,G).plugins,i.plugins),g=!0,this.emit("pluginsUpdate")),h&&(jr(c(this,G).polls,i.polls),g=!0,this.emit("pollsUpdate")),Object.keys(f).length!==0&&(jr(c(this,G),f),g=!0),g&&this.emit("permissionsUpdate")}),!e)throw l.error("DytePermissionsPreset::load_preset_permissions_failed"),new C("Could not load preset permissions.");T(this,eo,t),T(this,Zs,r),T(this,G,e),n&&this.setupEvents()}setupEvents(){b.on(w.UPDATE_PERMISSIONS,c(this,$l))}static fromResponse(t,e,r){return new to(r,t,e,!0)}static default(t,e){return new to(t,we,e)}static init(t,e,r){let n;return r?n=new to(t,r,e,!0):n=new to(t,we,e),n}get mediaRoomType(){const{sfu:t}=c(this,eo).getValue("roomNodeOptions");return t===Qi.CF?"CF":"HIVE"}get stageEnabled(){var t;return((t=c(this,G))==null?void 0:t.stageEnabled)||c(this,Zs)===We.Webinar||c(this,Zs)===We.Livestream}get acceptStageRequests(){var t,e;return this.stageEnabled?((t=c(this,G))==null?void 0:t.acceptStageRequests)||((e=c(this,G))==null?void 0:e.canAcceptProductionRequests):!1}get stageAccess(){var t,e,r;return((t=c(this,G))==null?void 0:t.stageAccess)===q.NotAllowed?q.NotAllowed:((e=c(this,G))==null?void 0:e.stageAccess)===q.CanRequest?q.CanRequest:((r=c(this,G))==null?void 0:r.stageAccess)===q.Allowed||c(this,G).media.audio.canProduce===q.Allowed||c(this,G).media.video.canProduce===q.Allowed||c(this,G).media.screenshare.canProduce===q.Allowed?q.Allowed:c(this,G).media.audio.canProduce===q.CanRequest||c(this,G).media.video.canProduce===q.CanRequest||c(this,G).media.screenshare.canProduce===q.CanRequest?q.CanRequest:q.NotAllowed}get acceptWaitingRequests(){var t,e;return(e=(t=c(this,G))==null?void 0:t.acceptWaitingRequests)!=null?e:we.acceptWaitingRequests}get requestProduceVideo(){var t,e,r;return((r=(e=(t=c(this,G))==null?void 0:t.media)==null?void 0:e.video)==null?void 0:r.canProduce)===q.CanRequest}get requestProduceAudio(){var t,e,r;return((r=(e=(t=c(this,G))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.canProduce)===q.CanRequest}get requestProduceScreenshare(){var t,e,r;return((r=(e=(t=c(this,G))==null?void 0:t.media)==null?void 0:e.screenshare)==null?void 0:r.canProduce)===q.CanRequest}get canAllowParticipantAudio(){var t,e;return(e=(t=c(this,G))==null?void 0:t.disableParticipantAudio)!=null?e:we.disableParticipantAudio}get canAllowParticipantScreensharing(){var t,e;return(e=(t=c(this,G))==null?void 0:t.canAcceptProductionRequests)!=null?e:we.canAcceptProductionRequests}get canAllowParticipantVideo(){var t,e;return(e=(t=c(this,G))==null?void 0:t.disableParticipantVideo)!=null?e:we.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var t,e;return(e=(t=c(this,G))==null?void 0:t.kickParticipant)!=null?e:we.kickParticipant}get pinParticipant(){var t,e;return(e=(t=c(this,G))==null?void 0:t.pinParticipant)!=null?e:we.pinParticipant}get canRecord(){var t,e;return(e=(t=c(this,G))==null?void 0:t.canRecord)!=null?e:we.canRecord}get waitingRoomType(){var t,e;return(e=(t=c(this,G))==null?void 0:t.waitingRoomType)!=null?e:we.waitingRoomType}get waitingRoomBehaviour(){var t,e;return(e=(t=c(this,G))==null?void 0:t.waitingRoomType)!=null?e:we.waitingRoomType}get plugins(){var t,e;return(e=(t=c(this,G))==null?void 0:t.plugins)!=null?e:we.plugins}get polls(){var t,e;return(e=(t=c(this,G))==null?void 0:t.polls)!=null?e:we.polls}get produceVideo(){return this.canProduceVideo}get requestProduce(){return c(this,G).media.audio.canProduce===q.CanRequest||c(this,G).media.video.canProduce===q.CanRequest||c(this,G).media.screenshare.canProduce===q.CanRequest}get canProduceVideo(){var t;const e=(t=c(this,G).media.video.canProduce)!=null?t:we.media.video.canProduce;return this.stageEnabled&&(c(this,Rt,xt)==="ACCEPTED_TO_JOIN_STAGE"||c(this,Rt,xt)==="ON_STAGE")&&e===q.CanRequest?q.Allowed:this.stageEnabled&&(c(this,Rt,xt)==="OFF_STAGE"||c(this,Rt,xt)==="REQUESTED_TO_JOIN_STAGE")&&e===q.Allowed?q.NotAllowed:e}get produceScreenshare(){return this.canProduceScreenshare}get canProduceScreenshare(){var t;const e=(t=c(this,G).media.screenshare.canProduce)!=null?t:we.media.screenshare.canProduce;return this.stageEnabled&&(c(this,Rt,xt)==="ACCEPTED_TO_JOIN_STAGE"||c(this,Rt,xt)==="ON_STAGE")&&e===q.CanRequest?q.Allowed:this.stageEnabled&&(c(this,Rt,xt)==="OFF_STAGE"||c(this,Rt,xt)==="REQUESTED_TO_JOIN_STAGE")&&e===q.Allowed?q.NotAllowed:e}get produceAudio(){return this.canProduceAudio}get canProduceAudio(){var t;const e=(t=c(this,G).media.audio.canProduce)!=null?t:we.media.audio.canProduce;return this.stageEnabled&&(c(this,Rt,xt)==="ACCEPTED_TO_JOIN_STAGE"||c(this,Rt,xt)==="ON_STAGE")&&e===q.CanRequest?q.Allowed:this.stageEnabled&&(c(this,Rt,xt)==="OFF_STAGE"||c(this,Rt,xt)==="REQUESTED_TO_JOIN_STAGE")&&e===q.Allowed?q.NotAllowed:e}get chatPublic(){var t,e,r;return(r=(e=(t=c(this,G))==null?void 0:t.chat)==null?void 0:e.public)!=null?r:we.chat.public}get chatPrivate(){var t,e,r;return(r=(e=(t=c(this,G))==null?void 0:t.chat)==null?void 0:e.private)!=null?r:we.chat.private}get chatChannel(){var t,e,r;return(r=(e=(t=c(this,G))==null?void 0:t.chat)==null?void 0:e.channel)!=null?r:we.chat.channel}get chatMessage(){var t,e,r;return(r=(e=(t=c(this,G))==null?void 0:t.chat)==null?void 0:e.message)!=null?r:we.chat.message}get connectedMeetings(){var t,e;return(e=(t=c(this,G))==null?void 0:t.connectedMeetings)!=null?e:we==null?void 0:we.connectedMeetings}get hiddenParticipant(){var t,e;return(e=(t=c(this,G))==null?void 0:t.hiddenParticipant)!=null?e:we.hiddenParticipant}get showParticipantList(){var t;return(t=c(this,G).showParticipantList)!=null?t:we.showParticipantList}get canChangeParticipantRole(){var t,e;return(e=(t=c(this,G))==null?void 0:t.canChangeParticipantPermissions)!=null?e:we.canChangeParticipantPermissions}get canChangeParticipantPermissions(){var t,e;return(e=(t=c(this,G))==null?void 0:t.canChangeParticipantPermissions)!=null?e:we.canChangeParticipantPermissions}get canChangeTheme(){return!1}get canPresent(){return c(this,G).media.audio.canProduce===q.Allowed||c(this,G).media.video.canProduce===q.Allowed||c(this,G).media.screenshare.canProduce===q.Allowed}get acceptPresentRequests(){return this.acceptStageRequests}get canEditDisplayName(){var t;return(t=c(this,G).canEditDisplayName)!=null?t:!1}get maxScreenShareCount(){return 1}get isRecorder(){return c(this,G).isRecorder}get canSpotlight(){return c(this,G).canSpotlight}get canLivestream(){return c(this,G).canLivestream}get transcriptionEnabled(){return c(this,G).transcriptionEnabled}};let XM=to;G=new WeakMap,Zs=new WeakMap,eo=new WeakMap,$l=new WeakMap,Rt=new WeakSet,xt=function(){return c(this,eo).getValue("stageStatus")};var Ig;class ZM extends Dt{constructor(){super(...arguments),m(this,"localMediaHandler"),_(this,Ig,void 0)}updatePermission(){return u(this,null,function*(){var e,r;const n=(h,p)=>{this.mediaPermissions[h]=p;const f={message:this.mediaPermissions[h],kind:h};p==="DENIED"?b.emit(w.MEDIA_PERMISSION_ERROR,f):b.emit(w.MEDIA_PERMISSION_UPDATE,f)};if(ye.getName()==="firefox")return;const i="microphone",s="camera",o=yield(e=navigator==null?void 0:navigator.permissions)==null?void 0:e.query({name:i}),a=yield(r=navigator==null?void 0:navigator.permissions)==null?void 0:r.query({name:s}),d=(h,p)=>{switch(p){case"granted":n(h,"ACCEPTED");break;case"denied":n(h,"DENIED");break;case"prompt":n(h,"NOT_REQUESTED");break}this.localMediaHandler.repopulateAvailableDevices()};o&&(o.onchange=()=>d("audio",o.state)),a&&(a.onchange=()=>d("video",a.state))})}populateMediaPermissionsInCallstats(e){return u(this,arguments,function*({message:r,kind:n}){B.onSafeInitialization(()=>{switch(n){case"audio":{B.mediaPermission("AUDIO",r),B.mediaPermission("SPEAKER",r);break}case"video":{B.mediaPermission("VIDEO",r);break}case"screenshare":{B.mediaPermission("SCREENSHARE",r);break}}})})}init(){return u(this,arguments,function*(e={},r=!1,n=null){var i,s,o,a,d;if(ye.init(),!this.localMediaHandler)try{let h=!0;if(n!=null&&n.getValue("defaults").mediaHandler)h=!1,this.localMediaHandler=n.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:p}=navigator;this.localMediaHandler=yield p.init()}else this.localMediaHandler=new It(n,e.constraints,(i=n==null?void 0:n.getValue("defaults"))==null?void 0:i.isNonPreferredDevice,(s=n==null?void 0:n.getValue("defaults"))==null?void 0:s.autoSwitchAudioDevice);if(b.on(w.MEDIA_PERMISSION_UPDATE,p=>u(this,null,function*(){if(this.populateMediaPermissionsInCallstats({message:p.message,kind:p.kind}),p.message==="NOT_REQUESTED")switch(p==null?void 0:p.kind){case"audio":this.rawAudioTrack&&(l.info("Disabling audio due to media permission update"),this.disableAudio());break;case"video":this.rawVideoTrack&&(l.info("Disabling video due to media permission update"),this.disableVideo());break;default:break}this.emit("mediaPermissionUpdate",p)})),b.on(w.MEDIA_PERMISSION_ERROR,p=>u(this,null,function*(){const{kind:f,message:g,constraints:E}=p;this.populateMediaPermissionsInCallstats({message:g,kind:f}),f==="audio"?(l.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):f==="video"&&(l.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),l.error("SelfController::mediaPermissionError",{error:{message:g},constraints:E,mediaPermissionsErrors:{kind:f,message:g}}),this.emit("mediaPermissionError",p),this.emit("mediaPermissionUpdate",{message:g,kind:f})})),h){l.info(`Setting up DyteSelfMedia streams using media handler. audio:${!!(e!=null&&e.audio)} video:${(o=e==null?void 0:e.video)!=null?o:!0}`);const p=this.localMediaHandler.setupStreams({video:(a=e==null?void 0:e.video)!=null?a:!0,audio:(d=e==null?void 0:e.audio)!=null?d:!0});r||(yield p)}}catch(h){l.error("DyteSelf::init::Failed To Setup Streams",{error:{name:h.name,message:h.message}})}})}get audioTrack(){return this.localMediaHandler.audioTrack}get rawAudioTrack(){return this.localMediaHandler.rawAudioTrack}get mediaPermissions(){return this.localMediaHandler.permissions}addAudioMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.addAudioMiddleware(e)})}removeAudioMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.removeAudioMiddleware(e)})}get videoTrack(){return this.localMediaHandler.videoTrack}get rawVideoTrack(){return this.localMediaHandler.rawVideoTrack}addVideoMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.addVideoMiddleware(e)})}setVideoMiddlewareGlobalConfig(){return u(this,arguments,function*(e={disablePerFrameCanvasRendering:!1}){return this.localMediaHandler.setVideoMiddlewareGlobalConfig(e)})}removeVideoMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.removeVideoMiddleware(e)})}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 u(this,null,function*(){yield this.localMediaHandler.enableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})}enableVideo(){return u(this,null,function*(){yield this.localMediaHandler.enableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})}disableAudio(){return u(this,null,function*(){this.localMediaHandler.disableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})}enableScreenShare(){return u(this,null,function*(){yield this.localMediaHandler.enableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})}disableScreenShare(){return u(this,null,function*(){yield this.localMediaHandler.disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})}disableVideo(){return u(this,null,function*(){yield this.localMediaHandler.disableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})}getCurrentDevices(){return this.localMediaHandler.getCurrentDevices()}getAudioDevices(){return u(this,null,function*(){return yield this.localMediaHandler.getAudioDevices()})}getVideoDevices(){return u(this,null,function*(){return yield this.localMediaHandler.getVideoDevices()})}getSpeakerDevices(){return u(this,null,function*(){return yield this.localMediaHandler.getSpeakerDevices()})}getDeviceById(e,r){let n;return r==="audio"?n="audioinput":r==="video"?n="videoinput":r==="speaker"&&(n="audiooutput"),this.localMediaHandler.getDeviceById(e,n)}setDevice(e){return u(this,null,function*(){switch(e.kind){case"audioinput":try{yield this.localMediaHandler.setAudioDevice(e)}catch(r){}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(r){}finally{this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})})}}Ig=new WeakMap;const ro={},sn={executeWithLock({methodName:t,lockName:e,timeout:r}){return(n,i,s)=>{const o=s.value;return s.value=function(...a){if(ro[e]){const p=new Error(`Unsupported concurrent calls on Dyte method: ${t}.`);throw p.name="UnsupportedConcurrentMethodExecution",l.error("DyteLocker::UnsupportedConcurrentMethodExecution",{error:{stack:p.stack},dyteLocker:{methodName:t,lockName:e}}),p}ro[e]=!0;const d=setTimeout(()=>delete ro[e],r),h=o.apply(this,a);return Promise.resolve(h).then(()=>{delete ro[e],clearTimeout(d)}).catch(()=>{delete ro[e],clearTimeout(d)}),h},s}}};var eD=Object.defineProperty,tD=Object.getOwnPropertyDescriptor,Pt=(t,e,r,n)=>{for(var i=n>1?void 0:n?tD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&eD(e,r,i),i},pc,Or,no,es,Ge,Ye,io,Gl,Rg,Pg;let ot=(Pg=class extends ZM{constructor(t,e,r,n,i){var s;super(),_(this,Ge),_(this,Gl),m(this,"name"),m(this,"picture"),m(this,"customParticipantId"),m(this,"waitlistStatus"),_(this,pc,void 0),_(this,Or,void 0),_(this,no,void 0),m(this,"role"),m(this,"userId"),m(this,"organizationId"),m(this,"supportsRemoteControl",!1),m(this,"device"),_(this,es,void 0),m(this,"presetName"),m(this,"roomState","init"),_(this,io,new Set),T(this,es,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=(s=e.customParticipantId)!=null?s:e.clientSpecificId,this.waitlistStatus="none",T(this,Or,r),T(this,pc,n),T(this,no,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=ye.isElectron(),this.device=ye.getDeviceInfo(),this.presetName=i,n.viewType!==We.Chat&&this.updatePermission(),this.updateVideo=this.updateVideo.bind(this)}get stageStatus(){return c(this,es).getValue("stageStatus")}get id(){return c(this,es).getValue("peerId")}static __init__(t,e,r,n,i,s=!1){return u(this,null,function*(){var o,a,d,h,p;let f=(a=(o=t.getValue("defaults"))==null?void 0:o.audio)!=null?a:!0,g=(h=(d=t.getValue("defaults"))==null?void 0:d.video)!=null?h:!0;r.canProduceAudio!=="ALLOWED"&&(f=!1),r.canProduceVideo!=="ALLOWED"&&(g=!1);const E=new ot(t,e,r,n,i);if(n.viewType===We.Chat)return E;const v=OA(n.mediaConstraints);return jr(v,(p=t.getValue("defaults"))==null?void 0:p.mediaConfiguration),yield E.init({audio:f,video:g,constraints:v},s,t),E.setupEvents(),E})}setupEvents(){this.on("videoUpdate",ue(this,Gl,Rg)),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",()=>u(this,null,function*(){if(l.info("DyteSelf::setupEvents::AUDIO_TRACK_CHANGE",V({},Bn(this))),this.roomJoined&&this.audioEnabled)try{yield c(this,Ge,Ye).shareMic(this.audioTrack)}catch(t){l.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",()=>u(this,null,function*(){if(l.info("DyteSelf::setupEvents::VIDEO_TRACK_CHANGE",V({},Bn(this))),this.roomJoined&&this.rawVideoTrack===void 0)l.info("DyteSelf::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&this.roomJoined)try{const t=yield c(this,Ge,Ye).shareWebcam(this.videoTrack);t&&t.id!==this.videoTrack.id&&K.hasFeature(X.EXP_RESHARE)&&(yield c(this,Ge,Ye).shareWebcam(this.videoTrack))}catch(t){l.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=>u(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",()=>u(this,null,function*(){if(!this.roomJoined){l.error("DyteSelf.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{yield c(this,Ge,Ye).shareScreen(this.screenShareTracks)}catch(t){l.error("DyteSelf::setupEvents::Error while sharing screen",{error:t}),this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare())}l.info("DyteSelf::setupEvents::SCREENSHARE_TRACK_CHANGE",V({},Bn(this))),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})),this.localMediaHandler.on("SCREENSHARE_ENDED",()=>u(this,null,function*(){l.log("Disabling screenshare due to SCREENSHARE_ENDED"),yield this.disableScreenShare(),l.info("DyteSelf::setupEvents::SCREENSHARE_ENDED",V({},Bn(this)))})),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{B.mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",()=>u(this,null,function*(){this.roomJoined&&(yield c(this,Ge,Ye).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),B.videoOff()}))}get permissions(){return c(this,Or)}get config(){return c(this,pc)}get roomJoined(){var t;return((t=c(this,Ge,Ye))==null?void 0:t.roomJoined)===!0}setName(t){if(!t)throw new C("Name cannot be empty.");this.name=t}setupTracks(){return u(this,arguments,function*(t={}){var e,r;return t.forceReset&&(c(this,Ge,Ye).stopAllProducers(),this.localMediaHandler.removeAllTracks()),this.localMediaHandler.setupStreams({video:(e=t.video)!=null?e:!0,audio:(r=t.audio)!=null?r:!0})})}destructMediaHandler(){return u(this,null,function*(){return this.localMediaHandler.destruct()})}removeDocumentEventListeners(){return u(this,null,function*(){return this.localMediaHandler.removeDocumentEventListeners()})}enableAudio(){return u(this,null,function*(){if(this.permissions.canProduceAudio!==q.NotAllowed&&!(c(this,Or).canProduceAudio===q.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if(yield this.localMediaHandler.enableAudio(),this.roomJoined&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{yield c(this,Ge,Ye).shareMic(this.audioTrack)}catch(t){l.error("DyteSelf::enableAudio::Error while sharing mic",{error:t}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return;c(this,Ge,Ye).unmuteSelf()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),B.audioOn()}})}enableVideo(){return u(this,null,function*(){if(c(this,Or).canProduceVideo!==q.NotAllowed&&!(c(this,Or).canProduceVideo===q.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if(yield this.localMediaHandler.enableVideo(),this.roomJoined&&this.stageStatus==="ON_STAGE")try{yield c(this,Ge,Ye).shareWebcam(this.videoTrack)}catch(t){l.error("DyteSelf::enableVideo::Error while sharing video",{error:t}),this.videoEnabled&&(yield this.localMediaHandler.disableVideo())}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),l.info("DyteSelf.enableVideo",V({},Bn(this))),B.videoOn()}})}updateVideoConstraints(t){return u(this,null,function*(){if(!this.localMediaHandler.updateVideoConstraints)throw new C("Unsupported");yield this.localMediaHandler.updateVideoConstraints(t)})}enableScreenShare(){return u(this,null,function*(){if(!this.roomJoined)throw new C("Can`t enable screenshare without joining room");if(c(this,Or).canProduceScreenshare!==q.NotAllowed&&!(c(this,Or).canProduceScreenshare===q.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 c(this,Ge,Ye).shareScreen(this.screenShareTracks)}catch(t){l.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 u(this,null,function*(){if(!this.localMediaHandler.updateScreenshareConstraints)throw new C("Unsupported");yield this.localMediaHandler.updateScreenshareConstraints(t)})}disableAudio(){return u(this,null,function*(){this.audioEnabled&&(this.localMediaHandler.disableAudio(),this.roomJoined&&c(this,Ge,Ye).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),B.audioOff())})}disableVideo(){return u(this,null,function*(){this.videoEnabled&&(yield this.localMediaHandler.disableVideo(),this.roomJoined&&(yield c(this,Ge,Ye).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),B.videoOff())})}disableScreenShare(){return u(this,null,function*(){this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare(),this.roomJoined&&(yield c(this,Ge,Ye).disableScreenShare()),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))})}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){T(this,no,t);const r=t?"pinned":"unpinned";e&&this.emit(r,this)}get isPinned(){return c(this,no)}pin(){return u(this,null,function*(){if(!this.roomJoined)throw new C("Can`t pin participants without joining room");return c(this,Ge,Ye).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!this.roomJoined)throw new C("Can`t unpin participants without joining room");return c(this,Ge,Ye).pinPeer(null)})}setDevice(t){return u(this,null,function*(){var e,r,n;if(!t)throw new C("No device selected");const i=this.getCurrentDevices();if(t.deviceId&&(((e=i==null?void 0:i.audio)==null?void 0:e.deviceId)===t.deviceId||((r=i==null?void 0:i.video)==null?void 0:r.deviceId)===t.deviceId||((n=i==null?void 0:i.speaker)==null?void 0:n.deviceId)===t.deviceId)&&(l.warn("DyteSelf.setDevice.setting_to_in_use_device",{devices:[t]}),K.hasFeature(X.SKIP_SETTING_IN_USE_DEVICE)))throw new C("Cannot set device currently in use");switch(t.kind){case"audioinput":try{yield this.localMediaHandler.setAudioDevice(t)}catch(s){this.roomJoined&&(yield c(this,Ge,Ye).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(s){this.roomJoined&&(yield c(this,Ge,Ye).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}})}cleanUpTracks(){var t,e,r,n;(t=this.audioTrack)==null||t.stop(),(e=this.rawAudioTrack)==null||e.stop(),(r=this.videoTrack)==null||r.stop(),(n=this.rawVideoTrack)==null||n.stop()}registerVideoElement(t){c(this,io).add(t),this.updateVideo(t)}deregisterVideoElement(t){t.srcObject=void 0,c(this,io).delete(t)}updateVideo(t){if(this.videoEnabled){if(this.videoTrack==null)return;const e=new MediaStream;e.addTrack(this.videoTrack),t.srcObject=e}else t.srcObject=void 0}},pc=new WeakMap,Or=new WeakMap,no=new WeakMap,es=new WeakMap,Ge=new WeakSet,Ye=function(){return c(this,es).getValue("roomNodeClient")},io=new WeakMap,Gl=new WeakSet,Rg=function(){Array.from(c(this,io)).forEach(this.updateVideo)},Pg);Pt([y.trace("DyteSelf.setupEvents")],ot.prototype,"setupEvents",1),Pt([y.trace("DyteSelf.setupTracks")],ot.prototype,"setupTracks",1),Pt([y.trace("DyteSelf.destructMediaHandler")],ot.prototype,"destructMediaHandler",1),Pt([y.trace("DyteSelf.removeDocumentEventListeners")],ot.prototype,"removeDocumentEventListeners",1),Pt([sn.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),y.trace("DyteSelf.enableAudio")],ot.prototype,"enableAudio",1),Pt([sn.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),y.trace("DyteSelf.enableVideo")],ot.prototype,"enableVideo",1),Pt([y.trace("DyteSelf.updateVideoConstraints")],ot.prototype,"updateVideoConstraints",1),Pt([y.trace("DyteSelf.enableScreenShare"),sn.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3})],ot.prototype,"enableScreenShare",1),Pt([y.trace("DyteSelf.updateScreenshareConstraints")],ot.prototype,"updateScreenshareConstraints",1),Pt([sn.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),y.trace("DyteSelf.disableAudio")],ot.prototype,"disableAudio",1),Pt([sn.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),y.trace("DyteSelf.disableVideo")],ot.prototype,"disableVideo",1),Pt([sn.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3}),y.trace("DyteSelf.disableScreenShare")],ot.prototype,"disableScreenShare",1),Pt([y.trace("DyteSelf.setDevice")],ot.prototype,"setDevice",1),ot=Pt([dt("1100")],ot);class rD extends mg{constructor(e){super(e),m(this,"sessionDescription"),this.sessionDescription=e.sessionDescription}}class nD extends Eg{}class iD extends yg{retryFailedConsumerCreationTasks(e){return u(this,null,function*(){return sc(e.map(r=>u(this,null,function*(){return fr(n=>u(this,null,function*(){return n>0&&l.warn(`retrying failed consumer creation task: ${JSON.stringify(r)}`),this.consumerCreationTask(V({},r))}))})))})}consumerCreationTask(e){return u(this,arguments,function*({consumerId:r,producerId:n,producingPeerId:i,producingTransportId:s,streamId:o,trackId:a,paused:d,screenShare:h,appData:p,kind:f,sessionDescription:g}){const E=`${o}:${f}`,v={consumerId:r,producerId:n,producingPeerId:i,producingTransportId:s,streamId:o,trackId:a,sessionDescription:g,appData:p,kind:f,paused:d,screenShare:h,name:"consumer creation task error",message:"consumer creation failed"};return new Promise((R,A)=>u(this,null,function*(){const L=setTimeout(()=>{this.consumerTrackEvents.delete(E),v.isTimedout=!0,A(v)},5e3),F=(I,S)=>{try{if(I.readyState==="ended")clearTimeout(L),A(v);else{const P=I;P.enabled=!0,this.handler.midTransceiverMap.set(S.mid,S);const N=new rD({id:r,localId:S.mid,track:P,paused:d,producerId:n,producingPeerId:i,handler:this.handler,appData:ne(V({},p),{screenShare:h,peerId:i}),reuseTrack:!0,rtpReceiver:S.receiver,producingTransportId:s,sessionDescription:g});this.consumers.set(r,N),N.once("close",()=>{this.consumers.delete(N.id),this.handler.midTransceiverMap.delete(S.mid)}),l.info("consumer created for ",{consumer:{id:r,kind:f,appData:{screenShare:h},peerId:i,producerId:n}}),this.observer.emit("newconsumer",N),clearTimeout(L),R(N)}}catch(P){l.warn("error while creating consumer:",P),clearTimeout(L),A(v)}},W=this.consumerTrackPool.get(r);if((W==null?void 0:W.length)===2){F(W[0],W[1]);return}const H=this.unknownTracksMap.get(E);H?(this.unknownTracksMap.delete(E),F(H.track,H.transceiver)):this.consumerTrackEvents.set(E,F),g&&(yield this.safeEmitAsPromise("negotiate",{description:g}))}))})}connect(){return u(this,null,function*(){try{const{offerSdp:e,callback:r}=yield this.handler.connect(),{answer:n}=yield this.safeEmitAsPromise("connect",{offer:e});if(yield r(n),!(yield this.isConnected))throw new Error("ice connection failed")}catch(e){throw l.error("transport failed to connect:",e),e}})}_ontrack(e){const{track:r,transceiver:n}=e;l.info(`track event received [trackId: ${r.id}]`);const i=`${n.mid}:${r.kind}`;r.addEventListener("ended",()=>{l.info(`rtc consumer track ended [trackId: ${r.id}]`),this.consumerTrackPool.delete(r.id),this.unknownTracksMap.delete(i)}),this.consumerTrackPool.set(r.id,[r,n]);const s=this.consumerTrackEvents.get(i);s?(s(r,n),this.consumerTrackEvents.delete(i)):(l.warn(`track event handler not found ${i}`),this.unknownTracksMap.set(i,e))}consume(e){return u(this,null,function*(){const{producers:r,producingPeerId:n}=e;if(l.debug(`consume() peerId: ${n}, producers: ${JSON.stringify(r)}`),this.closed)throw new it("closed");if(this.direction!=="recv")throw new Jn("not a receiving Transport");if(typeof e.producingPeerId!="string")throw new TypeError("missing producingPeerId");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(!(yield this.isConnected))return Promise.reject(new Error("Transport not connected"));const i=[],{consumersMap:s}=yield this.safeEmitAsPromise("consume_peer",{producingPeerId:n});return s.forEach((o,a)=>{const{consumerId:d,trackId:h,screenShare:p,paused:f,streamId:g,kind:E,appData:v,producingTransportId:R,sessionDescription:A}=o;i.push(this.consumerCreationTask({consumerId:d,trackId:h,streamId:g,kind:E,producerId:a,producingPeerId:n,producingTransportId:R,paused:f,screenShare:p,appData:v,sessionDescription:A}))}),sc(i)})}produce(){return u(this,arguments,function*({track:e,encodings:r,codecOptions:n,stopTracks:i=!0,disableTrackOnPause:s=!0,zeroRtpOnPause:o=!1,appData:a={}}={}){if(l.debug(`produce() [track:${e.id}]`),e){if(this.direction!=="send")throw new Jn("not a sending Transport");if(e.readyState==="ended")throw new it("track ended");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("produce")===0)throw new TypeError('no "produce" listener set into this transport');if(a&&typeof a!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!(yield this.isConnected))return Promise.reject(new Error("Transport not connected"));const{producerId:d,localId:h,rtpSender:p}=yield this.awaitQueue.push(()=>u(this,null,function*(){const{offerSdp:g,callback:E,sender:v,mid:R}=yield this.handler.send({track:e,encodings:r,codecOption:n,screenShare:a==null?void 0:a.screenShare}),{answer:A,producerId:L}=yield this.safeEmitAsPromise("produce",{offer:g,kind:e.kind,paused:s?!e.enabled:!1,appData:ne(V({},a||{}),{mid:R})}),F=yield E(A);return{producerId:L,localId:F,rtpSender:v}}),"producer"),f=new nD({id:d,localId:h,track:e,stopTracks:i,disableTrackOnPause:s,zeroRtpOnPause:o,appData:a,handler:this.handler,rtpSender:p});return this.producers.set(d,f),f.observer.on("close",()=>{this.producers.delete(f.id)}),this.emit("newproducer",f),this.observer.emit("newproducer",f),f})}}class sD extends Sg{createTransport({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,appData:o,config:a}){const d=gn(),h=new iD({id:d,direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,appData:o,handlerFactory:this.handlerFactory,config:a});return this._observer.emit("newtransport",h),h}}var Tt;class oD{constructor(e){_(this,Tt,void 0),T(this,Tt,e)}joinRoom(e,r,n=!1,i=null){return u(this,null,function*(){const s={roomUuid:e,displayName:r,prejoined:n};return i&&(s.location=i),(yield c(this,Tt).sendMessagePromiseWithTimeout({event:se.joinRoom,protobuf:Sm.toBinary(s),timeout:5e3})).payload})}connectTransport(e){return u(this,null,function*(){const r=(yield c(this,Tt).sendMessagePromise(se.createWebRTCTransport,vm.toBinary(e))).payload,{transportId:n,description:i}=Hd.fromBinary(r),s={sdp:i==null?void 0:i.sdp,type:i.type};return{transportId:n,answer:s}})}produce(e){return u(this,null,function*(){var r,n;const i=(yield c(this,Tt).sendMessagePromise(se.produce,bm.toBinary(e))).payload,s=Fm.fromBinary(i);return{answer:{sdp:(r=s==null?void 0:s.description)==null?void 0:r.sdp,type:(n=s==null?void 0:s.description)==null?void 0:n.type},producerId:s.producerId}})}consume(e){return u(this,null,function*(){const r=(yield c(this,Tt).sendMessagePromise(se.consume,_m.toBinary(e))).payload,{consumerIdsMap:{map:n},description:i}=xm.fromBinary(r);return{consumerStateMap:n,sessionDescription:i}})}closeProducer(e){return u(this,null,function*(){const r=(yield c(this,Tt).sendMessagePromise(se.closeProducer,Cm.toBinary(e))).payload,{description:n}=Um.fromBinary(r);return n})}closeConsumer(e){return u(this,null,function*(){return(yield c(this,Tt).sendMessagePromise(se.closeConsumer,Im.toBinary(e))).payload})}hostControlForPeer(e,r){return u(this,null,function*(){const n={audio:r==="audio",screeShare:!1,video:r==="video",participantId:e},i=(yield c(this,Tt).sendMessagePromise(se.hostControlPeer,Mm.toBinary(n))).payload;if(!i)return!1;const{status:s}=jm.fromBinary(i);return s==="success"})}hostControlForAll(e){return u(this,null,function*(){const r={audio:e==="audio",screenShare:!1,video:e==="video"},n=(yield c(this,Tt).sendMessagePromise(se.hostControlAllPeers,Dm.toBinary(r))).payload;if(!n)return!1;const{status:i}=Hm.fromBinary(n);return i==="success"})}kickAll(){return u(this,null,function*(){const e={},r=(yield c(this,Tt).sendMessagePromise(se.kickAll,Pm.toBinary(e))).payload;if(!r)return!1;const{status:n}=Bm.fromBinary(r);return n==="success"})}kickPeer(e){return u(this,null,function*(){const r=(yield c(this,Tt).sendMessagePromise(se.kickPeer,Rm.toBinary(e))).payload;if(!r)return!1;const{status:n}=Vm.fromBinary(r);return n==="success"})}changeDisplayName(e){return u(this,null,function*(){const r=(yield c(this,Tt).sendMessagePromise(se.changeDisplayName,Am.toBinary(e))).payload;if(!r)return!1;const{status:n}=Wm.fromBinary(r);return n==="success"})}notifySelfJoinComplete(){return u(this,null,function*(){const e={},r=(yield c(this,Tt).sendMessagePromise(se.selfJoinComplete,Tm.toBinary(e))).payload;return aa.fromBinary(r)})}}Tt=new WeakMap;const aD=2e3;var on;class cD extends ug{constructor(e,r){super(),m(this,"_device"),m(this,"_sendTransport"),m(this,"_recvTransport"),m(this,"_consumers"),m(this,"_producers"),m(this,"_producerStatus"),m(this,"_producerIdToConsumerIdMap"),m(this,"_socket"),m(this,"_socketHandler"),m(this,"_totalTransportReconnectionCount"),m(this,"_transportReconnectFailureCount"),m(this,"_consumerCreationFailureCount"),m(this,"_producerNotReadyFailureCount"),m(this,"_consumerNotBoundFailureCount"),m(this,"_transportDisconnectedTimer"),m(this,"_iceTransportPolicy","all"),m(this,"_transportConnectionFailCount",0),m(this,"lastConnectionTime",0),m(this,"transportConnectionStatus"),m(this,"transportState"),m(this,"transportDisconnected"),_(this,on,void 0),T(this,on,e),this._device=new sD({}),this._socket=r,this.transportState={consuming:{state:st.NEW,reconnected:!1},producing:{state:st.NEW,reconnected:!1}},this.transportDisconnected={consuming:!1,producing:!1},this._socketHandler=new oD(r),this.reset()}get socket(){return this._socket}get producers(){return this._producers}get consumers(){return this._consumers}get producerIdToConsumerIdMap(){return this._producerIdToConsumerIdMap}get cfSocketHandler(){return this._socketHandler}get sendTransport(){return this._sendTransport}get recvTransport(){return this._recvTransport}reset(){this._producers=new Map,this._consumers=new Map,this._producerStatus=new Map,this._producerIdToConsumerIdMap=new Map,this.transportConnectionStatus=new Map,this._transportReconnectFailureCount=0,this._consumerCreationFailureCount=0,this._totalTransportReconnectionCount=0,this._producerNotReadyFailureCount=0,this._consumerNotBoundFailureCount=0,this._transportDisconnectedTimer={consuming:void 0,producing:void 0}}setupTransports(e,r){return u(this,null,function*(){const n=yield je().getICEServers().catch(s=>(l.warn(`failed to get iceservers from server: ${s.message}`),[])),i=e.map(s=>{var o,a,d,h,p,f,g,E;const v=this.transportConnectionStatus.get(s);if(v&&!r)return v;switch(v&&r&&Yi.stop(v.id),s){case"send":{const R=Yi.execute(this.createSendTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(o=c(this,on).getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(h=(d=(a=c(this,on).getValue("defaults").mediaConfiguration)==null?void 0:a.audio)==null?void 0:d.enableHighBitrate)!=null?h:!1,enableStereo:(g=(f=(p=c(this,on).getValue("defaults").mediaConfiguration)==null?void 0:p.audio)==null?void 0:f.enableStereo)!=null?g:!1},iceTransportPolicy:this._iceTransportPolicy}));return this.transportConnectionStatus.set(s,R),R.value}case"recv":{const R=Yi.execute(this.createRecvTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(E=c(this,on).getValue("modules").e2ee)==null?void 0:E.enabled},iceTransportPolicy:this._iceTransportPolicy}));return this.transportConnectionStatus.set(s,R),R.value}default:return l.warn(`What are you thinking when passing this transportType: ${s}?`,{transport:{type:s}}),Promise.reject(Error("TYPE_OF_TRANSPORT_UNKNOWN"))}});return Promise.all(i).finally(()=>{e.forEach(s=>{this.transportConnectionStatus.delete(s)})})})}stopAllTransports(){var e,r,n,i;l.info(" closing all the transports"),(e=this._sendTransport)==null||e.close(),(r=this._sendTransport)==null||r.removeAllListeners(),(n=this._recvTransport)==null||n.close(),(i=this._recvTransport)==null||i.removeAllListeners(),this._sendTransport=void 0,this._recvTransport=void 0,this.reset()}createSendTransport(e){return u(this,null,function*(){var r,n,i,s;if(this._sendTransport&&this._sendTransport.connected){l.info("sendTransport::already_exists_in_connected_state",{transport:{id:(r=this._sendTransport)==null?void 0:r.id,serverId:(n=this._sendTransport)==null?void 0:n.serverId,type:"send"}});return}l.info("sendTransport::initializing_transport",{transport:{id:(i=this._sendTransport)==null?void 0:i.id,serverId:(s=this._sendTransport)==null?void 0:s.serverId,type:"send"}});const o=this._device.createSendTransport(e);this._transportDisconnectedTimer.producing=void 0,l.info("sendTransport::initialized_transport",{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}}),this.handleTransport(o,!1),l.info("sendTransport::connecting_transport",{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}});try{yield fr((a,d)=>u(this,null,function*(){this.socket.isConnected||d(new Error("socket is not connected")),o.connectionState==="closed"&&d(new Error("transport is closed")),a>0&&l.debug(`retrying transport connect, count: ${a}`,{transport:{id:o.id,serverId:o.serverId,type:"send"}});try{yield o.connect()}catch(h){throw l.error(`failed to connect send transport: ${o.id}`,{error:h,transport:{id:o.id,serverId:o.serverId,type:"send"}}),h.message==="ice connection failed"&&d(h),h}}),{delayTime:100,strategy:"exponential",maxRetryCount:K.hasFeature(X.ENABLE_CF_INFINITE_RETRIES)?1/0:3}),l.info("sendTransport::connected_transport",{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}}),this._transportReconnectFailureCount=Math.max(0,this._transportReconnectFailureCount-1),this._producerNotReadyFailureCount=0,this._sendTransport=o,B.onSafeInitialization(()=>{B.configureSendTransport(o)})}catch(a){throw l.error(`failed to connect send transport after retry:${o.id}`,{error:a,transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}}),o.close(),o.removeAllListeners(),this._transportReconnectFailureCount+=1,this.handleFailure(),a}})}createRecvTransport(e){return u(this,null,function*(){var r,n,i,s,o;if(this._recvTransport&&this._recvTransport.connected){l.info("recvTransport::already_exists_in_connected_state",{transport:{id:(r=this._recvTransport)==null?void 0:r.id,serverId:(n=this._recvTransport)==null?void 0:n.serverId,type:"recv"}});return}l.info("recvTransport::initializing_transport",{transport:{id:(i=this._recvTransport)==null?void 0:i.id,serverId:(s=this._recvTransport)==null?void 0:s.serverId,type:"recv"}});const a=this._device.createRecvTransport(ne(V({},e),{additionalSettings:ne(V({},(o=e.additionalSettings)!=null?o:{}),{rtcAudioJitterBufferMaxPackets:25,rtcAudioJitterBufferFastAccelerate:!0,rtcAudioJitterBufferMinDelayMs:20})}));this._transportDisconnectedTimer.consuming=void 0,l.info("recvTransport::initialized_transport",{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),this.handleTransport(a,!0),l.info("recvTransport::connecting_transport",{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}});try{yield fr((d,h)=>u(this,null,function*(){this.socket.isConnected||h(new Error("socket is not connected")),a.connectionState==="closed"&&h(new Error("transport is closed")),d>0&&l.debug(`retrying transport connect, count: ${d}`,{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}});try{yield a.connect()}catch(p){throw l.error(`fail to connect recv transport: ${a.id}`,{error:p,transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),p.message==="ice connection failed"&&h(p),p}}),{delayTime:100,strategy:"exponential",maxRetryCount:K.hasFeature(X.ENABLE_CF_INFINITE_RETRIES)?1/0:3}),l.info("recvTransport::connected_transport",{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),this._transportReconnectFailureCount=Math.max(0,this._transportReconnectFailureCount-1),this._consumerCreationFailureCount=0,this._consumerNotBoundFailureCount=0,this.producerIdToConsumerIdMap.clear(),this._recvTransport=a,B.onSafeInitialization(()=>{B.configureRecvTransport(a)})}catch(d){throw l.error(`failed to connect recv transport after retry:${a.id}`,{error:d,transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),a.close(),a.removeAllListeners(),this._transportReconnectFailureCount+=1,this.handleFailure(),d}})}handleTransport(e,r){if(e.on("connect",(n,i,s)=>u(this,[n,i,s],function*({offer:o},a,d){try{const h={consuming:r,description:{sdp:o.sdp,type:o.type,target:r?Mt.SUBSCRIBER:Mt.PUBLISHER}},{transportId:p,answer:f}=yield this._socketHandler.connectTransport(h);e.setServerId(p),a({answer:f})}catch(h){l.error(`${r?"consumer":"producer"} transport connection error:`,{error:h,transport:{id:e==null?void 0:e.id,serverId:e==null?void 0:e.serverId,type:r?"recv":"send"}}),d(h)}})),e.on("connectionstatechange",n=>u(this,null,function*(){this.updateTransportState({state:n,direction:r?"consuming":"producing"}),l.info(`${r?"consumer":"producer"} transport connectionState:`,{transport:{id:e==null?void 0:e.id,serverId:e==null?void 0:e.serverId,type:r?"recv":"send",status:n}});const i=()=>{this._transportDisconnectedTimer[r?"consuming":"producing"]!==void 0&&(clearTimeout(this._transportDisconnectedTimer[r?"consuming":"producing"]),this._transportDisconnectedTimer[r?"consuming":"producing"]=void 0)};switch(n){case"connected":i(),this.lastConnectionTime=performance.now();break;case"disconnected":this._transportDisconnectedTimer[r?"consuming":"producing"]=setTimeout(()=>{this.triggerTransportReconnection(e,r)},aD);break;case"failed":if(e.closed)return;i(),this.triggerTransportReconnection(e,r);break}})),e.on("icecandidate",n=>u(this,null,function*(){l.debug("sending icecandidate:",{iceCandidate:n})})),e.on("datachannel:events",(n,i)=>u(this,null,function*(){var s,o;l.debug("got data channel message on event:",{rtcChannel:{label:n,message:i}});try{switch(i.type){case"negotiation":{this.negotiateOverDC(i,ac(i),n,e);break}case"handshake":{const a={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,ac(i),a);break}case"consumer_toggle":{this.handleConsumerToggle(i.payload);break}case"hub-disconnect":{l.debug(`media hub disconnected, full_reconnect: ${(s=i.payload)==null?void 0:s.full_reconnect}`),((o=i.payload)==null?void 0:o.full_reconnect)===!0&&this.emit("rejoin");break}case"error":{this.handleErrorOverDC(i.payload,e.id);break}default:l.warn(`unknown event received from cf node, event: ${i.type}`);break}}catch(a){l.error(`Unable to handle the incoming datachannel message on channel ${n}`)}})),e.on("dc_error",()=>{e.direction==="recv"&&(l.warn("events datachannel did not open in 5s"),this.handleFailure())}),e.on("negotiate",(n,i,s)=>u(this,[n,i,s],function*({description:o},a,d){try{const h={sdp:o==null?void 0:o.sdp,type:o==null?void 0:o.type},p=yield this.negotiate(e,h);a({answer:p})}catch(h){l.error("negotiate error:",{transport:{id:e.id,serverId:e.serverId,type:e.direction},error:h}),d(h)}})),!r){e.on("produce",(n,i,s)=>u(this,[n,i,s],function*({offer:o,kind:a,paused:d,appData:h},p,f){var g;const E=Kc(o.sdp).media.filter(R=>a==="video"?R.type==="video":R.type==="audio").at(-1).msid,v={description:{sdp:o.sdp,type:o.type,target:Mt.PUBLISHER},paused:d,kind:a,msid:E,appData:JSON.stringify(h),screenShare:(g=h.screenShare)!=null?g:!1};try{const{answer:R,producerId:A}=yield this._socketHandler.produce(v);p({answer:R,producerId:A})}catch(R){l.error("create producer error:",{error:R}),f(R)}}));return}e.on("consume_peer",(n,i,s)=>u(this,[n,i,s],function*({producingPeerId:o},a,d){l.info("consumePeer:",o);const h={producingPeerId:o};try{const p=yield this._socketHandler.consume(h);l.debug(`consumePeer response for ${o}:`,{consumerStateMap:p.consumerStateMap});const f=new Map;Object.entries(p.consumerStateMap).forEach(([g,E])=>{var v,R,A;let L={};try{L=JSON.parse(E.producerState.appData)}catch(F){}f.set(g,{consumerId:E.consumerId,trackId:(v=E.producerTrack)==null?void 0:v.trackId,streamId:E.producerTrack.streamId,kind:E.producerState.kind===wt.VIDEO?"video":"audio",appData:L,screenShare:(R=E.producerState)==null?void 0:R.screenShare,paused:(A=E.producerState)==null?void 0:A.pause,sessionDescription:p.sessionDescription})}),a({consumersMap:f})}catch(p){l.error("consumePeer error:",{error:p}),d(p)}})),e.on("consume",(n,i,s)=>u(this,[n,i,s],function*({producerId:o,producingPeerId:a},d,h){var p,f,g,E,v,R,A,L,F;const W={producingPeerId:a,producerId:o};try{const H=yield this._socketHandler.consume(W),I=H.consumerStateMap[o];let S={};try{S=JSON.parse((p=I.producerState)==null?void 0:p.appData)}catch(P){}l.info("consumer create response:",{consumer:{remotelyPaused:(f=I.producerState)==null?void 0:f.pause,producerId:(g=I.producerState)==null?void 0:g.producerId,kind:(v=(E=I.producerState)==null?void 0:E.kind)==null?void 0:v.toString(),appData:ne(V({},S),{screenShare:(R=I.producerState)==null?void 0:R.screenShare}),id:I.consumerId,sessionDescription:H.sessionDescription},consumerState:I}),d({consumerId:I.consumerId,screenShare:(A=I.producerState)==null?void 0:A.screenShare,trackId:(L=I.producerTrack)==null?void 0:L.trackId,streamId:I.producerTrack.streamId,kind:I.producerState.kind===wt.VIDEO?"video":"audio",paused:(F=I.producerState)==null?void 0:F.pause,appData:S,sessionDescription:H.sessionDescription})}catch(H){l.error("error during consuming on server:",H),h(H)}}))}createProducer(e,r,n){return u(this,null,function*(){var i;if(this._sendTransport===void 0||this._sendTransport.closed)return null;l.info("createProducer::initializing_producer",{producer:{id:"TO_BE_CREATED",kind:e,status:"initializing",appData:r==null?void 0:r.appData}});const s=this._producerStatus.get(e);if((s==null?void 0:s.trackId)===r.track.id&&(s==null?void 0:s.status)===Pr.INITIALIZING)return l.info("createProducer::producer getting initializing",{producer:{id:"GETTING_CREATED",status:"initializing",kind:e,appData:r==null?void 0:r.appData}}),null;this._producerStatus.set(e,{trackId:r.track.id,status:Pr.INITIALIZING});try{const o=yield this._sendTransport.produce(r);return(i=r.appData)!=null&&i.e2ee&&b.emit(w.E2EE_ACTIVE_PRODUCER,o),l.info("createProducer::initialized_producer",{producer:{id:o==null?void 0:o.id,kind:e,status:"producing",appData:r==null?void 0:r.appData}}),o.on("close",(a,d)=>u(this,[a,d],function*({offer:h,reason:p},f){l.info("producer::closing",{debuggingHint:p,producer:{id:o==null?void 0:o.id,kind:e,status:"closing",appData:r==null?void 0:r.appData}});const g={producerId:o.id,description:{sdp:h.sdp,type:h.type,target:Mt.PUBLISHER}};try{const E=yield this._socketHandler.closeProducer(g),v={sdp:E==null?void 0:E.sdp,type:E==null?void 0:E.type};l.info("producer::closed",{producer:{id:o==null?void 0:o.id,kind:e,status:"closed",appData:r==null?void 0:r.appData}}),f({answer:v})}catch(E){l.error("producer close error",E)}this._producerStatus.delete(e),this._producers.delete(e),n(),this.reconfigureWebcamLayers()})),o.on("trackended",()=>{l.info("producer::trackended",{producer:{id:o==null?void 0:o.id,kind:e,status:"UNKNOWN",appData:o==null?void 0:o.appData}}),[Q.MIC,Q.WEBCAM].includes(e)||n()}),this._producers.set(e,o),this._producerStatus.set(e,{trackId:r.track.id,status:Pr.INITIALIZED}),this.reconfigureWebcamLayers(),o.track}catch(o){throw this._producerStatus.set(e,{status:Pr.NOT_INITIALIZED,trackId:r.track.id}),l.error("createProducer::transport_initialization_failed",{producer:{id:"FAILED_TO_CREATE",kind:e,status:"failed",appData:r==null?void 0:r.appData,error:o}}),o}})}reconfigureWebcamLayers(){return u(this,null,function*(){if(!K.hasFeature(X.DISABLE_WEBCAM_LAYERS_ON_SCREENSHARE))return;const e=this.producers.get(Q.WEBCAM);e&&(yield this._switchProducerSpatialLayer(e,this.producers.get(Q.SCREENSHARE_VIDEO)?0:3))})}_switchProducerSpatialLayer(e,r){return u(this,null,function*(){try{l.debug("switching layer of webcam producer to:",{media:{video:{layer:r}},producer:{id:e.id,kind:e.kind,appData:e.appData}}),yield e.setMaxSpatialLayer(r)}catch(n){l.error("failed to switch spatial layer",{error:n})}})}_initConsumer(e){e&&(e.observer.on("close",r=>u(this,null,function*(){l.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),this._consumers.delete(e.id),b.emit(w.CONSUMER_CLOSED,{id:e.id})})),this._consumers.set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),b.emit(w.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId}))}createConsumer(e){return u(this,null,function*(){if(this._recvTransport===void 0||this._recvTransport.closed||!this._recvTransport.connected)return;const{producers:r,producingPeerId:n}=e;if(r.every(i=>this.getProducer(i.producerId))){l.warn("why are you creating a consumer for local producer?");return}yield fr(i=>u(this,null,function*(){i>0&&l.debug(`retrying consume call, retryCount: ${i}`),(yield this._recvTransport.consume({producingPeerId:n,producers:r}).catch(s=>{throw l.error("failed to consume:",{error:s}),s})).forEach(s=>{s.status==="rejected"?(l.error("consumer creation task is failing",s.reason),this._consumerCreationFailureCount+=1,setTimeout(this.handleFailure.bind(this),0)):this._initConsumer(s.value)})})).catch(i=>{l.error("create consumer failed after retries",{error:i}),this._consumerCreationFailureCount+=1,this.handleFailure()})})}pauseProducer(e){return u(this,null,function*(){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.pause(),r.appData.e2ee&&b.emit(w.E2EE_INACTIVE_PRODUCER,r),l.info(`Paused the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})})}resumeProducer(e){return u(this,null,function*(){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.resume(),l.info(`Resumed the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})})}replaceTrack(e,r){return u(this,null,function*(){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}yield n.replaceTrack({track:r}),l.info(`Replaced track for the producer of type: ${n.kind}`,{producer:{id:n.id,kind:n.kind,appData:n.appData,trackId:r.id}})})}removeProducer(e,r){return u(this,null,function*(){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}r&&n.track.stop(),yield this.sendTransport.awaitQueue.push(n.close.bind(n),"producer").then(()=>{c(this,on).getValue("modules").e2ee.enabled&&b.emit(w.E2EE_INACTIVE_PRODUCER,n)}).catch(i=>{l.error("failed to close producer on server",i)})})}pauseConsumer(e){return u(this,null,function*(){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}this.toggleConsumerOverDC(e,!0),l.info(`Paused the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})})}pauseConsumerOverSocket(e){return u(this,null,function*(){try{const r={consumerId:e.id,pause:!0};yield this.socket.sendMessagePromise(se.toggleConsumer,oa.toBinary(r)),e.pause(),b.emit(w.CONSUMER_PAUSED,{id:e.id}),l.info(`Paused the consumer of type: ${e.kind} over socket`,{consumer:{id:e.id,kind:e.kind,appData:e.appData}})}catch(r){l.error("error on pausing consumer",{error:r,consumer:{id:e.id,kind:e.kind,appData:e.appData}})}})}toggleConsumerOverDC(e,r){return u(this,null,function*(){const n={type:"consumer_toggle",payload:{consumerId:e,mute:r}},i=this._recvTransport.getDatachannel("events");if(!i){l.warn("recvTransport:: events datachannel not found");return}yield i.request(n),l.info(`HiveSFUHandler::consumer toggled, consumerId: ${e}, muted: ${r}`)})}resumeConsumer(e){return u(this,null,function*(){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}if(!r.paused){l.warn(`consumer with id:${e} is not paused so not resuming`);return}try{const n={consumerId:e,pause:!1};yield this.socket.sendMessagePromise(se.toggleConsumer,oa.toBinary(n)),r.resume(),b.emit(w.CONSUMER_RESUMED,{id:r.id}),l.info(`Resumed the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})}catch(n){l.error("error on resuming consumer",n)}})}closeConsumer(e,r){return u(this,null,function*(){return this.closeConsumers([e],r)})}closeConsumers(e,r=!1){return u(this,null,function*(){l.info(`Closing consumers: ${JSON.stringify(e)} with force: ${r}`);let n=!0;const i=e.filter(a=>this._consumers.get(a)?!0:(l.warn(`consumer with id: ${a} not found`),!1));if(!i.length)return;const s={consumerIds:i},o=()=>u(this,null,function*(){var a;return(a=this._recvTransport)==null?void 0:a.awaitQueue.push(()=>u(this,null,function*(){yield this._socketHandler.closeConsumer(s)}),"close_consumer").catch(d=>{l.warn("error on closing consumer:",{error:d}),n=r})});r?o():yield o(),n&&i.forEach(a=>{const d=this.consumers.get(a);this.producerIdToConsumerIdMap.delete(d.producerId),d.close(r?"force closed":void 0)})})}cleanupConsumers(e){return u(this,null,function*(){l.debug("cleaning up all consumers");const r=[];this._consumers.forEach(n=>{e?n.peerId===e&&r.push(n.id):r.push(n.id)}),this.closeConsumers(r,!0)})}stopAllProducers(){return u(this,null,function*(){l.info("stopping all available producers"),this._producers.forEach((e,r)=>{l.debug(`closing producer type: ${r}`,{producer:{id:e==null?void 0:e.id,kind:e.kind,appData:e.appData}}),e.close()})})}getProducer(e){return Array.from(this.producers.values()).filter(r=>r.id===e).at(0)}hasProducer(e){return this.getProducer(e)!==void 0}negotiate(e,r){return u(this,null,function*(){l.debug(`setting remote offer : ${JSON.stringify(r)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}});const n=yield e.setRemoteOffer(r),i={transportId:e.serverId,description:{sdp:n.sdp,type:n.type,target:Mt.SUBSCRIBER}};return l.debug(`sending renegotiate request: ${JSON.stringify(i)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),yield this.socket.sendMessagePromise(se.renegotiateSessionDescription,ym.toBinary(i)),l.info("renegotiation done",{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),n})}negotiateOverDC(e,r,n,i){return u(this,null,function*(){const{sdp:s}=e.payload,o={sdp:s,type:"offer"};try{l.debug(`got offer over dc: ${s} for transport: ${i.id}`);const a=yield i.setRemoteOffer(o),d={type:"answer",payload:{type:a.type,sdp:a.sdp}};l.debug(`datachannel answer: ${JSON.stringify(d)}`),i.sendResponseOverDC(n,r,d)}catch(a){l.error("datachannel:events::Error:",a),a.code!=="DC_NOT_FOUND"&&i.sendErrorOverDC(n,r,a)}})}handleConsumerToggle(e){const{mute:r,trackId:n}=e;l.info(`consumer toggled for trackId: ${n} muted: ${r}`);const i=this.consumers.get(n);if(!i){l.warn(`consumer with trackId: ${n} not found`);return}i.paused!==r&&(l.debug("consumer state is not same",{consumer:{id:i.id,remotelyPaused:i.paused}}),r?(i.pause(),b.emit(w.CONSUMER_PAUSED,{id:i.id})):(i.resume(),b.emit(w.CONSUMER_RESUMED,{id:i.id})))}handleErrorOverDC(e,r){return u(this,null,function*(){l.error(`got error over dc: ${JSON.stringify(e)} for transport: ${r}`);const{type:n,error:i,id:s}=e;if(n==="consumer"){if(i==="bind-fail"){if(this._consumerNotBoundFailureCount>=2){this.handleFailure();return}this._consumerNotBoundFailureCount+=1;const o=this.consumers.get(s);if(!o)return;try{yield this.closeConsumer(o.id),yield this.createConsumer({producers:[{kind:o.kind,pause:o.paused,producerId:o.producerId,producingTransportId:o.producingTransportId,screenShare:o.appData.screenShare}],producingPeerId:o.peerId})}catch(a){l.error("failed to recreate consumer on downtrack bound failure,",{consumer:{id:o.id,producerId:o.producerId,kind:o.kind,appData:o.appData}})}}}else if(n==="producer")if(i==="ready-fail"){if(this._producerNotReadyFailureCount>=2){this.handleFailure();return}this._producerNotReadyFailureCount+=1;const[o]=Array.from(this.producers.entries()).find(a=>a[1].id===s);if(!o)return;yield this.removeProducer(o).catch(a=>{l.error("failed to remove ready-fail producer:",{error:a,producer:{id:s,kind:o,appData:null}})})}else i==="general-failure"&&(this.updateTransportState({state:st.RECONNECTING,direction:"producing"}),this.emit("reconnect_transport",this._sendTransport))})}handleFailure(){return u(this,null,function*(){if(this._transportReconnectFailureCount>0||this._totalTransportReconnectionCount>3){l.warn("transport failure detected"),K.hasFeature(X.ENABLE_CF_EXPERIMENTAL_FAIL_RECOVERY)&&(l.debug("rejoining room"),this.emit("rejoin"));return}(this._consumerCreationFailureCount>0||this._consumerNotBoundFailureCount>=2)&&(l.warn("consumer creation failure detected or consumer not bound failure increased"),K.hasFeature(X.ENABLE_CF_EXPERIMENTAL_FAIL_RECOVERY)&&(l.debug("reconnecting recv transport"),this._totalTransportReconnectionCount+=1,this.updateTransportState({state:st.RECONNECTING,direction:"consuming"}),this.emit("reconnect_transport",this._recvTransport))),this._producerNotReadyFailureCount>=2&&(l.warn("producer receiver not getting added needs to reconnect send transport"),this._totalTransportReconnectionCount+=1,this.updateTransportState({state:st.RECONNECTING,direction:"producing"}),this.emit("reconnect_transport",this._sendTransport))})}triggerTransportReconnection(e,r){l.info("triggerTransportReconnection:: reconnecting transport",{transport:{type:e.direction,id:e.id,serverId:e.serverId}});const n=K.hasFeature(X.ENABLE_CF_TRANSPORT_RECONNECTION_ON_ICE_FAILED),i=K.hasFeature(X.CF_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED);n&&(i&&this._socket.isConnected&&(performance.now()-this.lastConnectionTime>2e4&&(this._transportConnectionFailCount=0),this._transportConnectionFailCount>2&&(l.warn("Multiple disconnections, forcing relay"),this._iceTransportPolicy="relay"),this._transportConnectionFailCount+=1),this.updateTransportState({state:st.RECONNECTING,direction:r?"consuming":"producing"}),this.emit("reconnect_transport",e))}switchConsumersToLayer(e,r){return u(this,null,function*(){const n=this._recvTransport.getDatachannel("events");if(!n){l.warn("events datachannel not found");return}const i={type:"switch_consumer_layer",payload:{consumerIds:e,layer:r}};yield n.request(i),l.info(`CFSFUHandler::consumer id: ${e} layer switched to ${r}`)})}updateTransportState(e){const{state:r,direction:n}=e;r==="disconnected"&&(this.transportDisconnected[n]=!0),this.transportState[n]={state:r,reconnected:r==="connected"?this.transportDisconnected[n]:this.transportState[n].reconnected},r==="connected"&&(this.transportDisconnected[n]=!1),b.emit(w.TRANSPORT_STATE_UPDATE,V({transport:n},this.transportState[n]))}}on=new WeakMap;var dD=Object.defineProperty,lD=Object.getOwnPropertyDescriptor,le=(t,e,r,n)=>{for(var i=n>1?void 0:n?lD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&dD(e,r,i),i};const ts={joinAttempted:!1},uD=5e3;var Re,pe,Nr,rs,Zn,ei,mc,fc,gc,an,so,ti,Lr,cn,Ag;const Mg=(Ag=class extends lg{constructor(t,e){var r,n;super(),_(this,Lr),_(this,Re,void 0),_(this,pe,void 0),_(this,Nr,void 0),_(this,rs,void 0),_(this,Zn,void 0),_(this,ei,void 0),_(this,mc,void 0),_(this,fc,void 0),_(this,gc,void 0),_(this,an,void 0),_(this,so,void 0),_(this,ti,void 0),m(this,"legacyMode"),m(this,"roomNodeUrl"),m(this,"peerDisplayName"),m(this,"activatedProducingPeerIds"),m(this,"e2ee"),m(this,"partialJoinRoomPromise"),this.context=t;const{roomName:i,authToken:s,legacyMode:o,socketClient:a,meetingTitle:d}=e;this.roomJoined=!1,this.roomName=i,this.authToken=s,this.legacyMode=o,this.meetingTitle=d,T(this,Re,a),T(this,Nr,!1),T(this,ti,void 0),T(this,pe,new cD(t,a)),this.maxPreferredStreams=6,this.activatedProducingPeerIds=new Set,T(this,an,new Set),T(this,rs,!1),T(this,Zn,0),T(this,ei,new Ki),this.e2ee=(n=(r=t.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?n:!1,B.legacySwitch(o),this.handleSocketEvents(),this.handleSFUEvents(),this.handleSocketConnectionEvents(),this.handleCallstatsEvents(),T(this,mc,cr(()=>u(this,null,function*(){if(!ts.joinAttempted)return;const{roomJoined:h}=yield this.joinRoom(this.peerDisplayName,this.roomUUID,{},!0,!0);h&&(b.emit(w.RESET_PRODUCER_STATE),b.emit(w.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3})),T(this,fc,cr(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports(["send"]),l.info("send transport reconected!"),b.emit(w.RESET_PRODUCER_STATE)}),1e3)),T(this,gc,cr(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports(["recv"]),l.info("recv transport reconnected!"),this.activatedProducingPeerIds=new Set,b.emit(w.REFRESH_GRID,!0)}),1e3))}get socketState(){return c(this,Re).connectionState}get mediaState(){return c(this,pe).transportState}static init(t,e){return u(this,null,function*(){const{legacyMode:r=!0,meetingId:n,authToken:i,meetingTitle:s,socket:o}=e;return new Mg(t,{legacyMode:r,authToken:i,socketClient:o,roomName:n,meetingTitle:s})})}get sfuHandler(){return c(this,pe)}get rejoinRoom(){return c(this,mc)}reset(t=!0){var e,r,n,i;(r=(e=c(this,pe))==null?void 0:e.cleanupConsumers)==null||r.call(e),(i=(n=c(this,pe))==null?void 0:n.stopAllProducers)==null||i.call(n),c(this,an).clear(),this.activatedProducingPeerIds.clear(),t&&(c(this,ei).stop(),this.sfuHandler.stopAllTransports(),this.sfuHandler.reset(),T(this,ei,new Ki))}reconnectTransport(t){return u(this,null,function*(){l.info(`CFNodeClient::Room joining state: ${c(this,Nr)}`),!(!t||c(this,Nr))&&(t.direction==="send"?yield c(this,fc).call(this,t):yield c(this,gc).call(this,t))})}setupTransports(t=!1){return u(this,null,function*(){yield c(this,pe).setupTransports(["recv","send"],t)})}stopAllProducers(){return u(this,null,function*(){yield c(this,pe).stopAllProducers()})}joinRoom(t,e){return u(this,arguments,function*(r,n,i={},s=!1,o=!1){ts.joinAttempted=!0,T(this,Nr,!0),this.reset(s);const a=je().ipInfo;if(a!=null&&a.loc&&!c(this,so)){const h=a.loc.split(",");T(this,so,{latitude:parseFloat(h[0]),longitude:parseFloat(h[1])})}let d;try{return d=yield c(this,ei).push(()=>this._joinRoom(r,n,i,o,c(this,so)),"joinRoom"),d}catch(h){d={roomJoined:!1}}return d.roomJoined||b.emit(w.ROOM_NODE_FAILED),d})}_partialJoinRoom(t,e,r=!1,n=void 0){return u(this,null,function*(){const i=je().ipInfo;let s=n;if(i!=null&&i.loc&&!n){const o=i.loc.split(",");s={latitude:parseFloat(o[0]),longitude:parseFloat(o[1])}}yield fr((o,a)=>(c(this,Re).isConnected||a(new Error("socket is not connected")),o>0&&l.warn(`retrying sending join room request, count: ${o}`),this.sfuHandler.cfSocketHandler.joinRoom(e,t,r,s).catch(d=>{throw l.error("failed to send join room request, error:",{error:d}),d})),{delayTime:1e3,strategy:"exponential",maxRetryCount:K.hasFeature(X.ENABLE_CF_INFINITE_RETRIES)?1/0:3}),yield this.setupTransports(!0)})}partialJoinRoom(t,e,r=!1,n=void 0){return u(this,null,function*(){this.partialJoinRoomPromise=c(this,ei).push(()=>this._partialJoinRoom(t,e,r,n))})}_joinRoom(t,e){return u(this,arguments,function*(r,n,i={},s=!1,o=null){this.peerDisplayName=r;try{return this.partialJoinRoomPromise?yield this.partialJoinRoomPromise:yield this._partialJoinRoom(r,n,s,o),K.hasFeature(X.INTERNAL_CALL_STATS)&&navigator.product!=="ReactNative"&&setTimeout(()=>u(this,null,function*(){const a={userId:this.context.getValue("userId"),peerId:this.peerId,displayName:r,roomUUID:n,roomViewType:"groupCall",roomName:this.roomName,deviceInfo:ne(V({},ye.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};B.roomJoined(a),i!=null&&i.audio?B.audioOn():B.audioOff(),i!=null&&i.video?B.videoOn():B.videoOff()})),{roomJoined:yield this.completeJoinRoom()}}catch(a){return l.error("error on sending join room request",{error:a}),{roomJoined:!1}}finally{this.partialJoinRoomPromise=void 0}})}completeJoinRoom(){return u(this,null,function*(){try{const{maxPreferredStreams:t,roomState:e}=yield this.sfuHandler.cfSocketHandler.notifySelfJoinComplete();return this.roomUUID=e.roomUuid,this.maxPreferredStreams=t!=null?t:6,T(this,Nr,!1),T(this,rs,!0),this.roomJoined=!0,b.emit(w.REFRESH_GRID,!0),!0}catch(t){return l.error("error on completing join room:",{error:t}),!1}})}leaveRoom(){return u(this,null,function*(){c(this,pe).stopAllTransports(),T(this,rs,!1),ts.joinAttempted=!1;const t={closeRoom:!1};c(this,Re).sendMessagePromise(se.leaveRoom,km.toBinary(t)).then(e=>{var r;(r=Lm.fromBinary(e.payload))!=null&&r.closed||l.warn("weird state on peer closed and should not happen")}).catch(e=>{l.error("error on sending leave room request",{error:e})}),B.callEnded(),y.destruct()})}getConsumers(){return c(this,pe).consumers}activatePeers(t){return u(this,null,function*(){const e=t.map(({peerId:r,producers:n,force:i})=>{if(n.length===0)return Promise.resolve();if(i)return this.consumePeer(r,n,i);const s=[];return n.every(o=>{const a=this.sfuHandler.producerIdToConsumerIdMap.get(o.producerId);if(!a)return!1;const d=this.sfuHandler.consumers.get(a);return d&&!o.pause&&d.paused&&s.push(a),!0})?s.length>0?this.resumeConsumers(s):Promise.resolve():this.consumePeer(r,n)});yield Promise.all(e)})}deactivatePeers(t){return u(this,null,function*(){if(l.info("deactivating producers"),t.producers.some(e=>e.screenShare&&e.kind==="video")){l.debug("peer is screensharing can't deactivate");return}t.producers.forEach(({producerId:e,kind:r})=>{if(r==="audio"){l.debug("we don't want to deactive audio consumers");return}const n=this.sfuHandler.producerIdToConsumerIdMap.get(e);if(!n){l.warn(`consumer not found in deactivate producers: ${e}`);return}this.sfuHandler.closeConsumer(n)}),this.activatedProducingPeerIds.delete(t.peerId)})}createConsumer(t,e){return u(this,null,function*(){return this.sfuHandler.createConsumer({producingPeerId:t,producers:[e]})})}pauseConsumers(t){return u(this,null,function*(){t.forEach(e=>{this.sfuHandler.pauseConsumer(e)})})}resumeConsumers(t){return u(this,null,function*(){t.forEach(e=>{this.sfuHandler.resumeConsumer(e)})})}closeConsumers(t){return u(this,null,function*(){const e=Array.from(this.getConsumers().values()).filter(r=>t.includes(r.peerId)).map(r=>r.id);return t.forEach(r=>{this.activatedProducingPeerIds.delete(r)}),this.sfuHandler.closeConsumers(e)})}consumePeer(t,e,r){return u(this,null,function*(){if(l.info(`current activated Peer ids: ${JSON.stringify(Array.from(this.activatedProducingPeerIds.values()))}, forced?:${r}`),!this.activatedProducingPeerIds.has(t)||r)try{yield c(this,pe).createConsumer({producingPeerId:t,producers:e}),this.activatedProducingPeerIds.add(t)}catch(n){l.error("consumePeer failed in CFNodeClient.ts",{error:n})}else l.info(`not creating consumer for this peerId: ${t}`)})}shareWebcam(t){return u(this,null,function*(){if(t===void 0)return null;if(c(this,pe).producers.has(Q.WEBCAM)){const i=c(this,pe).producers.get(Q.WEBCAM);if(!i.closed&&!navigator.isReactNative)return yield i.replaceTrack({track:t}),yield this.resumeWebcam(),t;yield c(this,pe).removeProducer(Q.WEBCAM)}const e={track:t,codecOptions:{name:"VP8"},appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1};let r=t.getConstraints().width;r in qf||(r=640),e.encodings=MA[r],K.hasFeature(X.ENABLE_CF_SIMULCAST)&&(e.encodings=qf[r]);const n=()=>{l.info("Disabling video due to the producer closure"),this.disableWebcam()};return c(this,pe).createProducer(Q.WEBCAM,e,n)})}shareScreen(t){return u(this,null,function*(){const{video:e,audio:r}=t;if(e===void 0)return;const n={track:e,codecOptions:{name:"VP8"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ye.isElectron()},stopTracks:!1};let i=()=>{l.info("Disabling screenShare due to the producer closure"),this.disableScreenShare()};if(yield c(this,pe).createProducer(Q.SCREENSHARE_VIDEO,n,i),r){const s={track:r,codecOptions:{name:"opus"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ye.isElectron()},stopTracks:!1,zeroRtpOnPause:!0};i=()=>{},yield c(this,pe).createProducer(Q.SCREENSHARE_AUDIO,s,i)}B.screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new it("track undefined");if(c(this,pe).producers.has(Q.MIC)){const n=c(this,pe).producers.get(Q.MIC);if(!n.closed&&!navigator.isReactNative){yield n.replaceTrack({track:t}),yield this.resumeMic();return}yield c(this,pe).removeProducer(Q.MIC,!1)}const e={track:t,encodings:[{priority:"high"}],codecOptions:{name:"opus"},appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!0},r=()=>{l.info("Disabling audio due to the producer closure"),this.disableMic()};yield c(this,pe).createProducer(Q.MIC,e,r)}catch(e){throw new C(e)}})}pauseMic(){const t=c(this,pe).producers.get(Q.MIC);if(!t){l.error("pauseMic::could_not_find_mic_producer");return}if(t.paused){l.info("pauseMic::mic_producer_already_paused");return}t.pause();const e={producerId:t.id,pause:!0};c(this,Re).sendMessage(se.toggleProducer,$r.toBinary(e))}pauseWebcam(){return u(this,null,function*(){const t=c(this,pe).producers.get(Q.WEBCAM);if(!t){l.error("pauseWebcam::could_not_find_webcam_producer");return}t.pause();const e={producerId:t.id,pause:!0};c(this,Re).sendMessage(se.toggleProducer,$r.toBinary(e))})}resumeMic(){return u(this,null,function*(){const t=c(this,pe).producers.get(Q.MIC);if(!t){l.error("resumeMic::could_not_find_mic_producer");return}if(!t.pause){l.info("resumeMic::mic_producer_already_resumed");return}t.resume(),t.appData.e2ee&&b.emit(w.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,Re).sendMessage(se.toggleProducer,$r.toBinary(e))})}resumeWebcam(){return u(this,null,function*(){const t=c(this,pe).producers.get(Q.WEBCAM);if(!t){l.error("resumeWebcam::could_not_find_webcam_producer");return}t.resume(),t.appData.e2ee&&b.emit(w.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,Re).sendMessage(se.toggleProducer,$r.toBinary(e))})}disableWebcam(){return u(this,null,function*(){yield c(this,pe).removeProducer(Q.WEBCAM)})}disableMic(){return u(this,null,function*(){yield c(this,pe).removeProducer(Q.MIC)})}disableScreenShare(){return u(this,null,function*(){l.info("screen_sharing_stopped"),B.screenShareStop(),yield c(this,pe).removeProducer(Q.SCREENSHARE_VIDEO),yield c(this,pe).removeProducer(Q.SCREENSHARE_AUDIO),c(this,an).clear()})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}unmuteSelf(){return u(this,null,function*(){})}resetVideoProducers(t,e){return u(this,null,function*(){t&&(yield c(this,pe).removeProducer(Q.WEBCAM,!1),this.shareWebcam(t)),e&&(yield c(this,pe).removeProducer(Q.SCREENSHARE_VIDEO,!1),this.shareScreen({video:e}))})}changeDisplayName(t,e){return u(this,null,function*(){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!(yield this.sfuHandler.cfSocketHandler.changeDisplayName(r)))throw new Error("failed to change display name!")})}kick(t){return u(this,null,function*(){const e={participantId:t};if(!(yield this.sfuHandler.cfSocketHandler.kickPeer(e)))throw new Error("failed to kickout the participant!")})}kickAll(){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.kickAll()))throw new Error("failed to kickout all participant!")})}muteAll(t){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.hostControlForPeer(t,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(t){return u(this,null,function*(){const e={participantId:t!=null?t:""};try{yield c(this,Re).sendMessagePromise(se.globalPinPeer,wm.toBinary(e))}catch(r){l.error("Error in pinning peer:",{error:r})}})}validateScreenShare(t){return this.peerId===t.peerId&&this.sfuHandler.hasProducer(t.producerId)&&c(this,an).add(t.consumerPeerId),c(this,an).size}switchConsumersToLayer(t,e){return u(this,null,function*(){this.sfuHandler.switchConsumersToLayer(t,e)})}handleSocketEvents(){return u(this,null,function*(){c(this,Re).on(se.peerProducerCreateBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:r}=Gm.fromBinary(t);if(e===this.peerId)return;l.info(`producer created broadcast: ${e}, producer state: ${r}`),b.emit(w.NEW_PRODUCER,{peerId:e,producer:ne(V({},r),{kind:r.kind===wt.AUDIO?"audio":"video"})})}catch(e){l.error("error in peer-producer-create-broadcast",{error:e})}}),c(this,Re).on(se.peerProducerToggleBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:{kind:r,pause:n,producerId:i}}=Jm.fromBinary(t),s=r===wt.AUDIO?"audio":"video";l.info(`producer toggle broadcast: ${e}, producerId: ${i}, kind:${s}, paused:${n}`),b.emit(w.PRODUCER_TOGGLE,{peerId:e,producerId:i,paused:n,kind:s}),Array.from(this.getConsumers().values()).filter(o=>o.producerId===i).forEach(o=>{o.paused!==n&&(l.debug(`consumer state mismatched for ${o.id}. updating consumer pause state ${o.paused} to ${n}`),n?(o.pause(),b.emit(w.CONSUMER_PAUSED,{id:o.id})):(o.resume(),b.emit(w.CONSUMER_RESUMED,{id:o.id})))})}catch(e){l.error("error in producer toggle broadcast handler",{error:e})}}),c(this,Re).on(se.peerLeaveBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e}=ca.fromBinary(t);if(e===this.peerId)return;l.info(`peer left broadcast:${e}`),c(this,an).delete(e),this.sfuHandler.cleanupConsumers(e)}catch(e){l.error("error in peer left broadcast",{error:e})}}),c(this,Re).on(se.peerProducerCloseBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:{producerId:r}}=qm.fromBinary(t);if(e===this.peerId)return;l.info(`producer closed broadcast:${e}`),b.emit(w.PRODUCER_CLOSED,{peerId:e,producerId:r});const n=this.sfuHandler.producerIdToConsumerIdMap.get(r);if(!n){l.warn(`no consumer found for producer:${r}`);return}l.info(`closing consumer ${n}, producer id: ${r}`),this.sfuHandler.closeConsumer(n).then(()=>{l.info(`closed consumer: ${n}`),this.sfuHandler.producerIdToConsumerIdMap.delete(r),b.emit(w.CONSUMER_CLOSED,{id:n})}).catch(i=>{l.error("error closing consumer",{error:i})})}catch(e){l.error("error on producer close broadcast",{error:e})}}),c(this,Re).on(se.mediaRoomTerminationBroadcastResponse,()=>{!this.roomJoined&&!c(this,Nr)&&!c(this,rs)||(l.warn("media hub termination broadcast received, rejoining room"),b.emit(w.ROOM_NODE_DISCONNECTED),this.rejoinRoom())})})}handleSocketConnectionEvents(){c(this,Re).onStateEvent("connected",()=>u(this,null,function*(){l.info("SocketService::Connected to socket-edge"),clearTimeout(c(this,ti)),T(this,ti,void 0),ue(this,Lr,cn).call(this,"connected")})),c(this,Re).onStateEvent("disconnected",({code:t,reason:e})=>{l.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e}});const{consuming:r,producing:n}=this.mediaState;r.state!==st.CONNECTED||n.state!==st.CONNECTED?b.emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:ts.joinAttempted}):T(this,ti,setTimeout(()=>{b.emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:ts.joinAttempted}),T(this,ti,void 0)},uD)),ue(this,Lr,cn).call(this,"disconnected"),this.roomJoined=!1}),c(this,Re).onStateEvent("reconnecting",()=>u(this,null,function*(){l.info("SocketService::Reconnecting to socket-edge"),ue(this,Lr,cn).call(this,"reconnecting")})),c(this,Re).onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){l.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),ue(this,Lr,cn).call(this,"reconnectAttempt",e)})),c(this,Re).onStateEvent("reconnectFailure",({attempt:t})=>{l.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),ue(this,Lr,cn).call(this,"reconnectFailure",t)}),c(this,Re).onStateEvent("reconnected",()=>u(this,null,function*(){l.info("SocketService::Reconnected to socket-edge",{connectionState:ts}),b.emit(w.SOCKET_SERVICE_RECONNECTED),ue(this,Lr,cn).call(this,"reconnected")})),c(this,Re).onStateEvent("failed",()=>u(this,null,function*(){l.info("SocketService::Failed to connect to socket-edge"),ue(this,Lr,cn).call(this,"failed")}))}handleSFUEvents(){c(this,pe).on("reconnect_transport",t=>u(this,null,function*(){try{yield this.reconnectTransport(t),l.info(`transport reconnected [id:${t.id}]`)}catch(e){l.error("error on reconnection transports",{error:e})}})),c(this,pe).on("rejoin",t=>{if(c(this,Zn)>3&&!t){l.warn("cannot rejoin more already rejoined 3 times");return}if(c(this,Nr)&&!t){l.warn("room joining in progress, cannot start rejoining");return}T(this,Zn,c(this,Zn)+1),l.warn(`rejoining the room because transports are failing. [rejoinCount: ${c(this,Zn)}]`),this.roomJoined=!1,b.emit(w.ROOM_NODE_DISCONNECTED),this.rejoinRoom()})}handleCallstatsEvents(){B.onSafeInitialization(()=>{B.onConsumerScore(t=>{t.forEach((e,r)=>{const n=this.sfuHandler.consumers.get(r);n&&b.emit(w.CONSUMER_SCORE_UPDATE,{id:r,kind:n.kind,peerId:n.peerId,score:+(e*10).toFixed()})})}),B.onProducerScore(t=>{t.forEach((e,r)=>{const n=Array.from(this.sfuHandler.producers.values()).find(i=>i.id===r);n&&b.emit(w.PRODUCER_SCORE_UPDATE,{id:r,kind:n.kind,appData:n.appData,score:+(e*10).toFixed()})})})})}},Re=new WeakMap,pe=new WeakMap,Nr=new WeakMap,rs=new WeakMap,Zn=new WeakMap,ei=new WeakMap,mc=new WeakMap,fc=new WeakMap,gc=new WeakMap,an=new WeakMap,so=new WeakMap,ti=new WeakMap,Lr=new WeakSet,cn=function(t,e){let r;const{reconnected:n}=c(this,Re).connectionState;switch(t){case"connected":r={state:"connected",reconnected:n,reconnectionAttempt:void 0};break;case"disconnected":r={state:"disconnected",reconnected:!1,reconnectionAttempt:0};break;case"reconnected":r={state:"connected",reconnected:!0,reconnectionAttempt:void 0};break;case"reconnecting":r={state:"reconnecting",reconnected:n,reconnectionAttempt:0};break;case"reconnectAttempt":r={state:"reconnecting",reconnected:n,reconnectionAttempt:e};break;case"failed":r={state:"failed",reconnected:n,reconnectionAttempt:void 0};break}r&&(c(this,Re).connectionState=r,b.emit(w.SOCKET_STATE_UPDATE,r))},Ag);let ae=Mg;le([y.trace("CFNodeClient.reset")],ae.prototype,"reset",1),le([y.trace("CFNodeClient.reconnect")],ae.prototype,"reconnectTransport",1),le([y.trace("CFNodeClient.setupTransport")],ae.prototype,"setupTransports",1),le([y.trace("CFNodeClient.stopAllProducers")],ae.prototype,"stopAllProducers",1),le([y.trace("CFNodeClient.joinRoom")],ae.prototype,"joinRoom",1),le([y.trace("CFNodeClient.completeJoinRoom")],ae.prototype,"completeJoinRoom",1),le([y.trace("CFNodeClient.leaveRoom")],ae.prototype,"leaveRoom",1),le([y.trace("CFNodeClient.activatePeers")],ae.prototype,"activatePeers",1),le([y.trace("CFNodeClient.deactivatePeers")],ae.prototype,"deactivatePeers",1),le([y.trace("CFNodeClient.createConsumer")],ae.prototype,"createConsumer",1),le([y.trace("CFNodeClient.pauseConsumers")],ae.prototype,"pauseConsumers",1),le([y.trace("CFNodeClient.resumeConsumers")],ae.prototype,"resumeConsumers",1),le([y.trace("CFNodeClient.closeConsumers")],ae.prototype,"closeConsumers",1),le([y.trace("CFNodeClient.consumePeer")],ae.prototype,"consumePeer",1),le([y.trace("CFNodeClient.shareWebcam")],ae.prototype,"shareWebcam",1),le([y.trace("CFNodeClient.shareScreen")],ae.prototype,"shareScreen",1),le([y.trace("CFNodeClient.shareMic")],ae.prototype,"shareMic",1),le([y.trace("CFNodeClient.pauseMic")],ae.prototype,"pauseMic",1),le([y.trace("CFNodeClient.pauseWebcam")],ae.prototype,"pauseWebcam",1),le([y.trace("CFNodeClient.resumeMic")],ae.prototype,"resumeMic",1),le([y.trace("CFNodeClient.resumeWebcam")],ae.prototype,"resumeWebcam",1),le([y.trace("CFNodeClient.disableWebcam")],ae.prototype,"disableWebcam",1),le([y.trace("CFClient.disableMic")],ae.prototype,"disableMic",1),le([y.trace("CFClient.disableScreenShare")],ae.prototype,"disableScreenShare",1),le([y.trace("CFNodeClient.muteSelf")],ae.prototype,"muteSelf",1),le([y.trace("CFNodeClient.resetVideoProducers")],ae.prototype,"resetVideoProducers",1),le([y.trace("CFNodeClient.changeDisplayName")],ae.prototype,"changeDisplayName",1),le([y.trace("CFNodeClient.kickPeer")],ae.prototype,"kick",1),le([y.trace("CFNodeClient.kickAllPeers")],ae.prototype,"kickAll",1),le([y.trace("CFNodeClient.muteAll")],ae.prototype,"muteAll",1),le([y.trace("CFNodeClient.muteAllVideo")],ae.prototype,"muteAllVideo",1),le([y.trace("CFNodeClient.disableAudio")],ae.prototype,"disableAudio",1),le([y.trace("CFNodeClient.disableVideo")],ae.prototype,"disableVideo",1),le([y.trace("CFNodeClient.pinPeer")],ae.prototype,"pinPeer",1),le([y.trace("CFNodeClient.validateScreenShare")],ae.prototype,"validateScreenShare",1),le([y.trace("CFNodeClient.init")],ae,"init",1);function hD(t,e){return u(this,null,function*(){const r=t.getValue("roomNodeClient");if(r){if(r instanceof oe)return r;throw new Error("Room Node Client already setup")}const n=yield oe.init(t,e);return t.setValue("roomNodeClient",n),n})}function pD(t,e){return u(this,null,function*(){const r=t.getValue("roomNodeClient");if(r){if(r instanceof ae)return r;throw new Error("Room Node Client already setup")}const n=yield ae.init(t,e);return t.setValue("roomNodeClient",n),n})}function Dg(t,e){return u(this,arguments,function*(r,n,i=Qi.HIVE){return i===Qi.CF?pD(r,n):hD(r,n)})}function Og(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch(r){l.error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var mD=Object.defineProperty,fD=Object.getOwnPropertyDescriptor,gD=(t,e,r,n)=>{for(var i=n>1?void 0:n?fD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&mD(e,r,i),i};let ns;const Ng=class{constructor(t){m(this,"socket"),this.socket=t,this.handleSocketEvents()}static create(t){return ns||(ns=new Ng(t)),ns}static cleanup(){var t;try{(t=ns==null?void 0:ns.socket)==null||t.disconnect()}catch(e){l.error("roomSocketHandler::cleanup")}ns=void 0}joinRoom(t,e,r,n){return u(this,null,function*(){const i={capabilities:[],peer:{displayName:t!=null?t:"Participant",peerId:e,userId:r,waitlisted:!1},roomUuid:""},s=this.socket.sendMessagePromise(j.joinRoom,$0.toBinary(i));try{const{peer:o}=wi.fromBinary((yield s).payload);b.emit(w.SOCKET_SERVICE_ROOM_JOINED,{peer:o});const a=this.getRoomState();let d=()=>new Promise(f=>{f({peers:[]})});n!==We.Livestream&&(d=this.getRoomPeersNonPaginated()),n===We.Livestream&&o.stageType===1&&(d=this.getStagePeers());const[{room:h},{peers:p}]=yield Promise.all([a,d]);return b.emit(w.ROOM_STATE,h),b.emit(w.SOCKET_PEERS,p),{peer:o}}catch(o){throw l.error("RoomSocketHandler.joinRoom.failed",{error:o}),new C("Error: RoomSocketHandler.joinRoom failed.","0002",o)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return RC.fromBinary((yield this.socket.sendMessagePromise(j.getAllAddedParticipants)).payload).participants.map(t=>{var e=t,{id:r}=e,n=Ro(e,["id"]);return ne(V({},n),{userId:r})})}catch(t){return[]}})}getRoomPeers(t,e,r){return u(this,null,function*(){let n;try{const i={seachQuery:t,limit:e,offset:r},s=yield this.socket.sendMessagePromise(j.getRoomPeersInfo,N0.toBinary(i));n=Jd.fromBinary(s.payload)}catch(i){l.error("getRoomPeers::binary_decode_error",{error:i})}return n})}getRoomPeersNonPaginated(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(j.getRoomPeersInfo);t=Jd.fromBinary(e.payload)}catch(e){l.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getStagePeers(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(j.getRoomPeersInfo);t=Jd.fromBinary(e.payload)}catch(e){l.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getPeerInfo(t){return u(this,null,function*(){let e;try{const r=yield this.socket.sendMessagePromise(j.getPeerInfo,Zm.toBinary({peerId:t}));e=wi.fromBinary(r.payload)}catch(r){l.error("getPeerInfo::binary_decode_error",{error:r})}return e})}getRoomState(){return u(this,null,function*(){let t=Xm.create();try{const e=yield this.socket.sendMessagePromise(j.getRoomInfo);t=Xm.fromBinary(e.payload)}catch(e){l.error("getRoomState::binary_decode_error",{error:e})}return t})}getRoomStageState(){return u(this,null,function*(){let t=sf.create();try{const e=yield this.socket.sendMessagePromise(j.getRoomStageState);t=sf.fromBinary(e.payload)}catch(e){l.error("getRoomStageState::binary_decode_error",{error:e})}return t})}broadcastMessage(t,e){return u(this,null,function*(){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),peerIds:[]};return this.socket.sendMessagePromise(j.broadcastMessage,ha.toBinary(r))})}broadcastToPeers(t,e,r){return u(this,null,function*(){const n={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),peerIds:e};return this.socket.sendMessage(j.broadcastToPeers,ha.toBinary(n))})}leaveRoom(){return u(this,null,function*(){this.socket.sendMessagePromise(j.leaveRoom,J0.toBinary({}))})}kick(t){return u(this,null,function*(){const e={peerIds:[t]};this.socket.sendMessage(j.kick,DC.toBinary(e))})}kickAll(){return u(this,null,function*(){this.socket.sendMessage(j.kickAll)})}getWaitingRoomRequests(){this.socket.sendMessage(j.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(j.acceptWaitingRoomRequests,LC.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(j.denyWaitingRoomRequests,FC.toBinary(e))}updatePermissions(t,e){return u(this,null,function*(){const r={updatePeersPresets:[]};return t.forEach(n=>{r.updatePeersPresets.push({userIds:n,patch:e})}),this.socket.sendMessagePromise(va.updateUserPreset,hI.toBinary(r))})}handleSocketEvents(){this.socket.on(j.broadcastMessage,({payload:t})=>{try{const e=ha.fromBinary(t);b.emit(w.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){l.error("failed to decode broadcast message:",e)}}),this.socket.on(j.broadcastToPeers,({payload:t})=>{try{const e=ha.fromBinary(t);b.emit(w.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){l.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,n;switch(t){case j.joinRoom:case j.leaveRoom:case j.kick:case j.kickAll:{r=wi.fromBinary.bind(wi),n=wi.create();break}case j.getWaitingRoomRequests:{r=(i,s)=>i?nf.fromBinary(i,s):{requests:[]},n=nf.create();break}case j.recordingPaused:case j.recordingStarted:case j.recordingStopped:{r=vf.fromBinary.bind(vf);break}case va.updateUserPreset:{r=af.fromBinary.bind(af);break}case se.peerJoinedBroadcast:case ie.peerJoinedBroadcast:{r=$m.fromBinary.bind($m);break}case se.selfJoinComplete:case ie.selfJoinComplete:{r=aa.fromBinary.bind(aa);break}case se.globalPeerPinBroadcast:case ie.globalPeerPinBroadcast:{r=Km.fromBinary.bind(Km);break}case se.selectedPeer:case ie.selectedPeer:{r=Wd.fromBinary.bind(Wd);break}case se.selectedPeerDiff:case ie.selectedPeerDiff:{r=Nm.fromBinary.bind(Nm);break}case se.leaveRoom:case ie.leaveRoom:{r=ca.fromBinary.bind(ca);break}}this.socket.on(t,({payload:i})=>{let s=n;if(!r)return e(void 0);try{s=r(i)}catch(o){l.error("roomSocketHandler::on::binary_decode_error",{error:o})}return e(s)})}getUserPermissions(t){return u(this,null,function*(){const e={userIds:[t]};try{const r=yield this.socket.sendMessagePromise(va.getUserPresets,sI.toBinary(e)),n=dI.fromBinary(r.payload).peerPresets[0],i=new TextDecoder().decode(n.preset),s=JSON.parse(i).permissions;return{chat:s.chat,polls:s.polls,plugins:s.plugins}}catch(r){throw l.error("Error in getting user preset",{error:r}),r}})}};let vc=Ng;gD([y.trace("RoomSocketHandler.joinRoom")],vc.prototype,"joinRoom",1);var vD=Object.defineProperty,yD=Object.getOwnPropertyDescriptor,is=(t,e,r,n)=>{for(var i=n>1?void 0:n?yD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&vD(e,r,i),i},ri,nr,kt,Ft,$t,Lg;const xg=(Lg=class{constructor(t,e,r,n){_(this,Ft),m(this,"self"),m(this,"authToken"),_(this,ri,void 0),m(this,"viewType"),_(this,nr,void 0),_(this,kt,void 0);const{socket:i}=r,s=t.getValue("authToken");this.self=e,T(this,kt,t),this.viewType=n,this.authToken=s,T(this,ri,i),T(this,nr,r),e.config.viewType!==We.Chat&&this.setupEvents()}get peerId(){return c(this,kt).getValue("peerId")}static init(t,e,r,n,i){return u(this,null,function*(){const s=je(),o=t.getValue("peerId"),a=!!t.getValue("cachedUserDetails"),d=yield ot.__init__(t,r,n,i,i.name,a);if(K.hasFeature(X.INTERNAL_CALL_STATS)&&navigator.product!=="ReactNative"){const h=!K.hasFeature(X.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const p=yield d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(p)}),B.onSafeInitialization(()=>u(this,null,function*(){B.devices("AUDIO",p==null?void 0:p.filter(f=>f.kind==="audioinput")),B.devices("VIDEO",p==null?void 0:p.filter(f=>f.kind==="videoinput")),B.devices("SPEAKER",p==null?void 0:p.filter(f=>f.kind==="audiooutput"))})),B.initialize({peerId:o,engineName:ye.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield s.getICEServers(),apiBase:t.getValue("apiBase"),flags:K.getAllFlags(),logger:l,apiHostnames:mm(t),skipConnectivityChecks:h})}))}return new xg(t,d,e,i.viewType)})}shareMediaTracks(){return u(this,null,function*(){var t;const{audioTrack:e,videoTrack:r,permissions:n,audioEnabled:i,videoEnabled:s,screenShareEnabled:o,screenShareTracks:a}=this.self;if(n.canProduceAudio&&i)try{yield c(this,Ft,$t).shareMic(e)}catch(d){this.self.disableAudio()}if(n.canProduceVideo&&s)try{const d=yield c(this,Ft,$t).shareWebcam(r);d&&d.id!==r.id&&K.hasFeature(X.EXP_RESHARE)&&(yield c(this,Ft,$t).shareWebcam(d))}catch(d){this.self.disableVideo()}if(n.canProduceScreenshare&&o)try{yield(t=c(this,Ft,$t))==null?void 0:t.shareScreen({video:a.video,audio:a.audio})}catch(d){this.self.disableScreenShare()}})}kickHandler(t){return u(this,null,function*(){let e="kicked";(t==null?void 0:t.kickType)==="kickAll"&&(e="ended"),this.leaveRoom(e)})}waitlistedHandler(){l.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(l.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){l.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(l.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){l.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}resetSelf(t){return u(this,null,function*(){if(B.callEnded(),!t){c(this,Ft,$t).reset();return}yield this.joinRoom(t)})}setupEvents(){b.on(w.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.self.roomJoined&&this.shareMediaTracks()})),b.on(w.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),b.on(w.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),b.on(w.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),b.on(w.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{this.self.roomState="init",this.resetSelf(t)}),b.on(w.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;(t||this.self.waitlistStatus==="waiting")&&K.hasFeature(X.REFRESH_ID_ON_DISCONNECTION)&&(e=gn()),c(this,ri).updateURL(e),y.resetPeerId(e),je().setHeader("dyte-tracing-id",e),Ts.remapContext(e,c(this,kt)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),b.on(w.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),c(this,nr).on(j.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),c(this,nr).on(va.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&b.emit(w.UPDATE_PERMISSIONS,e.patch)})}),c(this,nr).on(j.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),c(this,nr).on(j.kick,()=>{this.kickHandler({kickType:"kick"})}),c(this,nr).on(j.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),b.onAsync(w.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),b.on(w.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:r})=>{var n;const i=e==="video"&&((n=r==null?void 0:r.screenShare)!=null?n:!1);this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:i,score:t,participantId:this.self.id})}),b.on(w.MUTE_ALL,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),B.audioOff())})),b.on(w.MUTE_ALL_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),B.videoOff())})),b.onAsync(w.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),b.on(w.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return u(this,null,function*(){try{const{peer:e}=yield c(this,nr).joinRoom(this.self.name,this.self.id,this.self.userId,this.self.config.viewType);c(this,nr).socket.flush();const r=Pa(e.stageType);if(c(this,kt).setValue("stageStatus",r,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),c(this,kt).notify("stageStatus")}catch(e){throw l.error("Error in joinRoom",{error:e}),e}})}leaveRoom(t="left"){return u(this,null,function*(){var e,r;if(t==="rejected"){try{(e=c(this,ri))==null||e.disconnect()}catch(n){l.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),yield c(this,nr).leaveRoom(),c(this,kt).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),c(this,kt).notify("stageStatus");try{(r=c(this,ri))==null||r.disconnect()}catch(n){l.error("SelfController::leaveRoom::socketDisconnect")}Og(c(this,kt)),vc.cleanup(),this.self.roomState=t,this.self.emit("roomLeft",{state:t})})}partialMediaRoom(){var t;(t=c(this,Ft,$t))==null||t.partialJoinRoom(this.self.name,c(this,kt).getValue("meetingId"),void 0)}joinMediaRoom(t=!1){return u(this,null,function*(){var e,r;const{peerId:n,viewType:i,meetingId:s,authToken:o,stageStatus:a,roomNodeOptions:d}=c(this,kt).getAllValues(),{sfu:h,roomNodeUrl:p,meetingTitle:f}=d;try{if(i===We.Livestream){if(a!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}yield Dg(c(this,kt),{socket:c(this,ri),peerId:n,meetingId:s,authToken:o,roomNodeUrl:p,meetingTitle:f},h)}const{roomJoined:g}=(r=yield(e=c(this,Ft,$t))==null?void 0:e.joinRoom(this.self.name,s,{audio:this.self.audioEnabled,video:this.self.videoEnabled,screen:this.self.screenShareEnabled},t,t))!=null?r:{};if(!g)return;a==="ON_STAGE"&&this.shareMediaTracks(),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(g){throw l.error("Error:SelfController.mediaRoomJoin",g),new C("Error: could not join media room",g)}})}leaveMediaRoom(t){return u(this,null,function*(){const e=c(this,kt).getValue("viewType");yield this.cleanupSelf(),!(t==="stageLeft"&&e===We.Webinar)&&c(this,Ft,$t)&&(c(this,Ft,$t).roomJoined&&t!=="disconnected"&&(yield c(this,Ft,$t).leaveRoom()),!(t==="stageLeft"&&e===We.Livestream)&&(this.self.roomState="init",c(this,Ft,$t).roomJoined=!1))})}cleanupSelf(){return u(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()})}},ri=new WeakMap,nr=new WeakMap,kt=new WeakMap,Ft=new WeakSet,$t=function(){return c(this,kt).getValue("roomNodeClient")},Lg);let ni=xg;is([y.trace("SelfController.resetSelf")],ni.prototype,"resetSelf",1),is([y.trace("SelfController.setupEvents")],ni.prototype,"setupEvents",1),is([y.trace("SelfController.joinRoom")],ni.prototype,"joinRoom",1),is([y.trace("SelfController.leaveRoom")],ni.prototype,"leaveRoom",1),is([y.trace("SelfController.joinMediaRoom")],ni.prototype,"joinMediaRoom",1),is([y.trace("SelfController.leaveMediaRoom")],ni.prototype,"leaveMediaRoom",1);var yc;class ED{constructor(e){_(this,yc,void 0),T(this,yc,e)}on(e,r){let n;e===j.roomPeerCount?n=Ym.fromBinary.bind(Ym):n=pf.fromBinary.bind(pf),c(this,yc).on(e,({payload:i})=>{const s=n(i);return r(s)})}}yc=new WeakMap;var Ec;class SD{constructor(e){_(this,Ec,void 0),T(this,Ec,e)}on(e,r){let n,i;switch(e){case j.transcript:{n=$d.fromBinary.bind($d),i=$d.create();break}default:{l.debug("AISocketHandler switch case hit default, event not accounted for.");break}}c(this,Ec).on(e,({payload:s})=>{let o=i;try{o=n(s)}catch(a){l.error("chatSocketHandler::on::binary_decode_error",{error:a})}return r(o)})}}Ec=new WeakMap;var TD=Object.defineProperty,kD=Object.getOwnPropertyDescriptor,Jl=(t,e,r,n)=>{for(var i=n>1?void 0:n?kD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&TD(e,r,i),i},ii;class Sc{constructor(e){_(this,ii,void 0),T(this,ii,e)}getPolls(){return c(this,ii).sendMessagePromise(_r.getPolls)}createPoll(e,r,n=!1,i=!1){const s={anonymous:n,hideVotes:i,question:e,options:r};return c(this,ii).sendMessage(_r.createPoll,iP.toBinary(s))}votePoll(e,r){const n={index:r,pollId:e};return c(this,ii).sendMessage(_r.votePoll,oP.toBinary(n))}on(e,r){let n,i;switch(e){case _r.updatePoll:case _r.createPoll:case _r.votePoll:{n=rl.fromBinary.bind(rl),i=rl.create();break}}c(this,ii).on(e,({payload:s})=>{let o=i;try{o=n(s)}catch(a){l.error("pollSocketHandler::on::binary_decode_error",{error:a})}return r(o)})}}ii=new WeakMap,Jl([y.trace("PollSocketHandler.getPolls")],Sc.prototype,"getPolls",1),Jl([y.trace("PollSocketHandler.createPoll")],Sc.prototype,"createPoll",1),Jl([y.trace("PollSocketHandler.votePoll")],Sc.prototype,"votePoll",1);var Ut;class _D{constructor(e){_(this,Ut,void 0),T(this,Ut,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield c(this,Ut).sendMessagePromise(j.getStageRequests);return e?tl.fromBinary(e):{stageRequests:[]}})}requestAccess(){c(this,Ut).sendMessage(j.requestStageAccess)}cancelRequestAccess(){c(this,Ut).sendMessage(j.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const r={userIds:e};c(this,Ut).sendMessage(j.grantStageAccess,KR.toBinary(r))})}denyAccess(e){return u(this,null,function*(){const r={userIds:e};c(this,Ut).sendMessage(j.denyStageAccess,YR.toBinary(r))})}joinStage(){return c(this,Ut).sendMessagePromise(j.joinStage,void 0,void 0,j.peerStageStatusUpdate)}leaveStage(e){const r={userIds:[e]};return c(this,Ut).sendMessagePromise(j.leaveStage,ff.toBinary(r),void 0,j.peerStageStatusUpdate)}kick(e){const r={userIds:e};return c(this,Ut).sendMessagePromise(j.leaveStage,ff.toBinary(r))}on(e,r){let n;switch(e){case j.grantStageAccess:case j.denyStageAccess:{n=void 0;break}case j.getStagePeers:{n=mf.fromBinary.bind(mf);break}case j.getStageRequests:case j.requestStageAccess:case j.cancelStageRequest:{n=tl.fromBinary.bind(tl);break}case j.peerStageStatusUpdate:{n=zm.fromBinary.bind(zm);break}}c(this,Ut).on(e,({payload:i,id:s})=>{if(!i||!n)return r(void 0,s);const o=n(i);return r(o,s)})}getPeerInfo(e){return u(this,null,function*(){const r=yield c(this,Ut).sendMessagePromise(j.getPeerInfo,Zm.toBinary({peerId:e}));return wi.fromBinary(r.payload)})}}Ut=new WeakMap;var tt;class bD{constructor(e){_(this,tt,void 0),T(this,tt,e)}addPlugin(e,r){c(this,tt).sendMessage(J.addPlugin,uR.toBinary({pluginId:e,staggered:r}))}removePlugin(e){c(this,tt).sendMessage(J.removePlugin,pR.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield c(this,tt).sendMessagePromise(J.getPlugins);return e?xR.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,r,n){const i={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};c(this,tt).sendMessage(J.customPluginEventToRoom,_R.toBinary(i),n)}customPluginEventToPeers(e,r,n,i){const s={pluginId:e,peerIds:r,pluginData:new TextEncoder().encode(JSON.stringify(n))};c(this,tt).sendMessage(J.customPluginEventToPeers,wR.toBinary(s),i)}enablePluginForRoom(e,r){c(this,tt).sendMessage(J.enablePluginForRoom,fR.toBinary({pluginId:e}),r)}enablePluginForPeers(e,r,n){c(this,tt).sendMessage(J.enablePluginForPeers,ER.toBinary({pluginId:e,peerIds:r}),n)}disablePluginForRoom(e,r){c(this,tt).sendMessage(J.disablePluginForRoom,vR.toBinary({pluginId:e}),r)}disablePluginForPeers(e,r,n){c(this,tt).sendMessage(J.disablePluginForPeers,TR.toBinary({pluginId:e,peerIds:r}),n)}storeInsertKeys(e,r,n,i){const s={pluginId:e,storeName:r,insertKeys:n.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};c(this,tt).sendMessage(J.storeInsertKeys,df.toBinary(s),i)}storeGetKeys(e,r,n,i){const s={pluginId:e,storeName:r,getKeys:n.map(o=>({storeKey:o.key}))};c(this,tt).sendMessage(J.storeGetKeys,PR.toBinary(s),i)}storeDeleteKeys(e,r,n,i){const s={pluginId:e,storeName:r,deleteKeys:n.map(o=>({storeKey:o.key}))};c(this,tt).sendMessage(J.storeDeleteKeys,MR.toBinary(s),i)}storeDelete(e,r,n){c(this,tt).sendMessage(J.storeDelete,OR.toBinary({pluginId:e,storeName:r}),n)}getPluginDataOld(e,r){l.info("getPluginDataOld",{plugin:{id:e,storeName:r}})}storePluginDataOld(e,r,n){const i={pluginId:e,storeName:r,insertKeys:[{storeKey:n.key,payload:new TextEncoder().encode(JSON.stringify(n))}]};c(this,tt).sendMessage(J.storeInsertKeys,df.toBinary(i))}on(e,r){let n;switch(e){case J.addPlugin:case J.enablePluginForPeers:case J.enablePluginForRoom:{n=el.fromBinary.bind(el);break}case J.removePlugin:case J.disablePluginForPeers:case J.disablePluginForRoom:{n=lf.fromBinary.bind(lf);break}case J.customPluginEventToPeers:case J.customPluginEventToRoom:{n=hf.fromBinary.bind(hf);break}case J.storeInsertKeys:case J.storeGetKeys:case J.storeDeleteKeys:case J.storeDelete:{n=uf.fromBinary.bind(uf);break}}c(this,tt).on(e,({payload:i,id:s})=>{const o=n(i);return r(o,s)})}}tt=new WeakMap;var wD=Object.defineProperty,CD=(t,e,r)=>e in t?wD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ID=(t,e,r)=>(CD(t,typeof e!="symbol"?e+"":e,r),r),ql=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},O=(t,e,r)=>(ql(t,e,"read from private field"),r?r.call(t):e.get(t)),Pe=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},ge=(t,e,r,n)=>(ql(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),Ae=(t,e,r)=>(ql(t,e,"access private method"),r),dn,si,oi,Ue,ai,Me,He,ln,rt,xr,un,ir,ss,Fr,Kl,Fg,oo,Tc,zl,Ug,Yl,Vg,kc,Ql,Xl,Bg,ao,_c,co,bc,wc,Zl,os,lo,uo,Cc,eu={exports:{}},as=typeof Reflect=="object"?Reflect:null,jg=as&&typeof as.apply=="function"?as.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},Ic;as&&typeof as.ownKeys=="function"?Ic=as.ownKeys:Object.getOwnPropertySymbols?Ic=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Ic=function(t){return Object.getOwnPropertyNames(t)};function RD(t){console&&console.warn&&console.warn(t)}var Hg=Number.isNaN||function(t){return t!==t};function Ee(){Ee.init.call(this)}eu.exports=Ee,eu.exports.once=DD,Ee.EventEmitter=Ee,Ee.prototype._events=void 0,Ee.prototype._eventsCount=0,Ee.prototype._maxListeners=void 0;var Wg=10;function Rc(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(Ee,"defaultMaxListeners",{enumerable:!0,get:function(){return Wg},set:function(t){if(typeof t!="number"||t<0||Hg(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Wg=t}}),Ee.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},Ee.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Hg(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 $g(t){return t._maxListeners===void 0?Ee.defaultMaxListeners:t._maxListeners}Ee.prototype.getMaxListeners=function(){return $g(this)},Ee.prototype.emit=function(t){for(var e=[],r=1;r<arguments.length;r++)e.push(arguments[r]);var n=t==="error",i=this._events;if(i!==void 0)n=n&&i.error===void 0;else if(!n)return!1;if(n){var s;if(e.length>0&&(s=e[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=i[t];if(a===void 0)return!1;if(typeof a=="function")jg(a,this,e);else for(var d=a.length,h=zg(a,d),r=0;r<d;++r)jg(h[r],this,e);return!0};function Gg(t,e,r,n){var i,s,o;if(Rc(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=$g(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,RD(a)}return t}Ee.prototype.addListener=function(t,e){return Gg(this,t,e,!1)},Ee.prototype.on=Ee.prototype.addListener,Ee.prototype.prependListener=function(t,e){return Gg(this,t,e,!0)};function PD(){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 Jg(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=PD.bind(n);return i.listener=r,n.wrapFn=i,i}Ee.prototype.once=function(t,e){return Rc(e),this.on(t,Jg(this,t,e)),this},Ee.prototype.prependOnceListener=function(t,e){return Rc(e),this.prependListener(t,Jg(this,t,e)),this},Ee.prototype.removeListener=function(t,e){var r,n,i,s,o;if(Rc(e),n=this._events,n===void 0)return this;if(r=n[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete n[t],n.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(i=-1,s=r.length-1;s>=0;s--)if(r[s]===e||r[s].listener===e){o=r[s].listener,i=s;break}if(i<0)return this;i===0?r.shift():AD(r,i),r.length===1&&(n[t]=r[0]),n.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this},Ee.prototype.off=Ee.prototype.removeListener,Ee.prototype.removeAllListeners=function(t){var e,r,n;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[t]),this;if(arguments.length===0){var i=Object.keys(r),s;for(n=0;n<i.length;++n)s=i[n],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=r[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(n=e.length-1;n>=0;n--)this.removeListener(t,e[n]);return this};function qg(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?MD(i):zg(i,i.length)}Ee.prototype.listeners=function(t){return qg(this,t,!0)},Ee.prototype.rawListeners=function(t){return qg(this,t,!1)},Ee.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Kg.call(t,e)},Ee.prototype.listenerCount=Kg;function Kg(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}Ee.prototype.eventNames=function(){return this._eventsCount>0?Ic(this._events):[]};function zg(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function AD(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function MD(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function DD(t,e){return new Promise(function(r,n){function i(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}Yg(t,e,s,{once:!0}),e!=="error"&&OD(t,i,{once:!0})})}function OD(t,e,r){typeof t.on=="function"&&Yg(t,"error",e,r)}function Yg(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var ND=eu.exports;class LD extends k{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 Qg=new LD;class Xg{static encode(e){return Qg.toBinary(e)}static decode(e){return Qg.fromBinary(new Uint8Array(e))}}function xD(t,e){return Math.floor(Math.random()*(e-t+1)+t)}class FD{constructor(e={}){ID(this,"opts"),Pe(this,dn,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},ge(this,dn,0)}wait(){return u(this,null,function*(){ge(this,dn,O(this,dn)+1);const e=xD(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*dy(2,O(this,dn))));yield new Promise(r=>{setTimeout(r,e)})})}getAttempts(){return O(this,dn)}reset(){ge(this,dn,0)}}dn=new WeakMap;const hn={debug:0,info:1,warn:2,error:3};class UD{constructor(e){Pe(this,si,void 0),Pe(this,oi,void 0),ge(this,si,console),ge(this,oi,e)}debug(...e){hn[O(this,oi)]>hn.debug||O(this,si).debug("[Sockrates]:",...e)}info(...e){hn[O(this,oi)]>hn.info||O(this,si).info("[Sockrates]:",...e)}warn(...e){hn[O(this,oi)]>hn.warn||O(this,si).warn("[Sockrates]:",...e)}error(...e){hn[O(this,oi)]>hn.error||O(this,si).error("[Sockrates]:",...e)}}si=new WeakMap,oi=new WeakMap;var Zg=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(Zg||{});const VD="2",BD="3";class jD{constructor(e,r){Pe(this,Kl),Pe(this,oo),Pe(this,zl),Pe(this,Yl),Pe(this,kc),Pe(this,Xl),Pe(this,ao),Pe(this,co),Pe(this,wc),Pe(this,os),Pe(this,uo),Pe(this,Ue,void 0),Pe(this,ai,void 0),Pe(this,Me,void 0),Pe(this,He,void 0),Pe(this,ln,void 0),Pe(this,rt,void 0),Pe(this,xr,void 0),Pe(this,un,void 0),Pe(this,ir,void 0),Pe(this,ss,void 0),Pe(this,Fr,void 0);var n,i,s,o,a,d,h,p,f,g;ge(this,ai,e),ge(this,ln,[]),ge(this,rt,new ND),ge(this,xr,!0),ge(this,ir,!1),ge(this,Me,r!=null?r:{}),(n=O(this,Me)).autoReconnect!=null||(n.autoReconnect=!0),(i=O(this,Me)).retryConnectionInterval!=null||(i.retryConnectionInterval=1e3),(s=O(this,Me)).pingTimeout!=null||(s.pingTimeout=3e4),(o=O(this,Me)).connectionTimeout!=null||(o.connectionTimeout=5e3),(a=O(this,Me)).debug!=null||(a.debug=!0),(d=O(this,Me)).maxReconnectionAttempts!=null||(d.maxReconnectionAttempts=10),(h=O(this,Me)).disconnectOnPingTimeout!=null||(h.disconnectOnPingTimeout=!0),(p=O(this,Me)).queueOnDisconnect!=null||(p.queueOnDisconnect=!1),(f=O(this,Me)).flushOnReconnect!=null||(f.flushOnReconnect=!1),ge(this,un,{code:void 0,reason:void 0}),ge(this,He,(g=O(this,Me).logger)!=null?g:new UD(O(this,Me).debug?"debug":"info")),ge(this,Fr,new FD)}get readyState(){var e;return(e=O(this,Ue))==null?void 0:e.readyState}get url(){return O(this,ai)}updateURL(e){ge(this,ai,e),Ae(this,Xl,Bg).call(this)}get config(){return O(this,Me)}get sendQueue(){return O(this,ln)}flush(){if(!O(this,Me).queueOnDisconnect)return!1;const e=[];return O(this,ln).forEach(r=>{this.send(r.event,r.id,r.payload,r.metadata)||e.push(r)}),ge(this,ln,e),O(this,ln)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){O(this,He).debug("Websocket was already connecting or connected.");return}if(O(this,xr)!==!1)return new Promise((r,n)=>{Ae(this,os,lo).call(this),Ae(this,uo,Cc).call(this);try{ge(this,Ue,new WebSocket(Ae(this,Kl,Fg).call(this,O(this,ai)))),O(this,Ue).binaryType="arraybuffer",O(this,He).debug("Connecting to",O(this,ai));const i=setTimeout(()=>{O(this,He).debug("Connection timeout. Closing socket"),ge(this,xr,!0),Ae(this,uo,Cc).call(this),O(this,Ue).close(3001,"Connection Timeout"),O(this,Me).autoReconnect&&!O(this,ir)&&(O(this,rt).emit("reconnecting"),Ae(this,ao,_c).call(this)),n(new Error("Connection timed out!"))},O(this,Me).connectionTimeout);O(this,Ue).onopen=()=>{O(this,He).debug(`Ready State: ${Zg[O(this,Ue).readyState]}`),i&&clearTimeout(i),Ae(this,wc,Zl).call(this),ge(this,un,{code:void 0,reason:void 0}),O(this,rt).emit("connected"),O(this,Me).flushOnReconnect&&this.flush(),r()},O(this,Ue).onclose=s=>{try{i&&clearTimeout(i);const{code:o,reason:a}=s;n(a),O(this,He).debug("Socket closed. Close event:",s),O(this,He).debug("Connection closed code:",o),O(this,He).debug("Connection closed reason:",a),O(this,ir)||Ae(this,kc,Ql).call(this,o,a)}catch(o){Ae(this,oo,Tc).call(this,o)}},O(this,Ue).onerror=s=>{Ae(this,oo,Tc).call(this,s)},O(this,Ue).onmessage=s=>Ae(this,zl,Ug).call(this,s)}catch(i){Ae(this,oo,Tc).call(this,i,n)}})})}send(e,r,n,i){const s={event:e,id:r,payload:n,metadata:i};if(O(this,Me).queueOnDisconnect&&(!O(this,Ue)||O(this,Ue).readyState!==1))return O(this,He).debug("Queuing message since socket is not connected!",s),O(this,ln).push(s),!1;const o=Xg.encode(s);return Ae(this,co,bc).call(this,o)}emit(e,r,n,i){return this.send(e,r,n,i)}sendRaw(e){return Ae(this,co,bc).call(this,e)}receive(e,r){return O(this,rt).on(e.toString(),r)}on(e,r){if(typeof e=="string"&&(e==="connected"||e==="disconnected"||e==="errored"||e==="reconnected"||e==="reconnecting"||e==="reconnectAttempt"||e==="reconnectFailure"||e==="failed")){O(this,rt).on(e,r);return}this.receive(e,r)}removeAllListeners(){O(this,rt).removeAllListeners()}removeReceiver(e,r){this.removeListener(e,r)}removeListener(e,r){O(this,rt).removeListener(e.toString(),r)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){O(this,rt).listeners(e.toString()).map(r=>this.removeListener(e,r))}disconnect(){ge(this,xr,!1),Ae(this,os,lo).call(this),this.removeAllListeners(),ge(this,un,{code:1e3,reason:"Sockrates disconnect method called"}),O(this,Ue).close(1e3,"Sockrates disconnect method called.")}}Ue=new WeakMap,ai=new WeakMap,Me=new WeakMap,He=new WeakMap,ln=new WeakMap,rt=new WeakMap,xr=new WeakMap,un=new WeakMap,ir=new WeakMap,ss=new WeakMap,Fr=new WeakMap,Kl=new WeakSet,Fg=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)://.")},oo=new WeakSet,Tc=function(t,e){O(this,He).error("Error:",{error:t}),O(this,rt).emit("errored",{error:t}),e==null||e(t)},zl=new WeakSet,Ug=function(t){if(Ae(this,wc,Zl).call(this),t.data===VD){O(this,He).debug("Received ping from server"),Ae(this,co,bc).call(this,BD);return}O(this,He).debug("Received data:",t.data);const e=Xg.decode(t.data),{id:r,payload:n}=e;O(this,rt).emit(e.event.toString(),{id:r,payload:n})},Yl=new WeakSet,Vg=function(){return O(this,Ue).readyState===1},kc=new WeakSet,Ql=function(t,e){ge(this,un,{reason:e,code:t}),O(this,rt).emit("disconnected",{code:t,reason:e})},Xl=new WeakSet,Bg=function(){const{reason:t,code:e}=O(this,un);e&&e!==1e3&&O(this,xr)&&O(this,Me).autoReconnect&&!O(this,ir)&&(O(this,He).debug(`Triggering reconnection due to ${t}.`),O(this,rt).emit("reconnecting"),Ae(this,ao,_c).call(this))},ao=new WeakSet,_c=function(t=!0){return u(this,null,function*(){if(t&&O(this,ir)){O(this,He).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(O(this,ir)||O(this,Fr).reset(),O(this,Me).maxReconnectionAttempts!==null&&O(this,Fr).getAttempts()>=O(this,Me).maxReconnectionAttempts){O(this,rt).emit("failed"),ge(this,ir,!1);return}ge(this,ir,!0),Ae(this,uo,Cc).call(this),Ae(this,os,lo).call(this);try{if(yield O(this,Fr).wait(),O(this,xr)===!1)return;if(O(this,He).debug(`Reconnection attempt ${O(this,Fr).getAttempts()}`),O(this,rt).emit("reconnectAttempt",{attempt:O(this,Fr).getAttempts()}),yield this.connect(),!Ae(this,Yl,Vg).call(this))throw Error("Reconnect Failed");ge(this,ir,!1),ge(this,un,{code:void 0,reason:void 0}),O(this,rt).emit("reconnected")}catch(e){O(this,He).debug("Failed to reconnect."),O(this,rt).emit("reconnectFailure",{attempt:O(this,Fr).getAttempts()}),Ae(this,ao,_c).call(this,!1)}})},co=new WeakSet,bc=function(t){try{return O(this,Ue).send(t),!0}catch(e){return O(this,He).error(e.message),!1}},wc=new WeakSet,Zl=function(){this.config.disconnectOnPingTimeout&&(O(this,He).debug("Resetting ping timeout"),Ae(this,os,lo).call(this),ge(this,ss,setTimeout(()=>{var t;O(this,He).debug("Disconnecting the socket due to ping timeout"),ge(this,xr,!0);const e=3002,r="Ping timeout";(t=O(this,Ue))==null||t.close(e,r),Ae(this,kc,Ql).call(this,e,r)},O(this,Me).pingTimeout)))},os=new WeakSet,lo=function(){O(this,ss)&&(clearTimeout(O(this,ss)),ge(this,ss,void 0))},uo=new WeakSet,Cc=function(){O(this,Ue)&&(O(this,Ue).onopen=void 0,O(this,Ue).onerror=void 0,O(this,Ue).onmessage=void 0,O(this,Ue).onclose=void 0)};var HD=Object.defineProperty,WD=Object.getOwnPropertyDescriptor,Pc=(t,e,r,n)=>{for(var i=n>1?void 0:n?WD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&HD(e,r,i),i};const ev=65535;var ci,Je,di,Ac,tu,Mc,ru,tv;const rv=(tv=class{constructor(t,{peerId:e,meetingId:r,authToken:n,capabilities:i}){_(this,Ac),_(this,Mc),_(this,ci,void 0),_(this,Je,void 0),m(this,"roomName"),m(this,"authToken"),m(this,"capabilities"),m(this,"connectionState"),_(this,di,void 0);var s;if(!e||!r||!n)throw new C("peerId, roomName, or authToken can not be empty");T(this,di,t),this.capabilities=i,this.roomName=r,this.authToken=n,this.connectionState={state:void 0,reconnected:!1,reconnectionAttempt:void 0},T(this,ci,ue(this,Ac,tu).call(this,e)),T(this,Je,new jD(c(this,ci),{autoReconnect:!0,disconnectOnPingTimeout:(s=i.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:l}))}get peerId(){return c(this,di).getValue("peerId")}updateURL(t){t!==this.peerId&&(T(this,ci,ue(this,Ac,tu).call(this,t)),l.debug("SocketService:: Connection URL updated.")),c(this,Je).updateURL(c(this,ci))}static getSocketEdgeDomain(t){return bi({servicePrefix:"socket-edge",baseURI:t})}get url(){return c(this,ci)}connect(){return u(this,null,function*(){yield c(this,Je).connect()})}disconnect(){return c(this,Je).disconnect()}get isConnected(){try{return c(this,Je).readyState===1}catch(t){return!1}}sendMessage(t,e,r){const n={};return y.injectContext(n),c(this,Je).send(t,r!=null?r:ue(this,Mc,ru).call(this),e,new TextEncoder().encode(JSON.stringify(n)))}sendMessagePromise(t,e,r,n){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:i,protobuf:e,messageId:r,resp:n})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:r,messageId:n,resp:i}){const s=i!=null?i:t;return new Promise((o,a)=>{const d=(E,v)=>{c(this,Je).removeListener(s,E),c(this,Je).removeListener(ev,v),c(this,Je).removeListener(ie.errorResponse,v),c(this,Je).removeListener(se.errorResponse,v)},h=n!=null?n:ue(this,Mc,ru).call(this),p={};y.injectContext(p);const f=({id:E,payload:v})=>{if(h===E){let R;try{const A=Vw.fromBinary(v);R=new Error(A.errorMessage)}catch(A){R=new Error("failed to parse error message",{cause:A});try{const L=I0.fromBinary(v);R=new Error(L.message)}catch(L){R=new Error("failed to parse error message",{cause:L})}}a(R),d(g,f)}},g=({id:E,payload:v})=>{h===E&&(o({id:E,payload:v}),d(g,f))};c(this,Je).on(s,g),c(this,Je).on(ev,f),c(this,Je).on(ie.errorResponse,f),c(this,Je).on(se.errorResponse,f),setTimeout(()=>{d(g,f),a(new Error(`request timeout for callback eventId:${t}`))},e),c(this,Je).send(t,h,r,new TextEncoder().encode(JSON.stringify(p)))})}on(t,e){c(this,Je).on(t,e)}onStateEvent(t,e){c(this,Je).on(t,e)}flush(){return c(this,Je).flush()}},ci=new WeakMap,Je=new WeakMap,di=new WeakMap,Ac=new WeakSet,tu=function(t){let e=rv.getSocketEdgeDomain(c(this,di).getValue("baseURI"));typeof pm(c(this,di),"socket_server_base")=="string"&&(e=pm(c(this,di),"socket_server_base"));const r=`wss://${e}`,n=new URL(`${r}/ws`),i=this.peerId,s=ne(V({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},i!==t&&{oldPeerID:i}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>la[o]).join(" ")});return Object.entries(s).forEach(([o,a])=>{n.searchParams.append(o,a.toString())}),n.href},Mc=new WeakSet,ru=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},tv);let ho=rv;Pc([y.trace("SocketService.connect")],ho.prototype,"connect",1),Pc([y.trace("SocketService.disconnect")],ho.prototype,"disconnect",1),Pc([y.trace("SocketService.sendMessagePromise")],ho.prototype,"sendMessagePromise",1),Pc([y.trace("SocketService.sendMessagePromiseWithTimeout")],ho.prototype,"sendMessagePromiseWithTimeout",1);const li=class{static handleConnectedRoomsDumpRaw({payload:t}){var e;const r=eC.fromBinary(t),n=r.meetings.map(i=>{var s;return{id:i.id,title:i.title,participants:(s=i.participants)!=null?s:[]}});return{parentMeeting:{id:r.parentMeeting.id,title:r.parentMeeting.title,participants:(e=r.parentMeeting.participants)!=null?e:[]},meetings:n}}static handleTransferPeerRaw({payload:t}){const e=CC.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}static handleMovedPeerRaw({payload:t}){const e=rf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}static handleConnectedRoomsUpdatedRaw({payload:t}){return tf.fromBinary(t).payloads.map(e=>({id:e.id,title:e.title}))}static handleConnectedRoomsDeletedRaw({payload:t}){return gC.fromBinary(t).payloads}static getConnectedRoomsDump(){return u(this,null,function*(){const t=yield li.socketService.sendMessagePromise(j.getConnectedRoomsDump);return li.handleConnectedRoomsDumpRaw(t)})}static createConnectedRooms(t){return u(this,null,function*(){const{payload:e}=yield li.socketService.sendMessagePromise(j.createConnectedRooms,iC.toBinary({payloads:t}));return tf.fromBinary(e).payloads.map(r=>({id:r.id,title:r.title}))})}static updateConnectedRooms(t){return u(this,null,function*(){})}static disableConnectedRooms(t){return u(this,null,function*(){const e=t.map(n=>({id:n})),r=yield li.socketService.sendMessagePromise(j.deleteConnectedRooms,mC.toBinary({payloads:e}));return li.handleConnectedRoomsDeletedRaw(r)})}static movePeersBetweenRooms(t){return u(this,null,function*(){try{const e=yield li.socketService.sendMessagePromise(j.movePeers,kC.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 Ne=li;m(Ne,"socketService"),m(Ne,"currentMeetingId");var $D=Object.defineProperty,GD=Object.getOwnPropertyDescriptor,Dc=(t,e,r,n)=>{for(var i=n>1?void 0:n?GD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&$D(e,r,i),i};const ui=class{constructor(t,e){m(this,"apiBase"),m(this,"selfController"),m(this,"pollController"),m(this,"chatController"),m(this,"metaController"),m(this,"storesManager"),m(this,"stageController"),m(this,"pluginController"),m(this,"internalsController"),m(this,"recordingController"),m(this,"livestreamController"),m(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 u(this,null,function*(){const{peerId:e,apiBase:r,authToken:n,meetingId:i,organizationId:s,cachedUserDetails:o}=t.getAllValues();if(b.reset(),vc.cleanup(),Og(t),ye.isSupported()===!1)throw new C("Browser not supported","0010",!0);const a=UP(t,{authToken:n,baseURL:r,cachedUserDetails:o});a.setRoomName(i),a.setRoomUUID(i),a.setOrganizationId(s),a.setHeader("dyte-tracing-id",e),t.setValue("apiClient",a);const d=ui.createSocketService(t),h=d.connect(),p=a.getPlugins(),[{sfu:f,userResponse:g,meetingTitle:E,roomNodeUrl:v}]=yield Promise.all([ui.getRoomMetadata(),ui.setupFlagsmith(t)]);t.setValue("roomNodeOptions",{sfu:f,meetingTitle:E,roomNodeUrl:v});const{theme:R,controllers:A}=yield ui.setupControllers(d,t,g,p);dA(R)&&ui.createRoomNodeClient(t,d),Zb();try{yield h,A.selfController.partialMediaRoom()}catch(L){throw l.error("[Socket Service] Failed to connect to socket server:",{error:L}),new C("Failed to connect to websocket","0012")}return new ui(r,A)})}static getRoomMetadata(){return u(this,null,function*(){const t=je(),[{roomNodeUrl:e,meetingTitle:r,sfu:n=Qi.HIVE},i]=yield Promise.all([t.getRoomNodeData(),t.getUserDetails()]);return{sfu:n,roomNodeUrl:e,meetingTitle:r,userResponse:i}})}static setupFlagsmith(t){return u(this,null,function*(){const{peerId:e,baseURI:r,overrides:n,meetingId:i,organizationId:s}=t.getAllValues(),o=Qb(i),a=ne(V({entity:Vd.PEER,clientId:s,isAnonUser:!s,sdkVersion:t.getValue("sdkVersion"),meetingHash:o,roomName:i},ye.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const d=n!=null&&n.whitelabelled_flags_endpoint?bi({servicePrefix:"flags",baseURI:r}):"edge.api.flagsmith.com";yield K.identify(`${Vd.PEER}_${e}`,JSON.parse(JSON.stringify(a)),!1,5e3,d),l.info("flagsmith::allFlags",{flags:JSON.stringify(K.getAllFlags())},!0)}catch(d){l.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,r,n){return u(this,null,function*(){var i,s,o;const a=e.getValue("modules"),{preset:d,participant:h}=r,p=e.getValue("defaults"),{sfu:f,meetingTitle:g}=e.getValue("roomNodeOptions"),E=nM.init(d,!a.theme),{viewType:v,mediaConstraints:{audio:R}}=E;e.setValue("viewType",v),e.setValue("defaults",V({mediaConfiguration:{audio:{enableHighBitrate:(i=R.enableHighBitrate)!=null?i:!1,enableStereo:(s=R.enableStereo)!=null?s:!1}}},p));const A=XM.init(e,v,d.permissions);let L,F,W,H,I,S,P,N;const ce=new SD(t);Ne.socketService=t;const Le=new Sc(t),$=new Bt(t),x=new _D(t),Se=vc.create(t),fn=new bD(t),pi=new ED(t),mi=new In(t),ht=yield ni.init(e,Se,h,A,E),Qe=yield Nf.init(e,ht.self,Se,ce,g);if(a.participant&&(f===Qi.CF&&(N=new wg(e,ht.self,Se,a)),N=new Cg(e,ht.self,Se,a)),(o=a.e2ee)!=null&&o.enabled&&a.e2ee.manager.init(l,b),a.chat&&(F=yield wr.init(e,$,mi,ht.self,N.participants)),a.internals&&(I=yield gl.init()),a.livestream&&E.viewType===We.Livestream&&K.hasFeature(X.LIVESTREAM)&&(P=new rg(ht.self,pi)),E.viewType!==We.Chat&&(a.poll&&(L=yield Rf.init(e,ht.self,Le)),a.recording&&(S=new Hf(e,ht.self,Se)),a.stage&&(W=new Lf(e,x,Se,ht.self,N.participants)),a.plugin)){if(!N)throw new C("The plugin module cannot be initialized without the `participant` module");const fo=yield n;H=yield Ns.init(e,fo,fn,$,F==null?void 0:F.chat,ht.self,N.participants)}const Xe={storesManager:new uM(e,fn),pollController:L,selfController:ht,metaController:Qe,chatController:F,stageController:W,pluginController:H,recordingController:S,internalsController:I,livestreamController:P,participantController:N};return{theme:E,permissions:A,controllers:Xe}})}static createRoomNodeClient(t,e){return u(this,null,function*(){const{peerId:r,meetingId:n,authToken:i,roomNodeOptions:s}=t.getAllValues(),{sfu:o,roomNodeUrl:a,meetingTitle:d}=s;return Dg(t,{socket:e,peerId:r,meetingId:n,authToken:i,roomNodeUrl:a,meetingTitle:d},o)})}static createSocketService(t){const{peerId:e,meetingId:r,authToken:n}=t.getAllValues(),i=["PING"];return new ho(t,{peerId:e,meetingId:r,authToken:n,capabilities:i})}};let po=ui;Dc([y.trace("Controller.init")],po,"init",1),Dc([y.trace("setupFlagsmith")],po,"setupFlagsmith",1),Dc([y.trace("Controller.createSocketServiceAndRoomNodeClient")],po,"createRoomNodeClient",1),Dc([y.trace("Controller.createSocketService")],po,"createSocketService",1);var JD=Object.defineProperty,qD=Object.getOwnPropertyDescriptor,KD=(t,e,r,n)=>{for(var i=n>1?void 0:n?qD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&JD(e,r,i),i},Oc,nu;class nv extends Dt{constructor(e,r){super(),_(this,Oc,void 0),m(this,"meetings",[]),m(this,"parentMeeting",null),_(this,nu,void 0),T(this,nu,e),T(this,Oc,r.self)}get supportsConnectedMeetings(){return c(this,Oc).id!==""&&K.hasFeature(X.CONNECTED_MEETINGS)}get isActive(){return this.meetings.length!==0}get currentMeetingId(){return Ne.currentMeetingId}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
21
- Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`)}getConnectedMeetings(){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),yield Ne.getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield Ne.createConnectedRooms(e)).map(r=>({id:r.id,title:r.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield Ne.updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title})))})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction();const r=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.participants.map(i=>i.id)):Promise.resolve());return yield Promise.all(r),yield Ne.disableConnectedRooms(e)})}moveParticipants(e,r,n){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=yield Ne.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:n.map(s=>({id:s}))});return i.success&&this.moveSuccessHandler(e,r,n),i})}moveParticipantsWithCustomPreset(e,r,n){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=yield Ne.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:n});return i.success&&this.moveSuccessHandler(e,r,n.map(s=>s.id)),i})}moveSuccessHandler(e,r,n){const i=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(s=>s.participants)].forEach(s=>i.set(s.id,s)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(n.map(s=>i.get(s)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(s=>!n.includes(s.id))),this.meetings=this.meetings.map(s=>{if(r===s.id){const o=s.participants.concat(n.map(a=>i.get(a)));return ne(V({},s),{participants:o})}if(e===s.id){const o=s.participants.filter(a=>!n.includes(a.id));return ne(V({},s),{participants:o})}return s})}}Oc=new WeakMap,nu=new WeakMap,KD([Ct({maxInvocations:60,period:60})],nv.prototype,"getConnectedMeetings",1);var zD=Object.defineProperty,YD=Object.getOwnPropertyDescriptor,iu=(t,e,r,n)=>{for(var i=n>1?void 0:n?YD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&zD(e,r,i),i},mo,hi,su,ou;const pn=(su=class{constructor(t,e,r){m(this,"connectedMeetings"),_(this,mo,void 0),_(this,hi,void 0),_(this,ou,void 0),T(this,ou,t),T(this,mo,r),this.connectedMeetings=new nv(t,e),this.setCurrentMeeting(e)}static init(t,e,r){return pn.instance||(pn.instance=new pn(t,e,r)),pn.instance.connectedMeetings.supportsConnectedMeetings&&(pn.instance.setupEvents(),e.self.once("roomJoined",()=>pn.instance.getConnectedMeetings())),pn.instance}setCurrentMeeting(t){T(this,hi,t),Ne.currentMeetingId=t.meta.roomName}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){Ne.socketService&&(Ne.socketService.on(j.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),Ne.socketService.on(j.transferPeer,this.handleTransferPeer.bind(this)),Ne.socketService.on(j.movedPeer,this.handleMovedPeer.bind(this)),Ne.socketService.on(j.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),Ne.socketService.on(j.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this)))}handleTransferPeer(t){const e=Ne.handleTransferPeerRaw(t);return this.switchMeeting(e)}switchMeeting(t){return u(this,arguments,function*({authToken:e,meetingId:r}){if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
22
- Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`);this.connectedMeetings.emit("changingMeeting",r),yield c(this,hi).leave("connected-meeting"),Ne.socketService=void 0;const n=yield av.init(ne(V({},c(this,mo)),{cachedUserDetails:null,defaults:ne(V({},c(this,mo).defaults),{video:c(this,hi).self.videoEnabled,audio:c(this,hi).self.audioEnabled}),authToken:e}));n.self.setName(c(this,hi).self.name);try{yield n.join()}catch(i){y.addLogInCurrentSpan("error","ConnectedMeetingsController.joinRoom",{error:i})}return this.connectedMeetings.emit("meetingChanged",n),this.setCurrentMeeting(n),n})}handleConnectedRoomsDump(t){const e=Ne.handleConnectedRoomsDumpRaw(t);this.connectedMeetings.meetings=e.meetings.map(r=>({id:r.id,title:r.title,participants:r.participants||[]})),this.connectedMeetings.parentMeeting={id:e.parentMeeting.id,title:e.parentMeeting.title,participants:e.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(t){return Ne.handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=Ne.handleConnectedRoomsUpdatedRaw(t),r=new Map;this.connectedMeetings.meetings.forEach(n=>{r.set(n.id,n)}),e.forEach(n=>{r.has(n.id)?r.get(n.id).title=n.title:r.set(n.id,ne(V({},n),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(r.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=Ne.handleConnectedRoomsDeletedRaw(t).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id))}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},mo=new WeakMap,hi=new WeakMap,ou=new WeakMap,m(su,"instance"),su);let Nc=pn;iu([y.trace("ConnectedMeetingsController.getConnectedMeetings")],Nc.prototype,"getConnectedMeetings",1),iu([y.trace("ConnectedMeetingsController.setupEvents")],Nc.prototype,"setupEvents",1),iu([y.trace("ConnectedMeetingsController.switchMeeting")],Nc.prototype,"switchMeeting",1);class QD{constructor(){m(this,"battery"),m(this,"init",()=>u(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){l.error("Error getting battery",e)}})),m(this,"updateChargeInfo",()=>{var e;l.log(`Battery charging? ${(e=this.battery)!=null&&e.charging?"Yes":"No"}`)}),m(this,"updateLevelInfo",()=>{if(!this.battery){l.log("Battery level: Not known");return}l.log(`Battery level: ${this.battery.level*100}%`)}),m(this,"cleanup",()=>{var e,r;"getBattery"in navigator&&((e=this.battery)==null||e.removeEventListener("chargingchange",this.updateChargeInfo),(r=this.battery)==null||r.removeEventListener("levelchange",this.updateLevelInfo))})}}const iv=new QD;function XD(t,e){try{const{meetingId:r,orgId:n,participantId:i}=JSON.parse(atob(t.split(".")[1]));if(!r)throw Error(`Received V1 auth token ${t}`);let s="dyte.io";e&&(s=e);const o=`https://api.${s}`;return{meetingId:r,orgId:n,participantId:i,baseURI:s,apiBase:o}}catch(r){throw l.error("constants::decodeAuthToken",{error:r,debuggingHint:`Unable to decode auth token: ${t}`},!0),new C("Invalid auth token")}}var ZD=Object.defineProperty,eO=Object.getOwnPropertyDescriptor,Lc=(t,e,r,n)=>{for(var i=n>1?void 0:n?eO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&ZD(e,r,i),i},at,xc,Fc,au,sv,ov;let mn=(ov=class{constructor(t,e){_(this,au),_(this,at,void 0),_(this,xc,void 0),_(this,Fc,void 0),T(this,Fc,t),T(this,at,e)}static init(t){return u(this,null,function*(){var e,r,n,i,s;Kb(),ye.init();const o=gn();iv.init();const{authToken:a,baseURI:d}=t,h=XD(a,d),{meetingId:p}=h,f=Ro(h,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const g=mn.setupContext(o,t,p,f);y.meetingMetadata.roomName=p,y.meetingMetadata.userId=f.participantId,y.meetingMetadata.organizationId=f.orgId,y.init(g,(r=(e=t.modules)==null?void 0:e.tracing)!=null?r:!0),l.info("DyteClient::init::options",{dyteClientInitOptions:ne(V({},t),{authToken:`${(n=t.authToken)==null?void 0:n.slice(0,10)}...
23
- ${(i=t.authToken)==null?void 0:i.slice(-10)}`})});const E=yield po.init(g),v=new mn(g,E);return ue(s=v,au,sv).call(s,t),v})}static setupContext(t,e,r,n){var i;const s=Ts.createContext(t,e),o=V(V({},$b),e==null?void 0:e.modules);return s.setValue("peerId",t),s.setValue("modules",o),s.setValue("sdkName","web-core"),s.setValue("meetingId",r),s.setValue("apiBase",n.apiBase),s.setValue("baseURI",n.baseURI),s.setValue("userId",n.participantId),s.setValue("organizationId",n.orgId),s.setValue("authToken",e.authToken),s.setValue("overrides",(i=e.overrides)!=null?i:{}),s.setValue("env",Gb({baseURI:n.baseURI})),s.setValue("defaults",e.defaults||{audio:!0,video:!0}),s.setValue("cachedUserDetails",dr(e.cachedUserDetails)),s.setValue("sdkVersion","2.0.0-staging.50"),s}join(){return u(this,null,function*(){const{selfController:t}=c(this,at);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){iv.cleanup();const{selfController:e}=c(this,at);return e.leaveRoom(t)})}get participants(){var t;return(t=c(this,at).participantController)==null?void 0:t.participants}get self(){var t;return(t=c(this,at).selfController)==null?void 0:t.self}get meta(){var t;return(t=c(this,at).metaController)==null?void 0:t.meta}get ai(){var t;return(t=c(this,at).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=c(this,at).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=c(this,at).chatController)==null?void 0:t.chat}get polls(){var t;return(t=c(this,at).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=c(this,xc))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=c(this,at).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=c(this,at).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=c(this,at).stageController)==null?void 0:t.stage}get stores(){return c(this,at).storesManager}get __internals__(){var t;return(t=c(this,at).internalsController)==null?void 0:t.internals}joinRoom(){return u(this,null,function*(){return this.join()})}leaveRoom(t){return u(this,null,function*(){return this.leave(t)})}},at=new WeakMap,xc=new WeakMap,Fc=new WeakMap,au=new WeakSet,sv=function(t){T(this,xc,Nc.init(c(this,Fc),this,t))},ov);Lc([dt("0002"),sn.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],mn.prototype,"join",1),Lc([dt("0003")],mn.prototype,"leave",1),Lc([dt("0001"),sn.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],mn,"init",1),mn=Lc([dt("0000")],mn);const av=mn;return av}();
17
+ ${t}`}const Ui={maxInvocations:5,period:1};function xt(t,e){return function(r,n,i){const s=i.value;let a=0,o=Date.now();return i.value=function(...d){const h=Date.now(),p=e?this[e]:t;if(h-o>p.period*1e3&&(o=h,a=0),a>=p.maxInvocations)throw new _(`Method rate limit ${p.maxInvocations} invocations/${p.period}sec exceeded`,"0013");return a+=1,s.apply(this,d)},i}}var IM=Object.defineProperty,CM=Object.getOwnPropertyDescriptor,yt=(t,e,r,n)=>{for(var i=n>1?void 0:n?CM(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&IM(e,r,i),i};const PM=["text","image","file","custom","poll"],nc={maxInvocations:180,period:60};var se,Bi,Ze,ji,ic,Gl,fg,gg;let it=(gg=class extends jt{constructor(t,e,r,n,i){super(),T(this,Gl),f(this,"messages"),f(this,"channels",[]),T(this,se,void 0),T(this,Bi,void 0),T(this,Ze,void 0),T(this,ji,void 0),T(this,ic,void 0),f(this,"maxTextLimit",2e3),S(this,ic,t),S(this,Ze,e),S(this,ji,r),S(this,se,n),S(this,Bi,i),this.messages=[]}setMaxTextLimit(t){this.maxTextLimit=t}get socketJoined(){return c(this,Gl,fg).socketJoined===!0}sendMessageInternal(t,e,r){return u(this,arguments,function*(n,i,s,a={}){switch(n.type){case"text":{const o=a.replyTo&&a.replyTo.type==="text"?wM(n.message,a.replyTo.message):n.message;yield this.sendTextMessageInternal(o,i,s);break}case"image":yield this.sendImageMessageInternal(n.image,i,s);break;case"file":yield this.sendFileMessageInternal(n.file,i,s);break;default:l.error("sendMessage::message_type_not_supported",{dyteChat:{messageType:n.type}});break}})}sendTextMessageInternal(t,e,r){return u(this,null,function*(){var n,i,s,a,o,d;if(t.length>this.maxTextLimit)throw new _("Max character limit breached","0503");if(e&&e.length>0){if(!((n=c(this,se).permissions)!=null&&n.chatPrivate.canSend)||!((i=c(this,se).permissions)!=null&&i.chatPrivate.text))throw l.error("sendTextMessage::private_chat_permission_denied"),new _("Could not send message to private chat.","0501")}else if(!((a=(s=c(this,se).permissions)==null?void 0:s.chatPublic)!=null&&a.canSend)||!((d=(o=c(this,se).permissions)==null?void 0:o.chatPublic)!=null&&d.text))throw l.error("sendTextMessage::public_chat_permission_denied"),new _("Could not send message to public chat.","0501");if(!t)throw l.error("sendTextMessage::message_can_not_be_empty"),new _("Message can not be empty.","0502");if(r){c(this,Ze).sendMessageToChannel(t,kt.TEXT,r);return}let h=[];e&&e.length>0&&(e.push(c(this,se).id),h=c(this,Bi).joined.toArray().filter(p=>e.includes(p.id)).map(p=>p.userId),h.push(c(this,se).userId)),c(this,Ze).sendMessage(t,kt.TEXT,e)})}sendImageMessageInternal(t,e,r){return u(this,null,function*(){var n,i,s,a,o,d;if(e&&e.length>0){if(!((n=c(this,se).permissions)!=null&&n.chatPrivate.canSend)||!((i=c(this,se).permissions)!=null&&i.chatPrivate.files)){l.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((a=(s=c(this,se).permissions)==null?void 0:s.chatPublic)!=null&&a.canSend)||!((d=(o=c(this,se).permissions)==null?void 0:o.chatPublic)!=null&&d.files)){l.error("sendImageMessage::permission_denied");return}if(!t){l.error("sendImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(t.type)){l.error("sendImageMessage::image_type_not_supported",{dyteChat:{imageType:t.type}});return}try{const h=qe(),{getLocation:p,putLocation:m}=yield h.getPresignedUrls(t.name,c(this,se).config.viewType);if(yield h.uploadFile(t,m),r){c(this,Ze).sendMessageToChannel(p,kt.IMAGE,r);return}let g=[];e&&e.length>0&&(e.push(c(this,se).id),g=c(this,Bi).joined.toArray().filter(v=>e.includes(v.id)).map(v=>v.userId),g.push(c(this,se).userId)),c(this,Ze).sendMessage(p,kt.IMAGE,e)}catch(h){throw new _("Error sending image message.","0500")}})}sendFileMessageInternal(t,e,r){return u(this,null,function*(){var n,i,s,a,o,d;if(e&&e.length>0){if(!((n=c(this,se).permissions)!=null&&n.chatPrivate.canSend)||!((i=c(this,se).permissions)!=null&&i.chatPrivate.files)){l.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((a=(s=c(this,se).permissions)==null?void 0:s.chatPublic)!=null&&a.canSend)||!((d=(o=c(this,se).permissions)==null?void 0:o.chatPublic)!=null&&d.files)){l.error("sendFileMessage::permission_denied");return}if(!t){l.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const h=qe(),{getLocation:p,putLocation:m}=yield h.getPresignedUrls(t.name,c(this,se).config.viewType);if(yield h.uploadFile(t,m),r){c(this,Ze).sendMessageToChannel(JSON.stringify({link:p,name:t.name,size:"size"in t?t.size:0}),kt.FILE,r);return}let g=[];e&&e.length>0&&(e.push(c(this,se).id),g=c(this,Bi).joined.toArray().filter(I=>e.includes(I.id)).map(I=>I.userId),g.push(c(this,se).userId));const v=JSON.stringify({link:p,name:t.name,size:"size"in t?t.size:0});c(this,Ze).sendMessage(v,kt.FILE,e)}catch(h){throw new _("Error sending file message.","0500")}})}get rateLimits(){return nc}updateRateLimits(t,e){nc.maxInvocations=t,nc.period=e}sendTextMessage(t,e){return u(this,null,function*(){return this.sendTextMessageInternal(t,e)})}sendCustomMessage(t,e){return u(this,null,function*(){var r,n,i,s,a,o,d,h,p,m,g,v,I,A,P;if(e&&e.length>0){if(!((r=c(this,se).permissions)!=null&&r.chatPrivate.canSend)||!((n=c(this,se).permissions)!=null&&n.chatPrivate.files)||!((i=c(this,se).permissions)!=null&&i.chatPrivate.text)){l.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((a=(s=c(this,se).permissions)==null?void 0:s.chatPublic)!=null&&a.canSend)||!((d=(o=c(this,se).permissions)==null?void 0:o.chatPublic)!=null&&d.files)||!((p=(h=c(this,se).permissions)==null?void 0:h.chatPublic)!=null&&p.text)){l.error("sendCustomMessage::permission_denied");return}const D=J=>u(this,null,function*(){try{if(typeof J=="string")return{link:J};const C=qe(),{getLocation:G,putLocation:W}=yield C.getPresignedUrls(J.name,c(this,se).config.viewType);return yield C.uploadFile(J,W),{link:G,type:J.type,name:J.name,size:J.size}}catch(C){throw new _("Error sending image message.","0500")}}),N=X(U({},t),{files:yield Promise.all((g=(m=t.files)!=null?m:[])==null?void 0:g.map(J=>u(this,null,function*(){return D(J)}))),images:yield Promise.all((I=(v=t.images)!=null?v:[])==null?void 0:I.map(J=>u(this,null,function*(){return D(J)}))),videos:yield Promise.all((P=(A=t.videos)!=null?A:[])==null?void 0:P.map(J=>u(this,null,function*(){return D(J)})))});c(this,Ze).sendMessage(JSON.stringify(N),kt.CUSTOM,e)})}sendImageMessage(t,e){return u(this,null,function*(){return this.sendImageMessageInternal(t,e)})}sendFileMessage(t,e){return u(this,null,function*(){return this.sendFileMessageInternal(t,e)})}sendMessage(t,e){return u(this,null,function*(){return this.sendMessageInternal(t,e)})}editTextMessage(t,e,r){return u(this,null,function*(){var n,i,s,a,o,d;if(((i=(n=c(this,se).permissions)==null?void 0:n.chatMessage)==null?void 0:i.canEdit)==="NONE")throw new _("Not permitted to edit messages","0501");if(!((a=(s=c(this,se).permissions)==null?void 0:s.chatPublic)!=null&&a.canSend)||!((d=(o=c(this,se).permissions)==null?void 0:o.chatPublic)!=null&&d.text)){l.error("editTextMessage::permission_denied");return}if(!e){l.error("editTextMessage::message_can_not_be_empty");return}c(this,Ze).editMessage(t,e,kt.TEXT,r)})}editImageMessage(t,e,r){return u(this,null,function*(){var n,i,s,a;if(!((i=(n=c(this,se).permissions)==null?void 0:n.chatPublic)!=null&&i.canSend)||!((a=(s=c(this,se).permissions)==null?void 0:s.chatPublic)!=null&&a.files)){l.error("editImageMessage::permission_denied");return}if(!e){l.error("editImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(e.type)){l.error("sendImageMessage::image_type_not_supported",{dyteChat:{imageType:e.type}});return}try{const o=qe(),{getLocation:d,putLocation:h}=yield o.getPresignedUrls(e.name,c(this,se).config.viewType);yield o.uploadFile(e,h),c(this,Ze).editMessage(t,d,kt.IMAGE,r)}catch(o){throw new _("Error editing image message.","0500")}})}editFileMessage(t,e,r){return u(this,null,function*(){var n,i,s,a;if(!((i=(n=c(this,se).permissions)==null?void 0:n.chatPublic)!=null&&i.canSend)||!((a=(s=c(this,se).permissions)==null?void 0:s.chatPublic)!=null&&a.files)){l.error("sendFileMessage::permission_denied");return}if(!e){l.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const o=qe(),{getLocation:d,putLocation:h}=yield o.getPresignedUrls(e.name,c(this,se).config.viewType);yield o.uploadFile(e,h),c(this,Ze).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),kt.FILE,r)}catch(o){throw new _("Error editing file message.","0500")}})}editMessage(t,e,r){return u(this,null,function*(){switch(e.type){case"text":{this.editTextMessage(t,e.message,r);break}case"image":{this.editImageMessage(t,e.image,r);break}case"file":{this.editFileMessage(t,e.file,r);break}default:{l.error("editMessage::message_type_not_supported",{dyteChat:{messageType:e.type}});break}}})}deleteMessage(t,e){return u(this,null,function*(){var r,n;if(((n=(r=c(this,se).permissions)==null?void 0:r.chatMessage)==null?void 0:n.canDelete)==="NONE")throw new _("Not permitted to delete messages","0501");c(this,Ze).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 u(this,null,function*(){if(!this.socketJoined)throw new _("Can`t pin message without joining room","0505");if(!c(this,se).permissions.pinParticipant)throw new _("You do not have permission to pin messages.","0501");const e=this.messages.find(r=>r.id===t);if(e){c(this,Ze).setPinState(e,!0);return}throw new _(`No message found with id: ${t}`,"0504")})}unpin(t){return u(this,null,function*(){if(!this.socketJoined)throw new _("Can`t unpin message without joining room","0505");if(!c(this,se).permissions.pinParticipant)throw new _("You do not have permission to unpin messages.","0501");const e=this.messages.find(r=>r.id===t);if(e){c(this,Ze).setPinState(e,!1);return}throw new _(`No message found with id: ${t}`,"0504")})}getMessages(t,e,r,n=0,i=void 0){return u(this,null,function*(){const s=yield c(this,Ze).getChatMessagesPaginated(t,e,r,n,i);return{messages:s.messages.map(a=>xr.formatSocketServiceMessage(a)),next:s.next}})}createChannel(t,e){return u(this,arguments,function*(r,n,i={}){var s;const a=(s=c(this,se).permissions)==null?void 0:s.chatChannel;if(a){if(a.canCreate==="NONE")throw new _("Not permitted to create channels","0501");if(i.visibility==="public"&&!(a.canCreate==="PUBLIC"||a.canCreate==="ALL"))throw new _("Not permitted to create public channels","0501");if(i.visibility==="private"&&!(a.canCreate==="PRIVATE"||a.canCreate==="ALL"))throw new _("Not permitted to create private channels","0501")}if(!r||r.trim().length===0)throw new _("channel name cannot be empty.","0510");const o=[...new Set([...n,c(this,se).userId])];return yield c(this,ji).createChannel(r.trim(),o,i.displayPictureUrl,i.visibility,i.isDirectMessage)})}updateChannel(t,e){var r,n,i,s,a;const o=this.channels.find(p=>p.id===t),d=(r=c(this,se).permissions)==null?void 0:r.chatChannel;if(d){if(d.canUpdate==="NONE")throw new _("Not permitted to update channels","0501");if(o.visibility==="public"&&!(d.canUpdate==="PUBLIC"||d.canUpdate==="ALL"))throw new _("Not permitted to update public channels","0501");if(o.visibility==="private"&&!(d.canUpdate==="PRIVATE"||d.canUpdate==="ALL"))throw new _("Not permitted to update private channels","0501")}const h={memberIds:(n=e.memberIds)!=null?n:o.memberIds,displayName:(i=e.displayName)!=null?i:o.displayName,displayPictureUrl:(s=e.displayPictureUrl)!=null?s:o.displayPictureUrl,visibility:(a=e.visibility)!=null?a:o.visibility};return c(this,ji).updateChannel(t,h)}sendMessageToChannel(t,e){return u(this,arguments,function*(r,n,i={}){return this.sendMessageInternal(r,null,n,i)})}getChannelMembers(t){return u(this,null,function*(){return c(this,ji).getChannelMembers(t)})}searchMessages(t){return u(this,arguments,function*(e,r={}){if(!Q.hasFeature(ie.FEAT_CHAT_SDK_SEARCH))throw new _("searchMessages is temporarily disabled!","0506");return(yield c(this,Ze).searchMessages(e,r)).map(xr.formatSocketServiceMessage)})}markLastReadMessage(t,e){return u(this,null,function*(){yield c(this,Ze).markLastReadMessage(t,e);const r=this.channels.find(n=>n.id===t);if(r){const n=X(U({},r),{unreadCount:0});this.channels=this.channels.map(i=>i.id===t?n:i),this.emit("channelMessageUpdate",n)}})}get pinned(){return this.messages.filter(t=>t.pinned)}},se=new WeakMap,Bi=new WeakMap,Ze=new WeakMap,ji=new WeakMap,ic=new WeakMap,Gl=new WeakSet,fg=function(){return c(this,ic).getValue("connectionHandler")},gg);yt([y.trace("DyteChat.sendTextMessage"),xt(nc)],it.prototype,"sendTextMessage",1),yt([y.trace("DyteChat.sendImageMessage"),xt({maxInvocations:20,period:60})],it.prototype,"sendImageMessage",1),yt([y.trace("DyteChat.sendFileMessage"),xt({maxInvocations:20,period:60})],it.prototype,"sendFileMessage",1),yt([y.trace("DyteChat.sendMessage"),xt({maxInvocations:180,period:60})],it.prototype,"sendMessage",1),yt([y.trace("DyteChat.editTextMessage")],it.prototype,"editTextMessage",1),yt([y.trace("DyteChat.editImageMessage")],it.prototype,"editImageMessage",1),yt([y.trace("DyteChat.editFileMessage")],it.prototype,"editFileMessage",1),yt([y.trace("DyteChat.editMessage")],it.prototype,"editMessage",1),yt([y.trace("DyteChat.deleteMessage")],it.prototype,"deleteMessage",1),yt([y.trace("DyteChat.createChannel")],it.prototype,"createChannel",1),yt([y.trace("DyteChat.updateChannel")],it.prototype,"updateChannel",1),yt([y.trace("DyteChat.sendMessageToChannel")],it.prototype,"sendMessageToChannel",1),yt([y.trace("DyteChat.getChannelMembers")],it.prototype,"getChannelMembers",1),yt([y.trace("DyteChat.searchMessages")],it.prototype,"searchMessages",1),yt([y.trace("DyteChat.markLastReadMessage")],it.prototype,"markLastReadMessage",1),it=yt([vt("0500")],it);var RM=Object.defineProperty,AM=Object.getOwnPropertyDescriptor,MM=(t,e,r,n)=>{for(var i=n>1?void 0:n?AM(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&RM(e,r,i),i},ql,vg;const Zn=(vg=class{constructor(t,e,r,n,i){f(this,"chat"),f(this,"chatSocketHandler"),f(this,"chatChannelSocketHandler"),f(this,"self"),T(this,ql,void 0),S(this,ql,t),this.chatSocketHandler=e,this.chatChannelSocketHandler=r,this.chat=new it(t,e,r,n,i),this.self=n,this.setupEvents()}static init(t,e,r,n,i){return u(this,null,function*(){return new Zn(t,e,r,n,i)})}static formatMessage(t){return X(U({},t),{time:new Date(t.time),type:PM[t.type]})}static formatSocketServiceMessage(t){const e=t.createdAt*1e3,r={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(r.type){case kt.TEXT:{r.message=t.payload;break}case kt.IMAGE:{r.link=t.payload;break}case kt.FILE:{const{link:n,name:i,size:s}=JSON.parse(t.payload);r.link=n,r.name=i,r.size=s;break}case kt.CUSTOM:{const{html:n,images:i,message:s,videos:a,files:o}=JSON.parse(t.payload);r.message=s,r.html=n,r.images=i,r.videos=a,r.files=o;break}}return Zn.formatMessage(r)}getChatMessages(){return u(this,null,function*(){if(this.self.config.viewType==="LIVESTREAM"||this.self.config.viewType==="CHAT"||Q.hasFeature(ie.FEAT_PAGINATED_CHAT))return;const t=yield this.chatSocketHandler.getChatMessages();if(!(t!=null&&t.payload))return;const e=tg.fromBinary(t.payload).messages;this.chat.messages=e.map(r=>Zn.formatSocketServiceMessage(r))})}setupEvents(){b.on(w.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){this.getChatMessages()})),this.chatSocketHandler.on(xe.sendMessageToRoom,t=>{const e=Zn.formatSocketServiceMessage(t.message);if(!e.channelId)this.chat.messages=[...this.chat.messages,e];else{const r=this.chat.channels.find(n=>n.id===e.channelId);r&&(r.latestMessage=e,r.unreadCount+=1,this.chat.emit("channelMessageUpdate",r))}this.chat.emit("chatUpdate",{action:"add",message:e,messages:this.chat.messages})}),this.chatSocketHandler.on(xe.sendMessageToPeers,t=>{const e=Zn.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(xe.editMessage,t=>{const e=Zn.formatSocketServiceMessage(t.message);if(e.channelId){this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages});return}const r=this.chat.messages.findIndex(n=>n.id===e.id);r!==-1&&(this.chat.messages[r]=e,this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages}))}),this.chatSocketHandler.on(xe.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(n=>n.id===t.chatId);if(e===-1)return;const[r]=this.chat.messages.splice(e,1);this.chat.emit("chatUpdate",{action:"delete",message:r,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(Yn.createChatChannel,t=>{const[e]=t.chatChannels,r=Xn.formatChannel(e);this.chat.channels.push(r),this.chat.emit("channelCreate",r)}),this.chatSocketHandler.on(xe.pinMessage,t=>{const e=this.chat.messages.findIndex(n=>n.id===t.chatId);if(e===-1)return;const r=this.chat.messages[e];r.pinned=t.pinned,this.chat.messages[e]=r,this.chat.emit("chatUpdate",{action:"edit",message:r,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(Yn.updateChatChannel,t=>{const[e]=t.chatChannels,r=Xn.formatChannel(e);this.chat.channels=this.chat.channels.map(n=>n.id===r.id?r:n),this.chat.emit("channelUpdate",r)})}},ql=new WeakMap,vg);let xr=Zn;MM([y.trace("ChatController.setupEvents")],xr.prototype,"setupEvents",1);var DM=Object.defineProperty,OM=Object.getOwnPropertyDescriptor,NM=(t,e,r,n)=>{for(var i=n>1?void 0:n?OM(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&DM(e,r,i),i},zl,yg,Us,Bs,sc,Sg;let Kl=(Sg=class extends jt{constructor(t,e,r){super(),T(this,zl),f(this,"items"),T(this,Us,void 0),T(this,Bs,void 0),T(this,sc,void 0),S(this,sc,t),S(this,Us,e),S(this,Bs,r),this.items=[]}get socketJoined(){var t;return((t=c(this,zl,yg))==null?void 0:t.socketJoined)===!0}create(t,e,r=!1,n=!1){return u(this,null,function*(){if(!this.socketJoined)throw new _("Can't create polls without joining room","0705");if(!c(this,Us).permissions.polls.canCreate){l.error("DytePolls::create::permission_denied");return}if(!t||!e){l.error("DytePolls::question_and_options_can_not_be_empty",{dytePolls:{hasQuestion:!!t,optionsLength:e==null?void 0:e.length}});return}if(e.length<2){l.error("DytePolls::there_must_be_at_least_two_options",{dytePolls:{hasQuestion:!!t,optionsLength:e.length}});return}yield c(this,Bs).createPoll(t,e,r,n)})}vote(t,e){return u(this,null,function*(){if(!c(this,Us).permissions.polls.canVote){l.error("DytePolls::vote::permission_denied");return}yield c(this,Bs).votePoll(t,e)})}},zl=new WeakSet,yg=function(){return c(this,sc).getValue("connectionHandler")},Us=new WeakMap,Bs=new WeakMap,sc=new WeakMap,Sg);Kl=NM([vt("0700")],Kl);var LM=Object.defineProperty,xM=Object.getOwnPropertyDescriptor,FM=(t,e,r,n)=>{for(var i=n>1?void 0:n?xM(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&LM(e,r,i),i},js,Hi,Eg;const Wi=(Eg=class{constructor(t,e,r){f(this,"polls"),T(this,js,void 0),T(this,Hi,void 0),this.polls=new Kl(t,e,r),S(this,js,e),S(this,Hi,r),this.setupEvents()}static init(t,e,r){return u(this,null,function*(){return new Wi(t,e,r)})}canViewPolls(){return c(this,js).permissions.polls.canView}setupEvents(){const t={[Nr.createPoll]:n=>{n.poll&&this.updatePoll(Wi.formatSocketServicePoll(n.poll))},[Nr.updatePoll]:n=>{n.poll&&this.updatePoll(Wi.formatSocketServicePoll(n.poll))},[Nr.votePoll]:n=>{n.poll&&this.updatePoll(Wi.formatSocketServicePoll(n.poll))}},e=()=>{b.on(w.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(t).map(Number).forEach(n=>{c(this,Hi).on(n,t[n])})},r=()=>{b.on(w.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(t).map(Number).forEach(n=>{c(this,Hi).removeListeners(n)})};c(this,js).permissions.on("permissionsUpdate",n=>u(this,null,function*(){var i;(i=n==null?void 0:n.polls)!=null&&i.canView?(yield this.getPolls(),e()):(this.polls.items=[],r())})),this.canViewPolls()&&e()}updatePoll(t){if(!this.canViewPolls())return;const e=this.polls.items.findIndex(r=>r.id===t.id);if(e>-1){const r=JSON.stringify(this.polls.items[e]);this.polls.items[e]=t,r!==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 u(this,null,function*(){const t=yield c(this,Hi).getPolls();if(!(t!=null&&t.payload))return;const{polls:e}=KA.fromBinary(t.payload);this.polls.items=e.map(r=>Wi.formatSocketServicePoll(r))})}static formatSocketServicePoll(t){const e=t.options.map(r=>({count:r.count,text:r.text,votes:r.votes.map(n=>({id:n.userId,name:n.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}}},js=new WeakMap,Hi=new WeakMap,Eg);let Tg=Wi;FM([y.trace("PollController.setupEvents")],Tg.prototype,"setupEvents",1);var VM=Object.defineProperty,UM=Object.getOwnPropertyDescriptor,BM=(t,e,r,n)=>{for(var i=n>1?void 0:n?UM(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&VM(e,r,i),i},kg=(t=>(t[t.User=0]="User",t[t.Meeting=1]="Meeting",t))(kg||{}),Hs,Yl,_g,ac,Ql,$i,oc,bg;let Xl=(bg=class extends jt{constructor(t,e,r,n,i){super(),T(this,Yl),T(this,ac),f(this,"selfActiveTab"),f(this,"broadcastTabChanges"),T(this,Hs,void 0),T(this,$i,void 0),T(this,oc,void 0),f(this,"viewType"),f(this,"meetingStartedTimestamp"),f(this,"meetingTitle"),f(this,"sessionId"),S(this,Hs,t),S(this,$i,e),this.viewType=r,S(this,oc,n),this.meetingTitle=i,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return c(this,ac,Ql).socketState}get mediaState(){return c(this,ac,Ql).mediaState}get meetingId(){var t;return(t=c(this,Yl,_g))==null?void 0:t.roomName}setBroadcastTabChanges(t){if(!c(this,$i).permissions.canSpotlight)throw l.error("DyteSpotlight::setSpotlighted::permission_denied"),new _("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 r;l.info("DyteSpotlight::setActiveTab",{spotlight:{currentTab:{id:t.id,type:t.type}}}),this.selfActiveTab=t,e===0&&this.emit("selfTabUpdate",t),(r=c(this,$i).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){c(this,oc).broadcastMessage("spotlight",{userId:c(this,$i).userId,currentTab:this.selfActiveTab})}},Hs=new WeakMap,Yl=new WeakSet,_g=function(){return c(this,Hs).getValue("roomNodeClient")},ac=new WeakSet,Ql=function(){return c(this,Hs).getValue("connectionHandler")},$i=new WeakMap,oc=new WeakMap,bg);Xl=BM([vt("0800")],Xl);function jM(t){let e="",r=[""];const n=[r];let i=0,s=0,a=!0,o;for(o of t)o==='"'?(a&&o===e&&(r[i]+=o),a=!a):o===","&&a?o=r[++i]="":o===`
18
+ `&&a?(e==="\r"&&(r[i]=r[i].slice(0,-1)),r=n[++s]=[o=""],i=0):r[i]+=o,e=o;return n}var HM=Object.defineProperty,WM=Object.getOwnPropertyDescriptor,wg=(t,e,r,n)=>{for(var i=n>1?void 0:n?WM(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&HM(e,r,i),i};let fn=class extends jt{constructor(){super(),f(this,"transcripts"),this.transcripts=[]}static init(t){return u(this,null,function*(){const e=new fn;try{t&&e.getActiveTranscript()}catch(r){l.error("Error fetching active transcriptions ",r)}return e})}static parseTranscript(t,e=!1){try{if(!t)return;const[[r,n,i,s,a,o]]=jM(t);return{id:Un(),name:a,peerId:n,userId:i,customParticipantId:s,transcript:o,isPartialTranscript:e,date:new Date(parseInt(r,10)*1e3)}}catch(r){l.error(`Failed to parse transcript: ${t}`,r);return}}static parseTranscripts(t){return t?t.split(`
19
+ `).map(e=>fn.parseTranscript(e,!1)).filter(Boolean):[]}getActiveTranscript(){return u(this,null,function*(){try{const t=qe(),{transcript:e}=yield t.getActiveTranscript();this.transcripts=fn.parseTranscripts(e)}catch(t){}})}onTranscript(t){return u(this,null,function*(){var e;const r=this.transcripts.filter(({peerId:n})=>n===t.peerId);if((e=r==null?void 0:r.at(-1))!=null&&e.isPartialTranscript){const n=r.at(-1);n.transcript=t.transcript,n.isPartialTranscript=t.isPartialTranscript,this.emit("transcript",n);return}this.transcripts=[...this.transcripts,t],this.emit("transcript",t)})}};wg([y.trace("DyteAi.getActiveTranscript")],fn.prototype,"getActiveTranscript",1),fn=wg([vt("0000")],fn);var $M=Object.defineProperty,JM=Object.getOwnPropertyDescriptor,GM=(t,e,r,n)=>{for(var i=n>1?void 0:n?JM(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&$M(e,r,i),i},ei,Ws,Zl,Ig;const Cg=(Ig=class{constructor(t,e,r,n,i,s){f(this,"meta"),f(this,"ai"),T(this,ei,void 0),T(this,Ws,void 0),f(this,"aiSocketHandler"),T(this,Zl,void 0),S(this,Zl,t),this.meta=new Xl(t,e,e.config.viewType,r,s),this.ai=n,S(this,ei,e),S(this,Ws,r),this.aiSocketHandler=i,e.config.viewType!==gt.Chat&&this.setupEvents()}static init(t,e,r,n,i){return u(this,null,function*(){const s=yield fn.init(e.permissions.transcriptionEnabled);return new Cg(t,e,r,s,n,i)})}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,kg.Meeting),this.meta.emit("activeTabUpdate",t.currentTab))}setupEvents(){b.on(w.TRANSPORT_STATE_UPDATE,t=>{this.meta.emit("mediaConnectionUpdate",t)}),b.on(w.SOCKET_STATE_UPDATE,t=>{this.meta.emit("socketConnectionUpdate",t)}),b.on(w.ROOM_STATE,({createdAt:t,roomUuid:e})=>{const r=this.meta.meetingStartedTimestamp;if(e&&(this.meta.sessionId=e),t&&!r){const n=new Date(t*1e3);this.meta.meetingStartedTimestamp=n,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),b.on(w.PRODUCER_SCORE_UPDATE,({score:t})=>{t<5&&this.meta.emit("poorConnection",{score:t})}),c(this,ei).permissions.canSpotlight&&(l.info("DyteMetaController::Asserting Spotlight"),this.meta.selfActiveTab&&c(this,Ws).broadcastMessage("spotlight",{userId:c(this,ei).userId,currentTab:this.meta.selfActiveTab})),b.on(w.PEER_JOINED_INTERNAL,t=>u(this,null,function*(){c(this,ei).permissions.canSpotlight&&this.meta.selfActiveTab&&c(this,Ws).broadcastToPeers("spotlight",[t.id],{userId:c(this,ei).userId,currentTab:this.meta.selfActiveTab})})),b.on(w.ROOM_MESSAGE,t=>{var e,r;let n;if("type"in t){if(t.type!=="spotlight")return;n=U(U({},t),t.payload)}else if("roomMessageType"in t){if(t.roomMessageType!=="spotlight")return;n=t}else return;l.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:n.userId},currentTab:{id:(e=n.currentTab)==null?void 0:e.id,type:(r=n.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(n)}),b.on(w.MESSAGE,t=>{var e,r;let n;if("type"in t){if(t.type!=="spotlight")return;n=U(U({},t),t.payload)}else if("roomMessageType"in t){if(t.roomMessageType!=="spotlight")return;n=t}else return;l.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:n.userId},currentTab:{id:(e=n.currentTab)==null?void 0:e.id,type:(r=n.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(n)}),this.aiSocketHandler.on(j.transcript,t=>{const{meetingId:e,transcript:r,isPartial:n}=t,i=fn.parseTranscript(r,n);if(!i){l.warn("Received empty transcript data");return}this.ai.onTranscript(i),this.meta.emit("transcript",i);const{peerId:s,name:a,transcript:o}=i;l.debug(`${e} Received transcript for peer ${s} - ${a}: ${o}`)})}},ei=new WeakMap,Ws=new WeakMap,Zl=new WeakMap,Ig);let Pg=Cg;GM([y.trace("MetaController.setupEvents")],Pg.prototype,"setupEvents",1);var qM=Object.defineProperty,zM=Object.getOwnPropertyDescriptor,ti=(t,e,r,n)=>{for(var i=n>1?void 0:n?zM(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&qM(e,r,i),i},lr,$s,Ae,cc,Fr,Vr,Js,dc;class gn extends jt{constructor(e,r,n,i,s){super(),T(this,Js),T(this,lr,void 0),T(this,$s,void 0),T(this,Ae,void 0),T(this,cc,void 0),T(this,Fr,void 0),T(this,Vr,void 0),S(this,Vr,e),S(this,lr,i),S(this,$s,s),S(this,Ae,r),S(this,cc,n),S(this,Fr,[]),this.setupEvents()}get status(){return c(this,Vr).getValue("stageStatus")}setupEvents(){const e={[w.GET_STAGE_REQUESTS]:i=>u(this,null,function*(){S(this,Fr,i)}),[w.UPDATE_STAGE_REQUESTS]:i=>u(this,[i],function*({add:s}){const a=c(this,Fr).length,{stageRequests:o}=this.getAccessRequests();(s||o.length>a)&&this.emit("newStageRequest",{count:o.length}),this.emit("stageAccessRequestUpdate",o)})},r=()=>{Object.entries(e).forEach(([i,s])=>{b.onAsync(i,s)})},n=()=>{Object.entries(e).forEach(([i,s])=>{b.removeListener(i,s)})};c(this,Ae).permissions.on("permissionsUpdate",i=>{const{canAcceptProductionRequests:s}=i;s!==void 0&&(c(this,Ae).permissions.acceptStageRequests?(r(),c(this,lr).getStageRequests()):(n(),S(this,Fr,[]),this.emit("stageAccessRequestUpdate",c(this,Fr))))}),c(this,Ae).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!c(this,Ae).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new _("Stage is disabled","2003");if(!c(this,Ae).permissions.acceptStageRequests)throw l.error("DyteStage::get_access_request::permission_denied"),new _("You do not have permission to perform this action","2001");const e=c(this,cc).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return S(this,Fr,e),{stageRequests:c(this,Fr)}}requestAccess(){return u(this,null,function*(){if(!c(this,Ae).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new _("Stage is disabled","2003");if(this.status!=="OFF_STAGE")throw new _(`Unable to request access you are currently ${this.status}`,"2006");if(c(this,Ae).permissions.stageAccess===K.Allowed){Je(this,Js,dc).call(this,"ACCEPTED_TO_JOIN_STAGE");return}c(this,lr).requestAccess(),Je(this,Js,dc).call(this,"REQUESTED_TO_JOIN_STAGE")})}cancelRequestAccess(){return u(this,null,function*(){if(!c(this,Ae).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new _("Stage is disabled","2003");c(this,lr).cancelRequestAccess(),Je(this,Js,dc).call(this,"OFF_STAGE")})}grantAccess(e){if(!c(this,Ae).roomJoined)throw new _("Can`t grant for participant without joining room");if(!c(this,Ae).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new _("Stage is disabled","2003");if(!c(this,Ae).permissions.acceptStageRequests)throw l.error("DyteStage::grant_access::permission_denied"),new _("You do not have permission to perform this action","2001");return c(this,lr).grantAccess(e)}denyAccess(e){if(!c(this,Ae).roomJoined)throw new _("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!c(this,Ae).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new _("Stage is disabled","2003");if(!c(this,Ae).permissions.acceptStageRequests)throw l.error("DyteStage::deny_access::permission_denied"),new _("You do not have permission to perform this action","2001");return c(this,lr).denyAccess(e)}join(){return u(this,null,function*(){const e=c(this,Vr).getValue("viewType");if(this.status==="ON_STAGE")throw new _("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||c(this,Ae).permissions.stageAccess===K.NotAllowed)throw new _(`Unable to join stage you are currently ${this.status}`,"2006");if(yield c(this,lr).joinStage(),e===gt.Livestream?yield c(this,$s).joinRoom(c(this,Ae),e):b.emit(w.RESET_PRODUCER_STATE),c(this,Vr).setValue("stageStatus","ON_STAGE"),e===gt.Livestream){const{peers:r}=yield c(this,$s).getStagePeers();b.emit(w.SOCKET_PEERS,r),b.emit(w.JOIN_MEDIA_ROOM,r)}})}leave(){return u(this,null,function*(){if(!c(this,Ae).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new _("Stage is disabled","2003");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new _(`Unable to leave stage you are currently ${this.status}`,"2006");c(this,Ae).setIsPinned(!1),yield c(this,lr).leaveStage(c(this,Ae).userId),c(this,Vr).setValue("stageStatus","OFF_STAGE",!1),yield b.emitAsync(w.LEAVE_MEDIA_ROOM,"stageLeft"),c(this,Vr).notify("stageStatus")})}kick(e){return u(this,null,function*(){if(!c(this,Ae).roomJoined)throw new _("Can`t kick participant without joining room","2005");if(!c(this,Ae).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new _("Stage is disabled","2003");if(!c(this,Ae).permissions.acceptStageRequests)throw l.error("DyteStage::kick::permission_denied"),new _("You do not have permissions for kick","2001");return c(this,lr).kick(e)})}}lr=new WeakMap,$s=new WeakMap,Ae=new WeakMap,cc=new WeakMap,Fr=new WeakMap,Vr=new WeakMap,Js=new WeakSet,dc=function(t){return u(this,null,function*(){this.status!==t&&c(this,Vr).setValue("stageStatus",t)})},ti([y.trace("DyteStage.getStageRequests")],gn.prototype,"getAccessRequests",1),ti([y.trace("DyteStage.requestAccess")],gn.prototype,"requestAccess",1),ti([y.trace("DyteStage.cancelRequestAccess")],gn.prototype,"cancelRequestAccess",1),ti([y.trace("DyteStage.grantAccess")],gn.prototype,"grantAccess",1),ti([y.trace("DyteStage.denyAccess")],gn.prototype,"denyAccess",1),ti([y.trace("DyteStage.joinStage")],gn.prototype,"join",1),ti([y.trace("DyteStage.leaveStage")],gn.prototype,"leave",1);function KM(t){return!(t.viewType==="LIVESTREAM"||t.viewType==="CHAT")}function eu(t){switch(t){case Dr.UNSPECIFIED:return"OFF_STAGE";case Dr.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case Dr.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case Dr.OFF_STAGE:return"OFF_STAGE";case Dr.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var YM=Object.defineProperty,QM=Object.getOwnPropertyDescriptor,XM=(t,e,r,n)=>{for(var i=n>1?void 0:n?QM(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&YM(e,r,i),i},ri,Ji,ni,lc,vn;class Rg{constructor(e,r,n,i,s){f(this,"stage"),T(this,ri,void 0),T(this,Ji,void 0),T(this,ni,void 0),T(this,lc,0),T(this,vn,void 0),S(this,vn,e),this.stage=new gn(e,i,s,r,n),S(this,ni,r),S(this,ri,i),S(this,Ji,s),this.setupEvents()}setupEvents(){c(this,vn).subscribe("stageStatus",e=>{this.stage.emit("stageStatusUpdate",e)}),c(this,ni).on(j.grantStageAccess,()=>{c(this,ri).permissions.stageAccess!==K.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),c(this,ni).on(j.peerStageStatusUpdate,e=>{e!==void 0&&(e.peerId===c(this,ri).id?this.selfStageStatusHandler(e):this.peerStageStatusHandler(e))}),c(this,ni).on(j.denyStageAccess,()=>{c(this,ri).permissions.stageAccess!==K.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),c(this,ni).on(j.getStageRequests,e=>u(this,null,function*(){var r;if(c(this,ri).permissions.stageAccess!==K.Allowed)return;const n=(r=e==null?void 0:e.stageRequests)!=null?r:[];yield b.emitAsync(w.GET_STAGE_REQUESTS,n),c(this,lc)<n.length&&n.length>0&&this.stage.emit("newStageRequest",{count:n.length}),S(this,lc,n.length),this.stage.emit("stageAccessRequestUpdate",n)}))}getCurrentStageRequests(){return c(this,Ji).joined.toArray().filter(e=>e.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(e=>({displayName:e.name,userId:e.userId,peerId:e.id}))}setStageStatus(e){return u(this,null,function*(){this.stage.status!==e&&c(this,vn).setValue("stageStatus",e)})}selfStageStatusHandler(e){const r=eu(e.stageType),n=c(this,vn).getValue("stageStatus");if(n!==r)switch(e.stageType){case 1:c(this,vn).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(n);break;case 0:case 4:default:c(this,vn).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}peerStageStatusHandler(e){return u(this,null,function*(){const r=c(this,Ji).joined.get(e.peerId),n=c(this,Ji).viewMode==="ACTIVE_GRID";if(!r){l.warn("err::peerStageStatusUpdate: participant not found");return}switch(e.stageType){case 1:r.setStageStatus("ON_STAGE"),n&&b.emit(w.UPDATE_ACTIVE);break;case 2:r.setStageStatus("ACCEPTED_TO_JOIN_STAGE");break;case 3:r.setStageStatus("REQUESTED_TO_JOIN_STAGE");break;case 0:case 4:default:r.setStageStatus("OFF_STAGE"),n&&b.emit(w.UPDATE_ACTIVE);break}b.emit(w.UPDATE_PEER_STAGE_STATUS,{id:r.id,status:r.stageStatus})})}}ri=new WeakMap,Ji=new WeakMap,ni=new WeakMap,lc=new WeakMap,vn=new WeakMap,XM([y.trace("DyteStage.setupEvents")],Rg.prototype,"setupEvents",1);var ZM=Object.defineProperty,eD=Object.getOwnPropertyDescriptor,uc=(t,e,r,n)=>{for(var i=n>1?void 0:n?eD(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&ZM(e,r,i),i};const Ve={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 bt,Zt,Gs,qs,yn,zs,Ks,Gi,Ys,Ag;let qi=(Ag=class extends xi{constructor(t,{baseURL:e,createdAt:r,description:n,id:i,name:s,organizationId:a,picture:o,private:d,published:h,staggered:p,tags:m,type:g,updatedAt:v},I,A,P,D){super(),T(this,Gi),T(this,bt,void 0),f(this,"baseURL"),f(this,"createdAt"),f(this,"description"),f(this,"id"),f(this,"name"),T(this,Zt,void 0),T(this,Gs,void 0),T(this,qs,void 0),f(this,"organizationId"),f(this,"picture"),f(this,"private"),f(this,"published"),f(this,"staggered"),f(this,"tags"),f(this,"type"),f(this,"updatedAt"),T(this,yn,void 0),f(this,"config"),T(this,zs,void 0),f(this,"active"),f(this,"iframes"),f(this,"enabledBy"),T(this,Ks,void 0),S(this,Ks,t),this.baseURL=e,this.createdAt=new Date(r),this.description=n,this.id=i,this.name=s,S(this,Zt,A),this.organizationId=a,this.picture=o,this.private=d,this.published=h,this.staggered=p,this.tags=m,this.type=g,this.updatedAt=new Date(v),this.active=!1,this.iframes=new Map,S(this,bt,I),S(this,Gs,P),S(this,qs,D),this.enabledBy=""}sendIframeEvent(t){this.iframes.size&&this.iframes.forEach(e=>{const{iframe:r}=e;r&&(navigator.isReactNative?r.postMessage(JSON.stringify(t)):r.contentWindow.postMessage(t,"*"))})}handleIframeMessage(t){return u(this,null,function*(){var e;if(!this.active)return;const r=t,{payload:n,uuid:i,type:s}=r;switch(s){case z.customPluginEventToRoom:{c(this,bt).customPluginEventToRoom(this.id,n,i);break}case z.customPluginEventToPeers:{c(this,bt).customPluginEventToPeers(this.id,n.peerIds,n,i);break}case z.enablePluginForRoom:{c(this,bt).enablePluginForRoom(this.id,i);break}case z.enablePluginForPeers:{c(this,bt).enablePluginForPeers(this.id,n.peerIds,i);break}case z.disablePluginForRoom:{c(this,bt).disablePluginForRoom(this.id,i);break}case z.disablePluginForPeers:{c(this,bt).disablePluginForPeers(this.id,n.peerIds,i);break}case z.storeInsertKeys:{c(this,bt).storeInsertKeys(this.id,n.store,n.insertKeys,i);break}case z.storeGetKeys:{c(this,bt).storeGetKeys(this.id,n.store,n.getKeys,i);break}case z.storeDeleteKeys:{c(this,bt).storeDeleteKeys(this.id,n.store,n.deleteKeys,i);break}case z.storeDelete:{c(this,bt).storeDelete(this.id,n.store,i);break}case Ve.chatMessage:{const{messagePayload:a,peerIds:o}=n;if(!c(this,qs)){this.sendIframeEvent({type:Ve.chatMessage,uuid:r.uuid,payload:{error:"Chat is disabled for this room."}});return}try{yield c(this,qs).sendMessage(a,o),this.sendIframeEvent({type:Ve.chatMessage,uuid:r.uuid,payload:{success:!0}})}catch(d){this.sendIframeEvent({type:Ve.chatMessage,uuid:r.uuid,payload:{error:d}})}break}case Ve.getPeer:{let a;const{peerId:o}=n,d=X(U({},c(this,Zt)),{id:c(this,Zt).id,isRecorder:(e=c(this,Zt).permissions)==null?void 0:e.isRecorder,isHidden:c(this,Zt).permissions.hiddenParticipant,stageStatus:c(this,Zt).stageStatus});o?(a=c(this,Gs).joined.get(n.peerId),c(this,Zt).id===o&&(a=d)):a=d,this.sendIframeEvent({type:Ve.getPeer,payload:{peer:a&&tc(a)},uuid:r.uuid});break}case Ve.getPeers:{const a=c(this,Gs).joined.toArray().map(o=>tc(o));this.sendIframeEvent({type:Ve.getPeers,payload:{peers:a},uuid:r.uuid});break}case Ve.getPluginInitiator:{this.sendIframeEvent({type:Ve.getPluginInitiator,payload:{enabledBy:this.enabledBy},uuid:r.uuid});break}case Ve.getDisplayTitle:{this.sendIframeEvent({type:Ve.getDisplayTitle,payload:{displayTitle:c(this,Gi,Ys).meetingTitle},uuid:r.uuid});break}case Ve.getRoomName:{this.sendIframeEvent({type:Ve.getRoomName,payload:{roomName:c(this,Gi,Ys).roomName},uuid:r.uuid});break}case Ve.customPluginEventToParent:{this.emit(r.payload.eventName,r.payload.data);break}}})}sendData(t){this.active&&(l.info("DytePlugin::SendData",{plugin:{id:this.id,name:this.name,data:{eventName:t.eventName}}}),this.sendIframeEvent({type:Ve.sendData,uuid:"",payload:t}))}removePluginView(t="default"){var e;const{iframe:r,listener:n}=(e=this.iframes.get(t))!=null?e:{};(r||n)&&(navigator.isReactNative?r.props.onMessage=void 0:window.removeEventListener("message",n),this.iframes.delete(t))}addPluginView(t,e="default"){var r;if(!c(this,zs))throw l.error("DytePlugin::addPluginView::no_auth_token_set_for_plugin"),new _("No auth token set for plugin.","0602");if(!t)throw l.error("DytePlugin::addPluginView::iframe_was_not_provided"),new _("Iframe was not provided.","0603");this.removePluginView(e);const n=t,i=new URL(this.baseURL),s={auth:c(this,zs),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:c(this,Ks).getValue("apiBase"),pluginId:this.id,roomName:(r=c(this,Gi,Ys).roomName)!=null?r:"",displayTitle:c(this,Gi,Ys).meetingTitle};if(Object.keys(s).forEach(a=>{i.searchParams.set(a,s[a])}),n.src=i.href,n.allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",n.title=e,navigator.isReactNative)n.props.onMessage=a=>{this.handleIframeMessage(JSON.parse(a.nativeEvent.data))},this.iframes.set(e,{iframe:n});else{const a=o=>u(this,null,function*(){o.source===t.contentWindow&&(yield this.handleIframeMessage(o.data))});window.addEventListener("message",a),this.iframes.set(e,{iframe:n,listener:a})}}setActive(t){var e,r;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:(r=this.config)==null?void 0:r.views})}activateForSelf(){return u(this,null,function*(){const t=qe(),e=yield t.authorizePlugin(this.id);S(this,zs,e),S(this,yn,new Date);try{const r=yield t.getPluginConfig(this.baseURL);this.config=r}catch(r){l.error("DytePlugin::activateForSelf",{error:r})}this.setActive(!0),this.emit("enabled")})}deactivateForSelf(){Array.from(this.iframes.keys()).forEach(t=>{this.removePluginView(t)}),S(this,yn,void 0),this.iframes.clear(),this.setActive(!1),this.emit("closed")}enable(){return u(this,null,function*(){return this.activateForSelf()})}disable(){return this.deactivateForSelf()}activate(){return u(this,null,function*(){var t,e;this.active||(e=(t=c(this,Zt).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(c(this,bt).addPlugin(this.id,this.staggered),S(this,yn,new Date),l.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}}))})}deactivate(){return u(this,null,function*(){var t,e;this.active&&(!((e=(t=c(this,Zt).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==c(this,Zt).id||(c(this,bt).removePlugin(this.id),l.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:c(this,yn)?new Date().getTime()-c(this,yn).getTime():0}}),S(this,yn,void 0)))})}},bt=new WeakMap,Zt=new WeakMap,Gs=new WeakMap,qs=new WeakMap,yn=new WeakMap,zs=new WeakMap,Ks=new WeakMap,Gi=new WeakSet,Ys=function(){return c(this,Ks).getValue("roomNodeClient")},Ag);uc([xt({maxInvocations:5,period:1})],qi.prototype,"sendData",1),uc([y.trace("DytePlugin.activatePlugin")],qi.prototype,"activate",1),uc([y.trace("DytePlugin.deactivatePlugin")],qi.prototype,"deactivate",1),qi=uc([vt("0600")],qi);var Ye,zi;class Mg extends Map{constructor(e){const{onAddEvent:r,onDeleteEvent:n,onClearEvent:i}=e;super(),T(this,Ye,void 0),T(this,zi,void 0),f(this,"onAddEvent"),f(this,"onDeleteEvent"),f(this,"onClearEvent"),S(this,Ye,new xi),this.onAddEvent=r,this.onDeleteEvent=n,this.onClearEvent=i,S(this,zi,new Map)}emit(e,...r){return c(this,Ye).emit(e,...r)}on(e,r){return c(this,Ye).on(e,r)}addListener(e,r){return c(this,Ye).addListener(e,r)}off(e,r){return c(this,Ye).off(e,r)}once(e,r){return c(this,Ye).once(e,r)}prependListener(e,r){return c(this,Ye).prependListener(e,r)}prependOnceListener(e,r){return c(this,Ye).prependOnceListener(e,r)}removeListener(e,r){return c(this,Ye).removeListener(e,r)}removeAllListeners(e){return c(this,Ye).removeAllListeners(e)}listeners(e){return c(this,Ye).listeners(e)}listenerCount(e){return c(this,Ye).listenerCount(e)}getMaxListeners(){return c(this,Ye).getMaxListeners()}setMaxListeners(e){return c(this,Ye).setMaxListeners(e)}eventNames(){return c(this,Ye).eventNames()}add(e,r=!0){return this.set(e.id,e,r)}set(e,r,n=!0){const i=super.set(e,r),s=(a,...o)=>{this.emit(a,r,...o)};return c(this,zi).set(e,s),r.on("*",s),n&&c(this,Ye).emit(this.onAddEvent,r),i}delete(e,r=!0,n=!1){const i=this.get(e);if(!i)return!1;i.removeListener("*",c(this,zi).get(e));const s=super.delete(e);return n&&i.removeAllListeners(),r&&c(this,Ye).emit(this.onDeleteEvent,i),s}clear(e=!0,r=!1){this.forEach(i=>{i.removeListener("*",c(this,zi).get(i.id)),r&&i.removeAllListeners()});const n=super.clear();return e&&c(this,Ye).emit(this.onClearEvent),n}toArray(){return Array.from(this.values())}}Ye=new WeakMap,zi=new WeakMap;class Dg extends Mg{constructor(){super({onAddEvent:"pluginAdded",onDeleteEvent:"pluginDeleted"})}add(e,r=!0){return super.add(e,r)}delete(e,r=!0,n=!1){return super.delete(e,r,n)}}var tD=Object.defineProperty,rD=Object.getOwnPropertyDescriptor,nD=(t,e,r,n)=>{for(var i=n>1?void 0:n?rD(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&tD(e,r,i),i};let tu=class{constructor(){f(this,"all"),f(this,"active"),this.all=new Dg,this.active=new Dg}};tu=nD([vt("0600")],tu);var iD=Object.defineProperty,sD=Object.getOwnPropertyDescriptor,hc=(t,e,r,n)=>{for(var i=n>1?void 0:n?sD(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&iD(e,r,i),i},ur,Qs,pc,Og;const Ng=(Og=class{constructor(t,e,r,n){f(this,"plugins"),T(this,ur,void 0),T(this,Qs,void 0),T(this,pc,void 0),S(this,ur,e),S(this,Qs,r),S(this,pc,t),this.plugins=n,this.setupEvents()}static init(t,e,r,n,i,s,a){return u(this,null,function*(){const o=new tu;return e.forEach(d=>{const h=new qi(t,d,r,s,a,i);o.all.add(h)}),new Ng(t,r,n,o)})}getRoomPlugins(){return u(this,null,function*(){var t;const{plugins:e}=yield c(this,ur).getActivePlugins();(t=this.plugins.active)==null||t.toArray().forEach(r=>{this.disablePlugin({id:r.id})}),yield Promise.all(e.map(r=>this.enablePlugin({id:r.pluginId,enabledBy:r.enabledBy})))})}enablePlugin(t){return u(this,arguments,function*({id:e,enabledBy:r}){const n=this.plugins.all.get(e);n&&(yield n.activateForSelf(),n.enabledBy=r)})}disablePlugin(t){return u(this,arguments,function*({id:e}){const r=this.plugins.all.get(e);r&&r.deactivateForSelf()})}sendIframeEvent(t,e,r,n){const i=this.plugins.all.get(e);i&&i.sendIframeEvent({type:t,uuid:r,payload:n})}broadcastIframeEvent(t,e){this.plugins.active.forEach(r=>{this.sendIframeEvent(t,r.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)}),b.onAsync(w.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){yield this.getRoomPlugins(),l.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to fetch plugins.")})),c(this,ur).on(z.addPlugin,t=>u(this,null,function*(){var e;const r=t.pluginId;(e=this.plugins.all.get(r))!=null&&e.active||(yield this.enablePlugin({id:r,enabledBy:t.enabledBy}))})),c(this,ur).on(z.removePlugin,t=>u(this,null,function*(){var e;const r=t.pluginId;(e=this.plugins.all.get(r))!=null&&e.active&&(yield this.disablePlugin({id:r}))})),[z.enablePluginForPeers,z.enablePluginForRoom].forEach(t=>{c(this,ur).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{enabledBy:e.enabledBy})}))}),[z.disablePluginForPeers,z.disablePluginForRoom].forEach(t=>{c(this,ur).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{disabledBy:e.disabledBy})}))}),[z.customPluginEventToPeers,z.customPluginEventToRoom].forEach(t=>{c(this,ur).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{data:JSON.parse(new TextDecoder().decode(e.pluginData))})}))}),[z.storeInsertKeys,z.storeGetKeys,z.storeDeleteKeys].forEach(t=>{c(this,ur).on(t,(e,r)=>u(this,null,function*(){var n;const i=(n=e.storeItems)==null?void 0:n.map(s=>{var a;return{timestamp:s.timestamp,peerId:s.peerId,payload:JSON.parse((a=s.payload)!=null&&a.length?new TextDecoder().decode(s.payload):"{}"),key:s.storeKey}});this.sendIframeEvent(t,e.pluginId,r,{storeName:e.storeName,storeItems:i})}))}),c(this,ur).on(z.storeDelete,(t,e)=>u(this,null,function*(){this.sendIframeEvent(z.storeDelete,t.pluginId,e,{storeName:t.storeName})})),c(this,Qs).on(xe.sendMessageToPeers,t=>{const e=xr==null?void 0:xr.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(Ve.chatMessage,{message:e})}),c(this,Qs).on(xe.sendMessageToRoom,t=>{const e=xr==null?void 0:xr.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(Ve.chatMessage,{message:e})}),b.on(w.PEER_JOINED_INTERNAL,t=>{const e=tc(t);this.broadcastIframeEvent(Ve.peerJoined,e)}),b.on(w.PEER_CLOSED,t=>{this.broadcastIframeEvent(Ve.peerLeft,t)}),b.on(w.UPDATE_PEER_STAGE_STATUS,t=>{this.broadcastIframeEvent(Ve.peerStageStatusUpdate,t)}),c(this,pc).subscribe("stageStatus",t=>{this.broadcastIframeEvent(Ve.stageStatusUpdate,t)})}},ur=new WeakMap,Qs=new WeakMap,pc=new WeakMap,Og);let Xs=Ng;hc([y.trace("PluginController.getRoomPlugins")],Xs.prototype,"getRoomPlugins",1),hc([y.trace("PluginController.enableForSelf")],Xs.prototype,"enablePlugin",1),hc([y.trace("PluginController.disableForSelf")],Xs.prototype,"disablePlugin",1),hc([y.trace("PluginController.setupEvents")],Xs.prototype,"setupEvents",1);class aD{constructor(){f(this,"mediaJoined"),f(this,"socketJoined"),f(this,"socketJoinAttempted"),f(this,"mediaJoinAttempted"),f(this,"socketState"),f(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,r){let n;const{reconnected:i}=this.socketState;switch(e){case"connected":n={state:"connected",reconnected:i,reconnectionAttempt:void 0};break;case"disconnected":n={state:"disconnected",reconnected:!1,reconnectionAttempt:0},this.socketJoined=!1;break;case"reconnected":n={state:"connected",reconnected:!0,reconnectionAttempt:void 0};break;case"reconnecting":n={state:"reconnecting",reconnected:i,reconnectionAttempt:0};break;case"reconnectAttempt":n={state:"reconnecting",reconnected:i,reconnectionAttempt:r};break;case"failed":n={state:"failed",reconnected:i,reconnectionAttempt:void 0},this.socketJoined=!1;break}n&&(b.emit(w.SOCKET_STATE_UPDATE,n),this.socketState=n)}}var oD=Object.defineProperty,cD=Object.getOwnPropertyDescriptor,Zs=(t,e,r,n)=>{for(var i=n>1?void 0:n?cD(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&oD(e,r,i),i},ea,mc,ta,fc,Lg;let ii=(Lg=class extends jt{constructor(t,e){super(),T(this,ta),T(this,ea,void 0),T(this,mc,void 0),f(this,"recordingPeerIds",[]),f(this,"recordings",[]),S(this,mc,t),S(this,ea,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 u(this,null,function*(){if(!c(this,ea).permissions.canRecord)throw l.error("DyteRecording::start::permission_denied"),new _("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 l.error("DyteRecording::start::recording_in_progress",{recording:{state:this.recordingState}}),new _(`Cant start recording, recordingState irregular: ${this.recordingState}`,"1005");try{const e=qe(),{recording:r={}}=c(this,mc).getValue("defaults"),n=yield e.startRecording(r,t==null?void 0:t.allowMultiple);this.updateRecordings([...this.recordings,{id:n,state:"STARTING",type:"BROWSER"}])}catch(e){throw l.error("DyteRecording::stop::recording_failed_to_start",{error:e}),new _("Error while starting recording","1000")}})}stop(t){return u(this,null,function*(){yield Je(this,ta,fc).call(this,"stop",["RECORDING","PAUSED"],t)})}pause(t){return u(this,null,function*(){yield Je(this,ta,fc).call(this,"pause",["RECORDING"],t)})}resume(t){return u(this,null,function*(){yield Je(this,ta,fc).call(this,"resume",["PAUSED"],t)})}},ea=new WeakMap,mc=new WeakMap,ta=new WeakSet,fc=function(t,e,r){return u(this,null,function*(){if(!c(this,ea).permissions.canRecord)throw l.error("DyteRecording::stop::permission_denied"),new _("User does not have permission to stop recording","1001");let n=[];if(r!==void 0){const i=this.recordings.find(s=>s.id===r);if(i===void 0)throw new _("Could not find the specified recording","1004");if(e.includes(i.state)){l.error("DyteRecording::stop::recording_not_in_expected_state",{recording:{state:i.state}});return}n.push(i)}else n=this.recordings.filter(i=>e.includes(i.state));n.forEach(i=>u(this,null,function*(){const s=i.state;t==="stop"&&(i.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{yield qe().updateRecording(i.id,t)}catch(a){throw l.error("DyteRecording::stop::recording_failed_to_stop",{error:a}),i.state!==s&&(i.state=s,this.emit("recordingUpdate",s)),new _("Error while stopping recording","1000")}}))})},Lg);Zs([y.trace("DyteRecording.start")],ii.prototype,"start",1),Zs([y.trace("DyteRecording.stop")],ii.prototype,"stop",1),Zs([y.trace("DyteRecording.stop")],ii.prototype,"pause",1),Zs([y.trace("DyteRecording.stop")],ii.prototype,"resume",1),ii=Zs([vt("1000")],ii);var dD=Object.defineProperty,lD=Object.getOwnPropertyDescriptor,uD=(t,e,r,n)=>{for(var i=n>1?void 0:n?lD(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&dD(e,r,i),i},ru;class xg{constructor(e,r,n){f(this,"recording"),f(this,"room"),T(this,ru,void 0),S(this,ru,e),this.recording=new ii(e,r),this.room=n,this.setupEvents()}getRecordingTypeFromProtoType(e){let r;switch(e){case zn.BROWSER:r="BROWSER";break;case zn.COMPOSITE:r="COMPOSITE";break;case zn.TRACK:r="TRACK";break;default:r="BROWSER"}return r}setupEvents(){b.on(w.ROOM_STATE,e=>{e.activeRecordings.length!==0?this.recording.updateRecordings(e.activeRecordings.map(r=>{const n=this.getRecordingTypeFromProtoType(r.recordingType);return{id:r.recordingId,state:r.recordingStatus,type:n}})):this.recording.recordings.length&&this.recording.updateRecordings([])}),this.room.on(j.recordingStarted,e=>{let r=!1;const n=[...this.recording.recordings];if(n.forEach(i=>{i.id===e.recordingId&&(r=!0,i.state="RECORDING")}),r===!1){const i=this.getRecordingTypeFromProtoType(e.recordingType);n.push({id:e.recordingId,state:"RECORDING",type:i})}this.recording.updateRecordings(n)}),this.room.on(j.recordingPaused,e=>{const r=[...this.recording.recordings];r.forEach(n=>{n.id===e.recordingId&&(n.state="PAUSED")}),this.recording.updateRecordings(r)}),this.room.on(j.recordingStopped,e=>{const r=[...this.recording.recordings.filter(n=>n.id!==e.recordingId)];this.recording.updateRecordings(r)})}}ru=new WeakMap,uD([y.trace("RecordingController.setupEvents")],xg.prototype,"setupEvents",1);class hD{static hasFeature(e){var r;return(r=Q.hasFeature(e))!=null?r:!1}static getFeatureValue(e){return Q.getValue(e)}static getAllFeatures(){return Q.getAllFlags()}}class nu{constructor(e,r,n){f(this,"logger"),f(this,"features"),f(this,"browserSpecs"),f(this,"callStats"),this.logger=e,this.features=r,this.browserSpecs=Te,this.callStats=n}static init(e){return new nu(l,hD,e)}}class iu{constructor(e){f(this,"internals"),this.internals=e}static init(){return u(this,null,function*(){const e=nu.init($);return new iu(e)})}}var pD=Object.defineProperty,mD=Object.getOwnPropertyDescriptor,Wt=(t,e,r,n)=>{for(var i=n>1?void 0:n?mD(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&pD(e,r,i),i},st,at,Ue,Ur,hr,gc,su;class Ft extends xi{constructor(e,r,n=au,i=!0){super(),T(this,st,void 0),T(this,at,void 0),T(this,Ue,void 0),T(this,Ur,void 0),T(this,hr,void 0),T(this,gc,void 0),T(this,su,void 0),f(this,"audioUpdateInProgress"),f(this,"videoUpdateInProgress"),S(this,su,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,S(this,st,new jg(e,r)),S(this,at,new LD(c(this,st),void 0,n)),S(this,Ue,new HD(c(this,st),void 0,n)),S(this,hr,new UD(c(this,st))),S(this,Ur,new FD(c(this,st))),S(this,gc,i),c(this,at).on("trackMuted",this.onAudioTrackMuted.bind(this)),c(this,at).on("trackChanged",this.onAudioTrackChanged.bind(this)),c(this,Ue).on("trackChanged",this.onVideoTrackChanged.bind(this)),c(this,Ue).on("trackEnded",this.onVideoTrackEnded.bind(this)),c(this,hr).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}onVisibilityChange(){return u(this,null,function*(){$.tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?$.browserBackgrounded():($.browserForegrounded(),yield this.setupSpeaker())})}repopulateAvailableDevices(){return u(this,null,function*(){return!0})}setupStreams(e){return u(this,arguments,function*({audio:r,video:n}){var i;r?$.audioOn():$.audioOff(),n?$.videoOn():$.videoOff();let s,a;if(r&&n)try{const o=yield c(this,st).getAudioAndVideoTrack();s=o.audioTrack,a=o.videoTrack}catch(o){l.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:o})}if(!s&&r)try{s=yield c(this,st).getAudioTrack(!1)}catch(o){l.error("LocalMediaHandler::init::Failed to get audio track",{error:o})}if(!a&&n)try{a=yield c(this,st).getVideoTrack()}catch(o){l.error("LocalMediaHandler::init::Failed to get video track",{error:o})}r&&!s&&$.audioOff(),n&&!a&&$.videoOff(),yield c(this,at).setMediaTrack(s),yield c(this,Ue).setMediaTrack(a);try{yield c(this,Ur).setupSpeaker()}catch(o){}if(a){const o=yield this.getDeviceById(a.getSettings().deviceId);$.selectedDevice("VIDEO",o)}if(s){const o=yield this.getDeviceById(s.getSettings().deviceId);$.selectedDevice("AUDIO",o)}(i=c(this,Ur).currentDevice)!=null&&i.deviceId&&$.selectedDevice("SPEAKER",c(this,Ur).currentDevice),c(this,st).onDeviceChange((o,d,h)=>{this.onDeviceChange(d,h)})})}getCurrentDevices(){return{audio:c(this,at).currentDevice,video:c(this,Ue).currentDevice,speaker:c(this,Ur).currentDevice}}get permissions(){return c(this,st).permissions}getAllDevices(){return c(this,st).getAvailableDevices()}getDeviceById(e,r){return c(this,st).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return c(this,at).mediaTrack}get audioTrack(){return c(this,at).transformedMediaTrack}get audioEnabled(){return c(this,at).trackEnabled}enableAudio(){return u(this,null,function*(){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{yield c(this,at).unmuteTrack()}catch(e){}finally{this.audioUpdateInProgress=!1}}})}disableAudio(){c(this,at).muteTrack()}getAudioDevices(e){return c(this,st).getAudioInputDevices(e)}setAudioDevice(e){return u(this,null,function*(){yield c(this,at).setDevice(e),e!=null&&e.deviceId&&$.selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}setupSpeaker(){return c(this,Ur).setupSpeaker()}setSpeakerDevice(e){return u(this,null,function*(){yield c(this,Ur).setupSpeaker(e),e!=null&&e.deviceId&&$.selectedDevice("SPEAKER",e),this.emit("DEVICE_CHANGE",{device:e})})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return c(this,Ue).mediaTrack}get videoTrack(){return c(this,Ue).transformedMediaTrack}get videoEnabled(){return c(this,Ue).trackEnabled}enableVideo(){return u(this,null,function*(){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{yield c(this,Ue).unmuteTrack()}catch(e){}finally{this.videoUpdateInProgress=!1}}})}disableVideo(){c(this,Ue).disableTrack()}getVideoDevices(e){return c(this,st).getVideoInputDevices(e)}setVideoDevice(e){return u(this,null,function*(){yield c(this,Ue).setDevice(e),e!=null&&e.deviceId&&$.selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}updateVideoConstraints(e){return u(this,null,function*(){yield c(this,Ue).updateConstraints(e)})}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:c(this,hr).audioMediaTrack,video:c(this,hr).videoMediaTrack}}get screenShareEnabled(){return c(this,hr).trackEnabled}enableScreenShare(){return u(this,null,function*(){yield c(this,hr).enableScreenShare()})}disableScreenShare(){return u(this,null,function*(){c(this,hr).disableScreenShare()})}updateScreenshareConstraints(e){return u(this,null,function*(){yield c(this,hr).updateConstraints(e)})}getSpeakerDevices(e){return c(this,st).getAudioOutputDevices(e)}addAudioMiddleware(e){return c(this,at).addMiddleware(e)}removeAudioMiddleware(e){return c(this,at).removeMiddleware(e)}removeAllAudioMiddlewares(){return c(this,at).removeAllMiddlewares()}addVideoMiddleware(e){return c(this,Ue).addMiddleware(e)}removeVideoMiddleware(e){return c(this,Ue).removeMiddleware(e)}removeAllVideoMiddlewares(){return c(this,Ue).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return c(this,Ue).setVideoMiddlewareGlobalConfig(e)}destruct(){c(this,at).disableTrack(),c(this,Ue).disableTrack(),c(this,Ue).terminateMiddlewareWebWorker(),c(this,hr).disableScreenShare(),c(this,st).destruct()}onDeviceChange(e,r){return u(this,null,function*(){var n,i;this.emit("DEVICE_LIST_UPDATED",e),!(r||!c(this,gc))&&((n=e==null?void 0:e.added)==null||n.forEach(s=>u(this,null,function*(){var a;s&&!au(s)&&(s.kind==="audioinput"&&((a=this.audioTrack)==null?void 0:a.enabled)===!0?yield this.setAudioDevice(s):s.kind==="audiooutput"&&(yield this.setSpeakerDevice(s)))})),(i=e==null?void 0:e.removed)==null||i.forEach(s=>u(this,null,function*(){var a;if(s.kind==="audiooutput"&&((a=this.getCurrentDevices().speaker)==null?void 0:a.deviceId)===s.deviceId){const o=(yield this.getSpeakerDevices()).find(d=>d.deviceId!==s.deviceId);o&&(yield this.setSpeakerDevice(o))}})))})}removeAllTracks(){this.destruct()}removeAudioTrack(){c(this,at).disableTrack()}removeVideoTrack(){c(this,Ue).disableTrack(),c(this,Ue).terminateMiddlewareWebWorker()}removeDocumentEventListeners(){return u(this,null,function*(){document.removeEventListener("visibilitychange",this.onVisibilityChange)})}}st=new WeakMap,at=new WeakMap,Ue=new WeakMap,Ur=new WeakMap,hr=new WeakMap,gc=new WeakMap,su=new WeakMap,Wt([y.trace("MediaHandler.setupStreams")],Ft.prototype,"setupStreams",1),Wt([y.trace("MediaHandler.enableAudio")],Ft.prototype,"enableAudio",1),Wt([y.trace("MediaHandler.disableAudio")],Ft.prototype,"disableAudio",1),Wt([y.trace("MediaHandler.setAudioDevice")],Ft.prototype,"setAudioDevice",1),Wt([y.trace("MediaHandler.enableVideo")],Ft.prototype,"enableVideo",1),Wt([y.trace("MediaHandler.disableVideo")],Ft.prototype,"disableVideo",1),Wt([y.trace("MediaHandler.setVideoDevice")],Ft.prototype,"setVideoDevice",1),Wt([y.trace("MediaHandler.updateVideoConstraints")],Ft.prototype,"updateVideoConstraints",1),Wt([y.trace("MediaHandler.enableScreenShare")],Ft.prototype,"enableScreenShare",1),Wt([y.trace("MediaHandler.disableScreenShare")],Ft.prototype,"disableScreenShare",1),Wt([y.trace("MediaHandler.updateScreenshareConstraints")],Ft.prototype,"updateScreenshareConstraints",1),Wt([y.trace("MediaHandler.destruct")],Ft.prototype,"destruct",1),Wt([y.trace("MediaHandler.onDeviceChange")],Ft.prototype,"onDeviceChange",1);function vc(t,e,r){switch(!0){case Te.isChromiumBased():switch(e){case"NotAllowedError":return r.includes("by system")?"SYSTEM_DENIED":t==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case Te.isSafari():switch(e){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case Te.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 fD=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function au(t){var e,r;const n=(e=t.label)==null?void 0:e.toLowerCase();return((r=Te._bowser)==null?void 0:r.getOSName())==="macOS"&&n.includes("iphone")?(l.log("isVirtualDevice::ignore_macos_continuity"),!0):fD.some(i=>n==null?void 0:n.includes(i))}function gD(t,e){return u(this,null,function*(){if(!(t!=null&&t.length))return e;const r=new AudioContext,n=yield Promise.all(t==null?void 0:t.map(a=>a(r))),i=r.createMediaStreamSource(new MediaStream([e])),s=r.createMediaStreamDestination();try{let a=i;for(let o=0;o<n.length;o+=1)a.connect(n[o]),a=n[o];a.connect(s)}catch(a){return l.error("getTransformedAudioTrack::middleware_execution_failed",{error:a}),e}return s.stream.getAudioTracks()[0]})}var Ki;class vD{constructor(){T(this,Ki,void 0)}terminateMiddlewareWebWorker(){if(c(this,Ki))try{vh(c(this,Ki)),S(this,Ki,void 0)}catch(e){l.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}getTransformedVideoTrack(e,r,n){return u(this,null,function*(){if(!(e!=null&&e.length))return r;const i=document.createElement("canvas"),s=yield Promise.all(e==null?void 0:e.map(p=>p({canvas:i,WorkerTimers:Wy})));if(n.disablePerFrameCanvasRendering)return i.captureStream().getVideoTracks()[0];const a=document.createElement("video"),o=new MediaStream;o.addTrack(r);const d=i.getContext("2d");a.srcObject=o,a.autoplay=!0,this.terminateMiddlewareWebWorker();const h=()=>u(this,null,function*(){if(r.enabled===!1||r.readyState==="ended"){this.terminateMiddlewareWebWorker(),a.remove(),i.remove();return}try{d.drawImage(a,0,0);for(let p=0;p<s.length;p+=1)typeof s[p]=="function"&&(yield s[p](i,d))}catch(p){l.error("getTransformedVideoTrack::middleware_execution_failed",{error:p})}});try{a.play()}catch(p){}return a.addEventListener("play",()=>{i.width=a.width||r.getSettings().width,i.height=a.width||r.getSettings().height,S(this,Ki,yh(h,50))},!1),i.captureStream().getVideoTracks()[0]})}}Ki=new WeakMap;const Fg={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}}},Vg={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"}]},yD={320:[{rid:"q",maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"}],640:[{rid:"h",maxBitrate:7e5,maxFramerate:30,scalabilityMode:"L1T1"}],1280:[{rid:"h",maxBitrate:14e5,maxFramerate:30,scalabilityMode:"L1T1"}]},Ug={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"}]};var ne=(t=>(t.WEBCAM="webcam",t.MIC="mic",t.SCREENSHARE_VIDEO="screenshare_video",t.SCREENSHARE_AUDIO="screenshare_audio",t))(ne||{});const SD=x_(),Yi=dr(SD.config.media);function ED(t){var e,r;const n={};return t.audio&&(n.audio={enableStereo:(e=t.audio.enableStereo)!=null?e:!1,enableHighBitrate:(r=t.audio.enableHighBitrate)!=null?r:!1}),n.video=t.video.quality,n}var Qi,ou;class TD{constructor(e,r){T(this,Qi,void 0),T(this,ou,void 0),f(this,"getScreenShareConstraints",()=>{var n,i,s,a,o,d,h,p,m;const g=(n=c(this,Qi))==null?void 0:n.screenshare,v=(s=(i=g==null?void 0:g.width)==null?void 0:i.max)!=null?s:1920,I=(o=(a=g==null?void 0:g.height)==null?void 0:a.max)!=null?o:1080,A=(h=(d=g==null?void 0:g.frameRate)==null?void 0:d.max)!=null?h:5;let P=(m=(p=g==null?void 0:g.frameRate)==null?void 0:p.ideal)!=null?m:5;const D=g==null?void 0:g.displaySurface,N=g==null?void 0:g.selfBrowserSurface;Q.getValue(ie.VAL_MIN_FRAMERATE)&&(P=parseInt(Q.getValue(ie.VAL_MIN_FRAMERATE),10));let J={width:{max:v},height:{max:I},frameRate:{ideal:P,max:A}};if(Q.hasFeature(ie.SCREENSHARE_CONSTRAINTS)){const C=Q.getValue(ie.SCREENSHARE_CONSTRAINTS);J=JSON.parse(C)}return D!==void 0&&["monitor","browser","window"].includes(D)&&(J=X(U({},J),{displaySurface:D})),N!==void 0&&(J=X(U({},J),{selfBrowserSurface:N})),{audio:!0,video:J}}),f(this,"getAudioConstraints",n=>{var i,s,a,o,d,h,p,m;const g={},v=(i=c(this,Qi))==null?void 0:i.audio,I=v!=null&&v.enableStereo?2:1;return Te.isFirefox()||Te.isWebKitBased()?(g.audio={deviceId:n,autoGainControl:(s=v==null?void 0:v.autoGainControl)!=null?s:!0,echoCancellation:(a=v==null?void 0:v.echoCancellation)!=null?a:!0,noiseSuppression:(o=v==null?void 0:v.noiseSupression)!=null?o:!0,channelCount:I},g):(g.audio={},g.audio.optional=[n?{sourceId:n}:{sourceId:"default"},{channelCount:I},{echoCancellation:(d=v==null?void 0:v.echoCancellation)!=null?d:!0},{googEchoCancellation:(h=v==null?void 0:v.echoCancellation)!=null?h:!0},{googAutoGainControl:(p=v==null?void 0:v.autoGainControl)!=null?p:!0},{googNoiseSuppression:(m=v==null?void 0:v.noiseSupression)!=null?m:!0},{googHighpassFilter:!0}],g)}),f(this,"getVideoConstraints",n=>{var i,s,a;const o={},d=(i=c(this,Qi))==null?void 0:i.video;let h=Fg.vga;if(typeof d=="string"?h=Fg[d]:d!==void 0&&(h.height.ideal=d.height.ideal,h.width.ideal=d.width.ideal),h.frameRate={ideal:(a=(s=h.frameRate)==null?void 0:s.ideal)!=null?a:24},Te.isChromiumBased()&&(h.frameRate.max=30),Q.hasFeature(ie.VIDEO_CONSTRAINTS)){const p=Q.getValue(ie.VIDEO_CONSTRAINTS);h=JSON.parse(p)}return o.video=h,typeof o.video=="boolean"||(n?o.video.deviceId={exact:n}:o.video.facingMode="user"),o}),S(this,ou,e),S(this,Qi,r)}getUpdatedVideoConstraints(e){return e}}Qi=new WeakMap,ou=new WeakMap;class cu extends Error{constructor(e,r,n){super(r),f(this,"constraints"),f(this,"name"),this.name=e,this.constraints=n}}class kD{constructor(){f(this,"permissions"),this.permissions={audio:"NOT_REQUESTED",video:"NOT_REQUESTED",screenshare:"NOT_REQUESTED"}}getAudioInputDevices(e){return u(this,null,function*(){let r=e;return e||(r=yield this.getAvailableDevices()),r.filter(n=>n.kind==="audioinput")})}getVideoInputDevices(e){return u(this,null,function*(){let r=e;return e||(r=yield this.getAvailableDevices()),r.filter(n=>n.kind==="videoinput")})}getAudioOutputDevices(e){return u(this,null,function*(){let r=e;return e||(r=yield this.getAvailableDevices()),r.filter(n=>n.kind==="audiooutput")})}}var _D=Object.defineProperty,bD=Object.getOwnPropertyDescriptor,pr=(t,e,r,n)=>{for(var i=n>1?void 0:n?bD(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&_D(e,r,i),i},ra,mr,du,Bg;let $t=(Bg=class extends kD{constructor(t,e){super(),f(this,"availableDevices"),T(this,ra,void 0),T(this,mr,void 0),T(this,du,void 0),S(this,du,t),S(this,mr,new TD(t,e)),S(this,ra,new AbortController),this.availableDevices=[],this.getAvailableDevices()}get constraintsBuilder(){return c(this,mr)}destruct(){return u(this,null,function*(){var t;(t=c(this,ra))==null||t.abort()})}handlePermissionErrors(t,e){const r=vc(t,e.name,e.message);return this.permissions[t]=r,b.emit(w.MEDIA_PERMISSION_ERROR,{message:r,constraints:e.constraints,kind:t}),r}getAudioAndVideoTrack(){return u(this,null,function*(){const t={audio:c(this,mr).getAudioConstraints().audio,video:c(this,mr).getVideoConstraints().video};try{l.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(t)});const e=yield navigator.mediaDevices.getUserMedia(t);l.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(t)});const r=e.getAudioTracks()[0];let n=e.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",Q.hasFeature(ie.OBS_QUALITY)&&n.label.includes("OBS Virtual")){const i=(yield this.getVideoInputDevices()).find(s=>s.label.includes("OBS Virtual"));n=yield this.getVideoTrack(i.deviceId)}return b.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),b.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:r,videoTrack:n}}catch(e){throw l.error("WebMediaInterface.getAudioAndVideoTrack",{error:e}),new _("Couldnt fetch audio and video track","1605")}})}getAudioTrack(t,e){return u(this,null,function*(){let r=yield this.getAudioInputDevices();if(r.length===0)throw this.permissions.audio="NO_DEVICES_AVAILABLE",b.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new _("No audio devices available","1606");const n=i=>u(this,null,function*(){let s;try{r=r.filter(o=>o.deviceId!==i),s=c(this,mr).getAudioConstraints(i),l.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(s)});const[a]=(yield navigator.mediaDevices.getUserMedia(s)).getAudioTracks();return l.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(s)}),a}catch(a){const o=vc("audio",a.name,a.message),d=new cu(a.name,a.message,s);if(o==="COULD_NOT_START"){const h=r.shift();if(!h)throw d;l.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(s),error:a});const p=c(this,mr).getAudioConstraints(h.deviceId);return l.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(p)}),n(h.deviceId)}throw d}});try{const i=yield n(e);return i.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",b.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),i}catch(i){throw i.constraints&&this.handlePermissionErrors("audio",i),new _(i.message,"1601")}})}getVideoTrack(t){return u(this,null,function*(){var e;const r=Q.hasFeature(ie.OBS_QUALITY),n=(e=yield this.getCurrentDeviceLabel(t))==null?void 0:e.includes("OBS Virtual"),i=r&&n,s=yield this.getVideoInputDevices();if(s.length===0)throw this.permissions.video="NO_DEVICES_AVAILABLE",b.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new _("No video devices available","1607");const a=o=>u(this,null,function*(){try{let d=o;const{video:h}=d;i&&typeof h!="boolean"&&(d={video:{deviceId:h.deviceId}}),l.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(d)});const[p]=(yield navigator.mediaDevices.getUserMedia(d)).getVideoTracks();if(i&&typeof h!="boolean"&&typeof h.width=="object"){const{width:m,height:g}=p.getSettings(),{ideal:v}=h.width;p.applyConstraints({width:{ideal:v},height:{ideal:Math.floor(g*v/m)},frameRate:h.frameRate})}return l.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(d)}),p}catch(d){const h=vc("video",d.name,d.message),p=new cu(d.name,d.message,o);if(h==="COULD_NOT_START"){const m=s.shift();if(!m)throw p;l.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(o),error:d});const g=c(this,mr).getVideoConstraints(m.deviceId);return l.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(g)}),a({video:g.video})}throw p}});try{const o=c(this,mr).getVideoConstraints(t),d=yield a(o);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",b.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),d}catch(o){throw o.constraints&&this.handlePermissionErrors("video",o),new _(o.message,"1602")}})}getScreenShareTracks(){return u(this,null,function*(){const t=e=>u(this,null,function*(){try{l.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),$.screenShareRequested();const r=yield navigator.mediaDevices.getDisplayMedia(e);return l.info("getDisplayMediaWithoutTimeout::received_display_media",{constraints:JSON.stringify(e)}),r}catch(r){const n=vc("video",r.name,r.message),i=new cu(r.name,r.message,e),s={video:!0};if(rw(e,s)||!Q.hasFeature(ie.SCREEENSHARE_CONSTRAINTS_RETRY))throw i;if(n==="COULD_NOT_START")return t(s);throw i}});try{const e=c(this,mr).getScreenShareConstraints(),r=yield t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",b.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.screenshare,kind:"screenshare"})),{audioTrack:r.getAudioTracks()[0],videoTrack:r.getVideoTracks()[0]}}catch(e){throw e.constraints&&this.handlePermissionErrors("screenshare",e),new _(e.message,"1612")}})}getCurrentDeviceLabel(t){return u(this,null,function*(){const e=yield this.getDevice(t||"default");return e==null?void 0:e.label})}getAvailableDevices(){return u(this,null,function*(){try{const t=yield navigator.mediaDevices.enumerateDevices();return this.availableDevices=t,t}catch(t){throw l.error("enumerate_devices_failed",{error:t}),new _("Failed to get available devices","1609")}})}getAvailableDevicesByKind(t){return u(this,null,function*(){try{return(yield navigator.mediaDevices.enumerateDevices()).filter(({kind:e})=>t===e)}catch(e){throw l.error("enumerate_devices_failed",{error:e}),new _("Failed to get available devices by kind","1609")}})}getDevice(t){return u(this,null,function*(){try{return(yield navigator.mediaDevices.enumerateDevices()).filter(e=>e.deviceId===t)[0]}catch(e){throw l.error("enumerate_devices_failed",{error:e}),new _("Failed to get device","1609")}})}onDeviceChange(t){return u(this,null,function*(){Te.supportsDeviceChangeEvent()&&navigator.mediaDevices.addEventListener("devicechange",e=>u(this,null,function*(){var r,n;const i=p=>`${p.kind}-${p.deviceId}-${p.groupId}`,s=this.availableDevices,a=new Set(s.map(p=>i(p))),o=yield this.getAvailableDevices(),d=new Set(o.map(p=>i(p))),h={added:o.filter(p=>!a.has(i(p))),removed:s.filter(p=>!d.has(i(p))),devices:o};if((r=h.added)!=null&&r.length||(n=h.removed)!=null&&n.length){l.info("repopulated_full_device_list",{devices:JSON.stringify(o)});const p=[...h.added,...h.removed];p.some(m=>m.kind==="audioinput")&&$.devices("AUDIO",o==null?void 0:o.filter(m=>m.kind==="audioinput")),p.some(m=>m.kind==="videoinput")&&$.devices("VIDEO",o==null?void 0:o.filter(m=>m.kind==="videoinput")),p.some(m=>m.kind==="audiooutput")&&$.devices("SPEAKER",o==null?void 0:o.filter(m=>m.kind==="audiooutput")),t(e,h,!1)}}),{signal:c(this,ra).signal})})}},ra=new WeakMap,mr=new WeakMap,du=new WeakMap,Bg);pr([y.trace("WebMediaInterface.destruct")],$t.prototype,"destruct",1),pr([y.trace("WebMediaInterface.handlePermissionErrors")],$t.prototype,"handlePermissionErrors",1),pr([y.trace("WebMediaInterface.getAudioAndVideoTrack")],$t.prototype,"getAudioAndVideoTrack",1),pr([y.trace("WebMediaInterface.getAudioTrack")],$t.prototype,"getAudioTrack",1),pr([y.trace("WebMediaInterface.getVideoTrack")],$t.prototype,"getVideoTrack",1),pr([y.trace("WebMediaInterface.getScreenShareTracks")],$t.prototype,"getScreenShareTracks",1),pr([y.trace("WebMediaInterface.getAvailableDevices")],$t.prototype,"getAvailableDevices",1),pr([y.trace("WebMediaInterface.getAvailableDevicesByKind")],$t.prototype,"getAvailableDevicesByKind",1),pr([y.trace("WebMediaInterface.getDevice")],$t.prototype,"getDevice",1),pr([y.trace("WebMediaInterface.onDeviceChange")],$t.prototype,"onDeviceChange",1),$t=pr([vt("1600")],$t);const jg=$t,lu={setItem:(t,e)=>{try{localStorage.setItem(t,e)}catch(r){l.error("LocalStorage::setItem::crashed",{error:r,localStorage:{key:t,value:e}})}},getItem:t=>{try{return localStorage.getItem(t)}catch(e){l.error("LocalStorage::getItem::crashed",{error:e,localStorage:{key:t}})}return null}},wD=(t=0)=>new Promise(e=>setTimeout(e,t)),ID=(t,e,r)=>{const n=typeof r=="number"?r:250,i=t.createMediaStreamSource(e),s=t.createAnalyser();s.fftSize=2048,i.connect(s);const a=new Uint8Array(s.fftSize);let o=!1;setTimeout(()=>{o=!0},n);function d(){return o?Promise.resolve(!0):(s.getByteTimeDomainData(a),a.some(h=>h!==128&&h!==0)?Promise.resolve(!1):wD().then(d))}return d().then(h=>(i.disconnect(),h),h=>{throw i.disconnect(),h})},CD=typeof AudioContext!="undefined"?AudioContext:null;class uu{constructor(e){f(this,"_AudioContext"),f(this,"audioContext"),f(this,"_audioContextRefContainers");const r=U({AudioContext:CD},e);Object.defineProperties(this,{_AudioContext:{value:r.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:uu}})}getOrCreate(e){if(!this._audioContextRefContainers.has(e)&&(this._audioContextRefContainers.add(e),this._AudioContext&&!this.audioContext))try{this.audioContext=new this._AudioContext}catch(r){}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 Hg=new uu,PD=3,RD=250;function AD(t){const e={},r=Hg.getOrCreate(e);let n=PD;function i(){return n-=1,ID(r,t.srcObject,RD).then(s=>s?n>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{Hg.release(e)})}function Wg(t){return u(this,null,function*(){const e=new Audio,r=new MediaStream;r.addTrack(t),e.srcObject=r;let n=!1;try{const i=e.play();i&&(yield i),n=yield AD(e),n&&l.info("checkIfAudioTrackIsSilent::silence_detected")}catch(i){l.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:i})}finally{e.pause(),e.remove()}return n})}var MD=Object.defineProperty,DD=Object.getOwnPropertyDescriptor,$g=(t,e,r,n)=>{for(var i=n>1?void 0:n?DD(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&MD(e,r,i),i};let yc=class extends xi{constructor(t,e,r){super(),f(this,"constructorName",this.constructor.name),f(this,"userSelectedDevice"),f(this,"mediaInterface"),f(this,"isNonPreferredDevice"),f(this,"_mediaTrack"),f(this,"transformedMediaTrack"),f(this,"middlewares",[]),f(this,"currentDevice"),this.mediaInterface=t,e&&this.setMediaTrack(e),this.userSelectedDevice=void 0,this.isNonPreferredDevice=r,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 u(this,null,function*(){const e=r=>{l.error(`${this.constructorName}.setMediaTrack.error`,{error:r})};try{this.disableTrack()}catch(r){e(r)}this._mediaTrack=yield this.conditionallyChangeTrack(t),yield this.setTransformedTrack();try{this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(r){e(r)}})}get trackEnabled(){return!!this.mediaTrack&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}muteTrack(){if(!this.mediaTrack){l.warn("BaseMediaHandler.muteTrack Tried muting with no track present");return}this.transformedMediaTrack&&(this.transformedMediaTrack.enabled=!1),this.mediaTrack.enabled=!1}unmuteTrack(){return u(this,null,function*(){try{this.mediaTrack?this.mediaTrack.enabled=!0:yield this.enableTrack(!1)}catch(t){throw l.error(`${this.constructorName}.unmuteTrack.error`,{error:t}),this.disableTrack(),new _("Failed to unmute track","1611")}})}getCurrentDeviceId(){var t,e;const{kind:r}=this.mediaTrack;switch(r){case"audio":{const n=this.mediaTrack.getConstraints();return this.userSelectedDevice?(e=(t=n==null?void 0:n.deviceId)!=null?t:n==null?void 0:n.advanced[0].deviceId)!=null?e:this.mediaTrack.getSettings().deviceId:this.mediaTrack.getSettings().deviceId}default:return this.mediaTrack.getSettings().deviceId}}setCurrentDevice(){return u(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))})}addMiddleware(t){return u(this,null,function*(){if(Te.isWebKitBased()&&!Q.hasFeature(ie.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 l.error("While adding middleware",{error:e}),this.removeMiddleware(t),{success:!1,message:e==null?void 0:e.message}}})}removeMiddleware(t){return u(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(r){return l.error("While removing middleware",{error:r}),{success:!1,message:r==null?void 0:r.message}}return{success:!1,message:"No such middleware was found. Skipping."}})}removeAllMiddlewares(){return u(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 l.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,r;this.mediaTrack&&(l.info(`${this.constructorName}.addMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),this.mediaTrack.addEventListener("ended",this.onTrackEnded),this.mediaTrack.addEventListener("mute",this.onTrackMuted))}removeMediaTrackListeners(){var t,e,r;this.mediaTrack&&(l.info(`${this.constructorName}.removeMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),l.info(`${this.constructorName}.removeMediaTrackListeners`),this.mediaTrack.removeEventListener("ended",this.onTrackEnded),this.mediaTrack.removeEventListener("mute",this.onTrackMuted))}};$g([y.trace("BaseMediaHandler.unmuteTrack")],yc.prototype,"unmuteTrack",1),yc=$g([vt("1600")],yc);const Jg=yc;var OD=Object.defineProperty,ND=Object.getOwnPropertyDescriptor,hu=(t,e,r,n)=>{for(var i=n>1?void 0:n?ND(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&OD(e,r,i),i};const pu="[Dyte]nonSilentDeviceLabels";class Sc extends Jg{setDevice(e){return u(this,null,function*(){if(!e)throw l.warn("AudioMediaHandler.setDevice No device received"),new _("No device received!","1603");if(e.kind!=="audioinput")throw l.warn("AudioMediaHandler.setDevice Received non audio device"),new _("Non audio device received while setting device!","1603");try{const r=this.trackEnabled;this.userSelectedDevice=e.deviceId,yield this.setMediaTrack(yield this.mediaInterface.getAudioTrack(!r,this.userSelectedDevice)),this.userSelectedDevice=void 0}catch(r){throw l.error("AudioMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new _(r.message,"1604")}})}enableTrack(e){return u(this,null,function*(){if(this.trackEnabled){l.warn("AudioMediaHandler.enableTrack Track already enabled!");return}const r=yield this.mediaInterface.getAudioTrack(e,this.userSelectedDevice);yield this.setMediaTrack(r)})}setTransformedTrack(e){return u(this,null,function*(){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=yield gD(this.middlewares,this.mediaTrack),this.emit("trackChanged")}catch(n){l.error("AudioMediaHandler.setTransformedTrack",{error:n}),this.transformedMediaTrack=this.mediaTrack}})}onTrackEnded(){return u(this,null,function*(){l.info("AudioMediaHandler.TrackEnded"),this.emit("trackEnded");const e=this.mediaTrack.enabled;this.disableTrack(),yield this.enableTrack(!e),yield this.setTransformedTrack(),this.emit("trackChanged")})}onTrackMuted(){l.info("AudioMediaHandler.TrackMuted"),this.emit("trackMuted")}conditionallyChangeTrack(e){return u(this,null,function*(){var r;if(!e||this.userSelectedDevice)return e;let n=e;const i=yield this.mediaInterface.getAudioInputDevices(),s=this.isNonPreferredDevice?i.filter(d=>d&&!this.isNonPreferredDevice(d)):i;if(!(s!=null&&s.length))return n;s.find(d=>d.deviceId===e.getSettings().deviceId)||(n.stop(),l.info("localmediahandler::setupstreams::found_audio_non_preferred"),n=yield this.mediaInterface.getAudioTrack(!1,s[0].deviceId));const a=JSON.parse(lu.getItem(pu));if(a!=null&&a.devices.some(d=>d.label===n.label))return n;if(!(yield Wg(n))){const d=(r=a==null?void 0:a.devices.concat({label:n.label}))!=null?r:[{label:n.label}];return lu.setItem(pu,JSON.stringify({devices:d})),n}l.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const o=n.getSettings().deviceId;return s.filter(d=>d.deviceId!==o).some(d=>u(this,null,function*(){if(n=yield this.mediaInterface.getAudioTrack(!1,d.deviceId),!(yield Wg(n))){const h=a.devices.concat({label:n.label});return lu.setItem(pu,JSON.stringify({devices:h})),l.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return l.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1})),n})}}hu([y.trace("AudioMediaHandler.setTransformedTrack")],Sc.prototype,"setTransformedTrack",1),hu([y.trace("AudioMediaHandler.onTrackEnded")],Sc.prototype,"onTrackEnded",1),hu([y.trace("AudioMediaHandler.conditionallyChangeTrack")],Sc.prototype,"conditionallyChangeTrack",1);const LD=Sc;var na;class xD{constructor(e){T(this,na,void 0),f(this,"currentDevice"),S(this,na,e)}setupSpeaker(e){return u(this,null,function*(){var r;if(!(c(this,na)instanceof jg))return;let n=e;if(e||([n]=(yield c(this,na).getAvailableDevicesByKind("audiooutput")).filter(i=>!au(i))),!n)throw new _("No speaker found","1608");((r=this.currentDevice)==null?void 0:r.deviceId)!==n.deviceId&&(this.currentDevice=n,document.querySelectorAll("audio").forEach(i=>u(this,null,function*(){if(typeof i.sinkId!="undefined"&&this.currentDevice.deviceId&&i.sinkId!==this.currentDevice.deviceId)try{yield i.setSinkId(this.currentDevice.deviceId)}catch(s){}})))})}}na=new WeakMap;const FD=xD;class VD extends xi{constructor(e){super(),f(this,"mediaInterface"),f(this,"audioMediaTrack"),f(this,"videoMediaTrack"),this.mediaInterface=e}get trackEnabled(){return!!this.videoMediaTrack}enableScreenShare(){return u(this,null,function*(){var e,r;try{const{audioTrack:n,videoTrack:i}=yield this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=n,this.videoMediaTrack=i,this.addMediaTrackListeners(),((r=(e=this.mediaInterface)==null?void 0:e.permissions)==null?void 0:r.screenshare)==="ACCEPTED")return;this.mediaInterface.permissions&&(this.mediaInterface.permissions.screenshare="ACCEPTED",b.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch(n){}})}disableScreenShare(){var e,r;this.removeMediaTrackListeners(),(e=this.audioMediaTrack)==null||e.stop(),(r=this.videoMediaTrack)==null||r.stop(),this.videoMediaTrack=void 0,this.audioMediaTrack=void 0}updateConstraints(e){return u(this,null,function*(){if(!this.videoMediaTrack)throw new _("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new _("update constraints not supported for non web clients","1100");try{this.videoMediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),this.addMediaTrackListeners()}catch(n){l.error("ScreenShareHandler.updateConstraints.error",{error:n})}})}addMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.addEventListener("ended",this.onTrackEnded.bind(this)),Te.isWebKitBased()&&((r=this.videoMediaTrack)==null||r.addEventListener("mute",this.onTrackEnded.bind(this)))}removeMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded),(r=this.videoMediaTrack)==null||r.removeEventListener("mute",this.onTrackEnded)}onTrackEnded(){this.emit("trackEnded")}}const UD=VD;var BD=Object.defineProperty,jD=Object.getOwnPropertyDescriptor,Ec=(t,e,r,n)=>{for(var i=n>1?void 0:n?jD(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&BD(e,r,i),i},ia,Tc;class sa extends Jg{constructor(e,r,n){super(e,r,n),T(this,ia,void 0),T(this,Tc,{disablePerFrameCanvasRendering:!1}),S(this,ia,new vD)}setDevice(e){return u(this,null,function*(){if(!e)throw l.warn("VideoMediaHandler.setDevice No device received"),new _("No device received!","1603");if(e.kind!=="videoinput")throw l.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new _("Non video device received while setting video device!","1603");if(this.userSelectedDevice=e.deviceId,!(this.mediaTrack&&this.mediaTrack.enabled)){l.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(r){throw l.error("VideoMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new _("Failed to change device","1600")}})}enableTrack(){return u(this,null,function*(){if(this.trackEnabled){l.warn("VideoMediaHandler.enableTrack Track already enabled!");return}yield this.setMediaTrack(yield this.mediaInterface.getVideoTrack(this.userSelectedDevice))})}setTransformedTrack(e){return u(this,null,function*(){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=yield c(this,ia).getTransformedVideoTrack(this.middlewares,this.mediaTrack,c(this,Tc)),this.emit("trackChanged")}catch(n){l.error("VideoMediaHandler.setTransformedTrack",{error:n}),this.transformedMediaTrack=this.mediaTrack}})}setVideoMiddlewareGlobalConfig(e){return u(this,null,function*(){S(this,Tc,e)})}updateConstraints(e){return u(this,null,function*(){if(!this._mediaTrack)throw new _("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new _("update constraints not supported for non web clients","1100");try{this._mediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),yield this.setTransformedTrack(),this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(n){l.error("VideoMediaHandler.updateConstraints.error",{error:n})}})}terminateMiddlewareWebWorker(){c(this,ia).terminateMiddlewareWebWorker()}onTrackEnded(){return u(this,null,function*(){l.info("VideoMediaHandler.TrackEnded"),this.disableTrack(),this.emit("trackEnded")})}onTrackMuted(){l.info("VideoMediaHandler.TrackMuted"),this.emit("trackMuted")}conditionallyChangeTrack(e){return u(this,null,function*(){if(!e||this.userSelectedDevice)return e;let r=e;const n=yield this.mediaInterface.getVideoInputDevices(),i=this.isNonPreferredDevice?n.filter(s=>!this.isNonPreferredDevice(s)):n;return!(i!=null&&i.length)||window.FAST_DYTE||i.find(s=>s.deviceId===e.getSettings().deviceId)||(r.stop(),l.info("localmediahandler::setupstreams::found_video_non_preferred"),r=yield this.mediaInterface.getVideoTrack(i[0].deviceId)),r})}}ia=new WeakMap,Tc=new WeakMap,Ec([y.trace("VideoMediaHandler.setTransformedTrack")],sa.prototype,"setTransformedTrack",1),Ec([y.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],sa.prototype,"setVideoMiddlewareGlobalConfig",1),Ec([y.trace("VideoMediaHandler.onTrackEnded")],sa.prototype,"onTrackEnded",1),Ec([y.trace("VideoMediaHandler.conditionallyChangeTrack")],sa.prototype,"conditionallyChangeTrack",1);const HD=sa,Gg=dr(gl());var Jt,Xi,kc,aa;const oa=class{constructor(t){if(T(this,Jt,void 0),T(this,Xi,void 0),T(this,kc,void 0),T(this,aa,void 0),!t)throw new _("Could not load preset.","0904");S(this,Jt,t.config),S(this,kc,t.name),S(this,Xi,t.ui||dr(gl().ui)),S(this,aa,t.permissions.plugins.config)}static fromResponse(t){return new oa(t)}static default(){return new oa(Gg)}static init(t,e=!0){return!t||e?new oa(Gg):new oa(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:c(this,Xi).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return c(this,Jt).viewType}get livestreamViewerQualities(){return c(this,Jt).livestreamViewerQualities||[]}get maxVideoStreams(){return c(this,Jt).maxVideoStreams}get maxScreenShareCount(){return c(this,Jt).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(c(this,aa)).filter(t=>c(this,aa)[t].disabled)}get designTokens(){return c(this,Xi).designTokens}get configDiff(){return c(this,Xi).configDiff}get mediaConstraints(){var t,e,r,n,i,s,a,o,d,h,p,m,g,v,I,A,P,D,N,J,C,G,W,de;return{audio:{enableStereo:(n=(r=(e=(t=c(this,Jt))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?n:Yi.audio.enableStereo,enableHighBitrate:(o=(a=(s=(i=c(this,Jt))==null?void 0:i.media)==null?void 0:s.audio)==null?void 0:a.enableHighBitrate)!=null?o:Yi.audio.enableHighBitrate},video:{quality:(m=(p=(h=(d=c(this,Jt))==null?void 0:d.media)==null?void 0:h.video)==null?void 0:p.quality)!=null?m:Yi.video.quality,frameRate:(A=(I=(v=(g=c(this,Jt))==null?void 0:g.media)==null?void 0:v.video)==null?void 0:I.frameRate)!=null?A:Yi.video.frameRate},screenshare:{quality:(J=(N=(D=(P=c(this,Jt))==null?void 0:P.media)==null?void 0:D.screenshare)==null?void 0:N.quality)!=null?J:Yi.screenshare.quality,frameRate:(de=(W=(G=(C=c(this,Jt))==null?void 0:C.media)==null?void 0:G.screenshare)==null?void 0:W.frameRate)!=null?de:Yi.screenshare.frameRate}}}get name(){return c(this,kc)}};let WD=oa;Jt=new WeakMap,Xi=new WeakMap,kc=new WeakMap,aa=new WeakMap;var $D=Object.defineProperty,JD=Object.getOwnPropertyDescriptor,qg=(t,e,r,n)=>{for(var i=n>1?void 0:n?JD(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&$D(e,r,i),i},ca;class mu extends jt{constructor(e){super(),T(this,ca,void 0),f(this,"state","IDLE"),f(this,"playbackUrl"),f(this,"ingestionCredentials"),f(this,"viewerCount"),S(this,ca,e),this.viewerCount=0}setLivestreamState(e){const r=this.state;this.state=e,r!==e&&this.emitCurrentLivestreamState()}emitCurrentLivestreamState(){this.emit("livestreamUpdate",this.state)}start(){return u(this,arguments,function*(e={manualIngestion:!1}){if(!c(this,ca).permissions.canLivestream)throw l.error("DyteLivestream::start::permission_denied"),new _("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const r=qe(),{playbackUrl:n,ingestionCredentials:i}=yield r.startLivestreaming(e);this.playbackUrl=n,this.ingestionCredentials=i,e!=null&&e.manualIngestion&&this.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}catch(r){throw l.error("DyteRecording::stop::livestream_failed_to_start",{error:r}),this.setLivestreamState("IDLE"),new _("Error while starting livestream","1900")}})}stop(){return u(this,null,function*(){if(!c(this,ca).permissions.canLivestream)throw l.error("DyteLivestream::stop::permission_denied"),new _("User does not have permission to stop livestreaming","1901");if(this.state!=="LIVESTREAMING"&&this.state!=="WAITING_ON_MANUAL_INGESTION")throw l.error("DyteLivestream::stop::inconsistent_state"),new _("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),yield qe().stopLivestreaming()}catch(e){throw l.error("DyteLivestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new _("Error while stopping livestream","1900")}})}}ca=new WeakMap,qg([y.trace("livestream.start")],mu.prototype,"start",1),qg([y.trace("livestream.stop")],mu.prototype,"stop",1);var GD=Object.defineProperty,qD=Object.getOwnPropertyDescriptor,zD=(t,e,r,n)=>{for(var i=n>1?void 0:n?qD(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&GD(e,r,i),i},da,la,Sn;class zg{constructor(e,r){f(this,"livestream"),T(this,da,void 0),T(this,la,void 0),T(this,Sn,void 0),S(this,la,e),this.livestream=new mu(e),S(this,Sn,r),this.setupEvents()}fetchInitialLivestreamingState(){return u(this,null,function*(){const e=qe(),{status:r,playbackUrl:n,manualIngest:i,ingestionCredentials:s}=yield e.getActiveLivestream();this.livestream.playbackUrl=n,this.livestream.ingestionCredentials=s,r==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),r==="INVOKED"&&i&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")})}setupEvents(){c(this,Sn).on(j.startedLivestream,e=>u(this,null,function*(){this.livestream.playbackUrl=e.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{c(this,la).permissions.canLivestream&&(yield this.fetchInitialLivestreamingState())}catch(r){l.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}})),c(this,Sn).on(j.livestreamingInvoked,e=>u(this,null,function*(){if(e.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{c(this,la).permissions.canLivestream&&(yield this.fetchInitialLivestreamingState())}catch(r){l.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}})),c(this,Sn).on(j.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),c(this,Sn).on(j.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),c(this,Sn).on(j.roomPeerCount,e=>{this.livestream.viewerCount=e.count,this.livestream.emit("viewerCountUpdate",e.count)}),b.on(w.PEER_JOINED_INTERNAL,e=>u(this,null,function*(){var r;((r=e.flags)==null?void 0:r.hiddenParticipant)===!0&&e.recorderType==="LIVESTREAMER"&&(S(this,da,e.id),this.livestream.setLivestreamState("LIVESTREAMING"))})),b.on(w.PEER_CLOSED,e=>{e.id===c(this,da)&&(S(this,da,void 0),this.livestream.setLivestreamState("IDLE"))}),b.onAsync(w.LEAVE_MEDIA_ROOM,()=>u(this,null,function*(){this.livestream.playbackUrl||(l.info("Fetching livestreaming state on leave stage"),yield this.fetchInitialLivestreamingState())})),b.on(w.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){try{yield this.fetchInitialLivestreamingState()}catch(e){l.error("Error: LivestreamController.fetchLivestream")}}))}}da=new WeakMap,la=new WeakMap,Sn=new WeakMap,zD([y.trace("LivestreamController.setupEvents")],zg.prototype,"setupEvents",1);var KD=Object.defineProperty,YD=Object.getOwnPropertyDescriptor,ua=(t,e,r,n)=>{for(var i=n>1?void 0:n?YD(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&KD(e,r,i),i},wt,si,ai,fu,Kg;class Zi{constructor({name:e,socketHandler:r,meetingId:n}){T(this,fu),f(this,"name",""),T(this,wt,{}),T(this,si,""),T(this,ai,void 0),f(this,"rateLimitConfig",{maxInvocations:5,period:1}),f(this,"bulkRateLimitConfig",{maxInvocations:5,period:1}),f(this,"listeners",{}),this.name=e,S(this,ai,r),S(this,si,n)}set(e,r,n=!0,i=!1){return u(this,null,function*(){c(this,wt)[e]=r,n&&this.remoteSet(e,r),i&&(this.listeners[e]&&this.listeners[e].forEach(s=>s({[e]:c(this,wt)[e]})),this.listeners["*"]&&this.listeners["*"].forEach(s=>s({[e]:c(this,wt)[e]})))})}remoteSet(e,r){c(this,ai).storeInsertKeys(c(this,si),this.name,[{key:e,payload:r}])}bulkSet(e){return u(this,null,function*(){e.forEach(({key:r,payload:n})=>{c(this,wt)[r]=n}),c(this,ai).storeInsertKeys(c(this,si),this.name,e)})}update(e,r,n=!0){return u(this,null,function*(){Je(this,fu,Kg).call(this,e,r,n)})}delete(e,r=!0,n=!1){return u(this,null,function*(){if(c(this,wt)[e]&&delete c(this,wt)[e],r)return c(this,ai).storeDeleteKeys(c(this,si),this.name,[{key:e}]);n&&(this.listeners[e]&&(this.listeners[e].forEach(i=>i({[e]:void 0})),delete this.listeners[e]),this.listeners["*"]&&this.listeners["*"].forEach(i=>i({[e]:void 0})))})}bulkDelete(e){return u(this,null,function*(){return e.forEach(({key:r})=>{c(this,wt)[r]&&delete c(this,wt)[r]}),c(this,ai).storeDeleteKeys(c(this,si),this.name,e)})}get(e){if(c(this,wt)[e])return c(this,wt)[e]}getAll(){return c(this,wt)}get rateLimits(){return this.rateLimitConfig}updateRateLimits(e,r){this.rateLimitConfig.maxInvocations=e,this.rateLimitConfig.period=r}get bulkRateLimits(){return this.bulkRateLimitConfig}updateBulkRateLimits(e,r){this.bulkRateLimitConfig.maxInvocations=e,this.bulkRateLimitConfig.period=r}subscribe(e,r){if(this.listeners[e]){this.listeners[e].push(r);return}this.listeners[e]=[r]}unsubscribe(e,r){var n;if(r){this.listeners[e]=((n=this.listeners[e])==null?void 0:n.filter(i=>i!==r))||[];return}this.listeners[e]&&delete this.listeners[e]}populate(e){S(this,wt,e)}}wt=new WeakMap,si=new WeakMap,ai=new WeakMap,fu=new WeakSet,Kg=function(t,e,r=!0){let n;const i=c(this,wt)[t],s=Object.prototype.toString.call(e),a=Object.prototype.toString.call(i);if(s!==a){this.set(t,e);return}switch(a){case"[object Array]":n=[...i,...e];break;case"[object Object]":n=U(U({},i),e);break;case"[object Map]":n=new Map([...i,...e]);break;case"[object Set]":n=new Set([...i,...e]);break;default:n=e;break}this.set(t,n,r)},ua([xt(Ui,"rateLimitConfig")],Zi.prototype,"remoteSet",1),ua([xt(Ui,"bulkRateLimitConfig")],Zi.prototype,"bulkSet",1),ua([xt(Ui,"rateLimitConfig")],Zi.prototype,"update",1),ua([xt(Ui,"rateLimitConfig")],Zi.prototype,"delete",1),ua([xt(Ui,"bulkRateLimitConfig")],Zi.prototype,"bulkDelete",1);var es,ts,_c,gu,bc,oi,vu,Yg;class QD{constructor(e,r){T(this,_c),T(this,vu),f(this,"stores",new Map),T(this,es,void 0),T(this,ts,""),T(this,bc,void 0),T(this,oi,new Map),S(this,es,r),S(this,ts,e.getValue("meetingId")),S(this,bc,e),Je(this,vu,Yg).call(this)}create(e){const r=new Zi({name:e,socketHandler:c(this,es),meetingId:c(this,ts)});return c(this,es).storeGetKeys(c(this,ts),e,[]),new Promise((n,i)=>{const s=setTimeout(()=>i(Error("Failed")),3e3);c(this,oi).set(e,{rejectTimeout:s,resolve:n,store:r})})}}es=new WeakMap,ts=new WeakMap,_c=new WeakSet,gu=function(){return c(this,bc).getValue("peerId")},bc=new WeakMap,oi=new WeakMap,vu=new WeakSet,Yg=function(){[z.storeInsertKeys,z.storeGetKeys,z.storeDeleteKeys].forEach(t=>{c(this,es).on(t,e=>u(this,null,function*(){var r,n;if(e.pluginId!==c(this,ts))return;const i=(r=e.storeItems)==null?void 0:r.map(a=>{var o;return{timestamp:a.timestamp,peerId:a.peerId,payload:JSON.parse((o=a.payload)!=null&&o.length?new TextDecoder().decode(a.payload):"{}"),key:a.storeKey}});if(t===z.storeGetKeys){const a=c(this,oi).get(e.storeName),o=this.stores.get(e.storeName)||(a==null?void 0:a.store);c(this,oi).get(e.storeName)&&(this.stores.set(e.storeName,a.store),a.resolve(o),clearTimeout(a.rejectTimeout),c(this,oi).delete(e.storeName)),i.forEach(d=>{o.set(d.key,d.payload,!1,!1)});return}const s=this.stores.get(e.storeName)||((n=c(this,oi).get(e.storeName))==null?void 0:n.store);s!==void 0&&(t===z.storeInsertKeys&&i.forEach(({key:a,peerId:o,payload:d})=>{o===c(this,_c,gu)&&t!==z.storeGetKeys||s.set(a,d,!1,!0)}),t===z.storeDeleteKeys&&i.forEach(({key:a,peerId:o})=>{o!==c(this,_c,gu)&&s.delete(a,!1,!0)}))}))})};function ci(t){var e,r,n,i,s,a,o,d,h,p,m,g,v;return t?{media:{audio:{enabled:t.audioEnabled,trackId:(e=t.audioTrack)==null?void 0:e.id,permission:"mediaPermissions"in t?(r=t.mediaPermissions)==null?void 0:r.audio:null},video:{enabled:t.videoEnabled,trackId:(n=t.videoTrack)==null?void 0:n.id,permission:"mediaPermissions"in t?(i=t.mediaPermissions)==null?void 0:i.video:null},screenshare:{enabled:t.screenShareEnabled,permission:"mediaPermissions"in t?(s=t.mediaPermissions)==null?void 0:s.screenshare:null,audio:{enabled:(o=(a=t.screenShareTracks)==null?void 0:a.audio)==null?void 0:o.enabled,trackId:(h=(d=t.screenShareTracks)==null?void 0:d.audio)==null?void 0:h.id},video:{enabled:(m=(p=t.screenShareTracks)==null?void 0:p.video)==null?void 0:m.enabled,trackId:(v=(g=t.screenShareTracks)==null?void 0:g.video)==null?void 0:v.id}}}}:{}}var XD=Object.defineProperty,ZD=Object.getOwnPropertyDescriptor,rs=(t,e,r,n)=>{for(var i=n>1?void 0:n?ZD(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&XD(e,r,i),i};const e1=.8,t1=1.2;var ha,pa,di,ns,ma,En,wc,li,fa,Ic,Tn,yu,Cc,Su,Qg;let Br=(Qg=class extends jt{constructor(t,e,r,n){super(),T(this,ns),T(this,fa),T(this,Cc),f(this,"id"),f(this,"userId"),f(this,"name"),f(this,"picture"),f(this,"isHost"),f(this,"customParticipantId"),f(this,"flags"),f(this,"device"),f(this,"videoTrack"),f(this,"audioTrack"),f(this,"screenShareTracks"),f(this,"videoEnabled"),f(this,"audioEnabled"),f(this,"screenShareEnabled"),f(this,"producers"),f(this,"manualProducerConfig"),T(this,ha,void 0),f(this,"supportsRemoteControl",!1),T(this,pa,void 0),f(this,"presetName"),T(this,di,void 0),T(this,En,void 0),T(this,wc,void 0),T(this,li,new Map),T(this,Tn,1),T(this,yu,Mr(C=>{if(!this.videoTrack)return;const{clientWidth:G,clientHeight:W}=C,{width:de,height:ae}=this.videoTrack.getSettings();if(!de||!ae)return;const Le=ae/W,Dt=de/G,O=Math.max(Le,Dt);O>t1&&c(this,Tn)===1?(S(this,Tn,0),b.emit(w.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:c(this,Tn)})):O<e1&&c(this,Tn)===0&&(S(this,Tn,1),b.emit(w.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:c(this,Tn)}))},2e3)),S(this,di,t);const{id:i,userId:s,displayName:a,device:o,picture:d,isHost:h,flags:p,clientSpecificId:m,stageStatus:g,customParticipantId:v,audioMuted:I,audioTrack:A,videoEnabled:P=!1,videoTrack:D,producers:N,metadata:J}=e;this.id=i,this.userId=s,this.name=a,this.device=o,this.picture=d,this.isHost=h,this.flags=p,this.manualProducerConfig=hw,S(this,pa,g!=null?g:"ON_STAGE"),this.customParticipantId=v!=null?v:m,this.audioEnabled=!I,this.audioTrack=A,this.videoEnabled=P,this.videoTrack=D,this.screenShareTracks={audio:void 0,video:void 0},this.producers=N!=null?N:[],this.presetName=J==null?void 0:J.preset_name,S(this,ha,!1),S(this,En,r),S(this,wc,n),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),Je(this,Cc,Su).call(this)}get clientSpecificId(){return this.customParticipantId}get stageStatus(){return c(this,pa)}get mediaJoined(){return c(this,di).getValue("connectionHandler").mediaJoined}get socketJoined(){return c(this,di).getValue("connectionHandler").socketJoined}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(l.info("DyteParticipant::setVideoEnabled::videoUpdate",U({},ci(this))),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(l.info("DyteParticipant::setAudioEnabled::audioUpdate",U({},ci(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",Je(this,Cc,Su))}pin(){return u(this,null,function*(){if(!this.mediaJoined)throw new _("Can`t pin participant without joining room","1205");if(!c(this,En).permissions.pinParticipant)throw new _("You do not have permission to pin participants.","1201");return c(this,ns,ma).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!this.mediaJoined)throw new _("Can`t unpin participant without joining room","1205");if(!c(this,En).permissions.pinParticipant)throw new _("You do not have permission to unpin participants.","1201");return c(this,ns,ma).pinPeer(null)})}setIsPinned(t,e=!0){var r;S(this,ha,t);const n=t?"pinned":"unpinned";(r=c(this,fa,Ic))==null||r.updateSource(this.id,{pinned:t}),e&&this.emit(n,this)}disableAudio(){return u(this,null,function*(){const t=this.id;if(l.info("DyteParticipant::disable_audio",{dyteParticipant:{id:t}}),!this.mediaJoined)throw new _("Can`t disable participant audio without joining room","1205");if(c(this,En).permissions.canDisableParticipantAudio)return c(this,ns,ma).disableAudio(t);throw l.error("DyteParticipant::unauthorized_disable_audio",{dyteParticipant:{id:t}}),new _("Unauthorized: User does not have permission to disable participant audio.","1201")})}kick(){return u(this,null,function*(){const t=this.id;if(l.info("DyteParticipant::kick",{dyteParticipant:{id:t}}),!this.socketJoined)throw new _("Can`t kick participant without joining room","1205");if(c(this,En).permissions.kickParticipant){yield b.emitAsync(w.KICK_PEER,{peerId:t});return}throw l.error("DyteParticipant::unauthorized_kick",{dyteParticipant:{id:t}}),new _("Unauthorized: User does not have permission to kick participants.","1201")})}disableVideo(){return u(this,null,function*(){const t=this.id;if(l.info("DyteParticipant::disable_video",{dyteParticipant:{id:t}}),!this.mediaJoined)throw new _("Can`t disable participant video without joining room","1205");if(c(this,En).permissions.canDisableParticipantVideo)return c(this,ns,ma).disableVideo(t);throw l.error("DyteParticipant::unauthorized_disable_video",{dyteParticipant:{id:t}}),new _("Unauthorized: User does not have permission to disable participant video.","1201")})}getPermissions(){return u(this,null,function*(){return c(this,wc).getUserPermissions(this.userId)})}setStageStatus(t){S(this,pa,t),this.emit("stageStatusUpdate",this)}get isPinned(){return c(this,ha)}registerVideoElement(t){var e,r,n,i;let s;(r=(e=c(this,li).get(t))==null?void 0:e.observer)==null||r.disconnect(),"ResizeObserver"in window&&(s=new ResizeObserver(()=>c(this,yu).call(this,t)),s.observe(t)),c(this,li).set(t,{observer:s}),this.updateVideo(t),(i=c(this,fa,Ic))==null||i.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(n=this.raised)!=null?n:!1)}deregisterVideoElement(t){var e,r,n;t!==void 0&&(t.srcObject=void 0,(r=(e=c(this,li).get(t))==null?void 0:e.observer)==null||r.disconnect(),c(this,li).delete(t),(n=c(this,fa,Ic))==null||n.removeSource(this.id))}updateVideo(t){var e;if(this.videoEnabled){if(this.videoTrack==null)return;const r=(e=t.srcObject)==null?void 0:e.getTracks()[0];if((r==null?void 0:r.id)===this.videoTrack.id)return;const n=new MediaStream;n.addTrack(this.videoTrack),t.srcObject=n}else t.srcObject=void 0;t.style.display=this.videoEnabled?"block":"none"}},ha=new WeakMap,pa=new WeakMap,di=new WeakMap,ns=new WeakSet,ma=function(){return c(this,di).getValue("roomNodeClient")},En=new WeakMap,wc=new WeakMap,li=new WeakMap,fa=new WeakSet,Ic=function(){return c(this,di).getValue("pip")},Tn=new WeakMap,yu=new WeakMap,Cc=new WeakSet,Su=function(){Array.from(c(this,li).keys()).forEach(this.updateVideo)},Qg);rs([y.trace("DyteParticipant.disableAudio")],Br.prototype,"disableAudio",1),rs([y.trace("DyteParticipant.kick")],Br.prototype,"kick",1),rs([y.trace("DyteParticipant.disableVideo")],Br.prototype,"disableVideo",1),rs([y.trace("DyteParticipant.getPermissions")],Br.prototype,"getPermissions",1),rs([y.trace("DyteParticipant.setStageStatus")],Br.prototype,"setStageStatus",1),Br=rs([vt("1200")],Br);class ga extends Mg{constructor(e){const{onAddEvent:r="participantJoined",onDeleteEvent:n="participantLeft",onClearEvent:i="participantsCleared"}=e!=null?e:{};super({onAddEvent:r,onDeleteEvent:n,onClearEvent:i})}add(e,r=!0){return this.has(e.id)&&Object.is(this.get(e.id),e)===!1&&this.delete(e.id),super.add(e,r)}clear(e=!0,r=!1){return super.clear(e,r)}delete(e,r=!0,n=!1){return super.delete(e,r,n)}}var ui;class r1 extends xi{constructor(){super(),T(this,ui,void 0),S(this,ui,new Map)}__set(e,r){return c(this,ui).set(e,r)}__clear(){return c(this,ui).clear()}get(e){return c(this,ui).get(e)}toArray(){return Array.from(c(this,ui).values())}}ui=new WeakMap;var hi={},Pc={},Rc={},n1={get exports(){return Rc},set exports(t){Rc=t}},Eu,Xg;function i1(){if(Xg)return Eu;Xg=1;var t=1e3,e=t*60,r=e*60,n=r*24,i=n*7,s=n*365.25;Eu=function(p,m){m=m||{};var g=typeof p;if(g==="string"&&p.length>0)return a(p);if(g==="number"&&isFinite(p))return m.long?d(p):o(p);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(p))};function a(p){if(p=String(p),!(p.length>100)){var m=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(p);if(m){var g=parseFloat(m[1]),v=(m[2]||"ms").toLowerCase();switch(v){case"years":case"year":case"yrs":case"yr":case"y":return g*s;case"weeks":case"week":case"w":return g*i;case"days":case"day":case"d":return g*n;case"hours":case"hour":case"hrs":case"hr":case"h":return g*r;case"minutes":case"minute":case"mins":case"min":case"m":return g*e;case"seconds":case"second":case"secs":case"sec":case"s":return g*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return g;default:return}}}}function o(p){var m=Math.abs(p);return m>=n?Math.round(p/n)+"d":m>=r?Math.round(p/r)+"h":m>=e?Math.round(p/e)+"m":m>=t?Math.round(p/t)+"s":p+"ms"}function d(p){var m=Math.abs(p);return m>=n?h(p,m,n,"day"):m>=r?h(p,m,r,"hour"):m>=e?h(p,m,e,"minute"):m>=t?h(p,m,t,"second"):p+" ms"}function h(p,m,g,v){var I=m>=g*1.5;return Math.round(p/g)+" "+v+(I?"s":"")}return Eu}function s1(t){r.debug=r,r.default=r,r.coerce=d,r.disable=s,r.enable=i,r.enabled=a,r.humanize=i1(),r.destroy=h,Object.keys(t).forEach(p=>{r[p]=t[p]}),r.names=[],r.skips=[],r.formatters={};function e(p){let m=0;for(let g=0;g<p.length;g++)m=(m<<5)-m+p.charCodeAt(g),m|=0;return r.colors[Math.abs(m)%r.colors.length]}r.selectColor=e;function r(p){let m,g=null,v,I;function A(...P){if(!A.enabled)return;const D=A,N=Number(new Date),J=N-(m||N);D.diff=J,D.prev=m,D.curr=N,m=N,P[0]=r.coerce(P[0]),typeof P[0]!="string"&&P.unshift("%O");let C=0;P[0]=P[0].replace(/%([a-zA-Z%])/g,(G,W)=>{if(G==="%%")return"%";C++;const de=r.formatters[W];if(typeof de=="function"){const ae=P[C];G=de.call(D,ae),P.splice(C,1),C--}return G}),r.formatArgs.call(D,P),(D.log||r.log).apply(D,P)}return A.namespace=p,A.useColors=r.useColors(),A.color=r.selectColor(p),A.extend=n,A.destroy=r.destroy,Object.defineProperty(A,"enabled",{enumerable:!0,configurable:!1,get:()=>g!==null?g:(v!==r.namespaces&&(v=r.namespaces,I=r.enabled(p)),I),set:P=>{g=P}}),typeof r.init=="function"&&r.init(A),A}function n(p,m){const g=r(this.namespace+(typeof m=="undefined"?":":m)+p);return g.log=this.log,g}function i(p){r.save(p),r.namespaces=p,r.names=[],r.skips=[];let m;const g=(typeof p=="string"?p:"").split(/[\s,]+/),v=g.length;for(m=0;m<v;m++)g[m]&&(p=g[m].replace(/\*/g,".*?"),p[0]==="-"?r.skips.push(new RegExp("^"+p.slice(1)+"$")):r.names.push(new RegExp("^"+p+"$")))}function s(){const p=[...r.names.map(o),...r.skips.map(o).map(m=>"-"+m)].join(",");return r.enable(""),p}function a(p){if(p[p.length-1]==="*")return!0;let m,g;for(m=0,g=r.skips.length;m<g;m++)if(r.skips[m].test(p))return!1;for(m=0,g=r.names.length;m<g;m++)if(r.names[m].test(p))return!0;return!1}function o(p){return p.toString().substring(2,p.toString().length-2).replace(/\.\*\?$/,"*")}function d(p){return p instanceof Error?p.stack||p.message:p}function h(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}var a1=s1;(function(t,e){e.formatArgs=n,e.save=i,e.load=s,e.useColors=r,e.storage=a(),e.destroy=(()=>{let d=!1;return()=>{d||(d=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function r(){return typeof window!="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document!="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function n(d){if(d[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+d[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const h="color: "+this.color;d.splice(1,0,h,"color: inherit");let p=0,m=0;d[0].replace(/%[a-zA-Z%]/g,g=>{g!=="%%"&&(p++,g==="%c"&&(m=p))}),d.splice(m,0,h)}e.log=console.debug||console.log||(()=>{});function i(d){try{d?e.storage.setItem("debug",d):e.storage.removeItem("debug")}catch(h){}}function s(){let d;try{d=e.storage.getItem("debug")}catch(h){}return!d&&typeof process!="undefined"&&"env"in process&&(d={}.DEBUG),d}function a(){try{return localStorage}catch(d){}}t.exports=a1(e);const{formatters:o}=t.exports;o.j=function(d){try{return JSON.stringify(d)}catch(h){return"[UnexpectedJSONParseError]: "+h.message}}})(n1,Rc);var o1=_h&&_h.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Pc,"__esModule",{value:!0}),Pc.Logger=void 0;const is=o1(Rc),ss="awaitqueue";class c1{constructor(e){e?(this._debug=(0,is.default)(`${ss}:${e}`),this._warn=(0,is.default)(`${ss}:WARN:${e}`),this._error=(0,is.default)(`${ss}:ERROR:${e}`)):(this._debug=(0,is.default)(ss),this._warn=(0,is.default)(`${ss}:WARN`),this._error=(0,is.default)(`${ss}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}}Pc.Logger=c1,Object.defineProperty(hi,"__esModule",{value:!0});var as=hi.AwaitQueue=hi.AwaitQueueRemovedTaskError=hi.AwaitQueueStoppedError=void 0;const d1=Pc,kn=new d1.Logger;class Tu extends Error{constructor(e){super(e!=null?e:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Tu)}}hi.AwaitQueueStoppedError=Tu;class Ac extends Error{constructor(e){super(e!=null?e:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Ac)}}hi.AwaitQueueRemovedTaskError=Ac;class l1{constructor(){this.pendingTasks=new Map,this.nextTaskId=0,this.stopping=!1}get size(){return this.pendingTasks.size}push(e,r){return u(this,null,function*(){if(r=r!=null?r:e.name,kn.debug(`push() [name:${r}]`),typeof e!="function")throw new TypeError("given task is not a function");if(r)try{Object.defineProperty(e,"name",{value:r})}catch(n){}return new Promise((n,i)=>{const s={id:this.nextTaskId++,task:e,name:r,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:a=>{if(s.completed)return;s.completed=!0,this.pendingTasks.delete(s.id),kn.debug(`resolving task [name:${s.name}]`),n(a);const[o]=this.pendingTasks.values();o&&!o.executedAt&&this.execute(o)},reject:a=>{if(!s.completed&&(s.completed=!0,this.pendingTasks.delete(s.id),kn.debug(`rejecting task [name:${s.name}]: %s`,String(a)),i(a),!this.stopping)){const[o]=this.pendingTasks.values();o&&!o.executedAt&&this.execute(o)}}};this.pendingTasks.set(s.id,s),this.pendingTasks.size===1&&this.execute(s)})})}stop(){kn.debug("stop()"),this.stopping=!0;for(const e of this.pendingTasks.values())kn.debug(`stop() | stopping task [name:${e.name}]`);this.stopping=!1}remove(e){kn.debug(`remove() [taskIdx:${e}]`);const r=Array.from(this.pendingTasks.values())[e];if(!r){kn.debug(`stop() | no task with given idx [taskIdx:${e}]`);return}r.reject(new Ac)}dump(){const e=Date.now();let r=0;return Array.from(this.pendingTasks.values()).map(n=>({idx:r++,task:n.task,name:n.name,enqueuedTime:n.executedAt?n.executedAt-n.enqueuedAt:e-n.enqueuedAt,executionTime:n.executedAt?e-n.executedAt:0}))}execute(e){return u(this,null,function*(){if(kn.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{const r=yield e.task();e.resolve(r)}catch(r){e.reject(r)}})}}as=hi.AwaitQueue=l1;var Mc;class Zg{constructor(){f(this,"meetingTitle"),f(this,"roomName"),f(this,"roomUUID"),T(this,Mc,void 0),f(this,"context"),f(this,"authToken"),f(this,"maxPreferredStreams")}get peerId(){return this.context.getValue("peerId")}get mediaJoined(){return!1}set mediaJoined(e){throw new _("Method not implemented.")}get sfuHandler(){return c(this,Mc)}get mediaState(){return c(this,Mc).transportState}reconnect(){throw new _("Method not implemented.")}partialJoinRoom(e,r,n=!1,i=void 0){return u(this,null,function*(){throw new _("Method not implemented.")})}joinRoom(e,r){return u(this,arguments,function*(n,i,s={},a=!1,o=!1){throw new _("Method not implemented.")})}leaveRoom(){return u(this,null,function*(){throw new _("Method not implemented.")})}reset(e=!0){throw new _("Method not implemented")}handleSocketCallbacks(e){return u(this,null,function*(){throw new _("Method not implemented.")})}handleSockets(e,r){return u(this,null,function*(){throw new _("Method not implemented.")})}shareMic(e){return u(this,null,function*(){throw new _("Method not implemented.")})}shareWebcam(e){return u(this,null,function*(){throw new _("Method not implemented.")})}shareScreen(e){return u(this,null,function*(){throw new _("Method not implemented.")})}unmuteSelf(){return u(this,null,function*(){throw new _("Method not implemented.")})}muteSelf(){return u(this,null,function*(){throw new _("Method not implemented.")})}pauseWebcam(){return u(this,null,function*(){throw new _("Method not implemented.")})}disableScreenShare(){return u(this,null,function*(){throw new _("Method not implemented.")})}acceptWaitingRequest(e){return u(this,null,function*(){throw new _("Method not implemented.")})}rejectWaitingRequest(e){return u(this,null,function*(){throw new _("Method not implemented.")})}muteAll(e){return u(this,null,function*(){throw new _("Method not implemented.")})}muteAllVideo(){return u(this,null,function*(){throw new _("Method not implemented.")})}disableAudio(e){return u(this,null,function*(){throw new _("Method not implemented.")})}disableVideo(e){return u(this,null,function*(){throw new _("Method not implemented.")})}kickAll(){return u(this,null,function*(){throw new _("Method not implemented.")})}kick(e){return u(this,null,function*(){throw new _("Method not implemented.")})}pinPeer(e){return u(this,null,function*(){throw new _("Method not implemented.")})}getConsumers(){throw new _("Method not implemented.")}stopAllProducers(){throw new _("Method not implemented.")}activatePeers(e){return u(this,null,function*(){throw new _("Method not implemented.")})}deactivatePeers(e,r="default"){return u(this,null,function*(){throw new _("Method not implemented.")})}createConsumers(e){return u(this,null,function*(){throw new _("Method not implemented.")})}closeConsumers(e){return u(this,null,function*(){throw new _("Method not implemented.")})}switchConsumersToLayer(e,r){return u(this,null,function*(){throw new _("Method not implemented.")})}}Mc=new WeakMap;var jr=(t=>(t.INITIALIZING="INITIALIZING",t.INITIALIZED="INITIALIZED",t.NOT_INITIALIZED="NOT_INITIALIZED",t))(jr||{});class ev extends ht.EventEmitter{}class pi extends ht.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}safeEmit(e,...r){const n=this.listenerCount(e);try{return this.emit(e,...r)}catch(i){return l.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:i}),Boolean(n)}}safeEmitAsPromise(e,...r){return u(this,null,function*(){const n={}.EVENT_PROMISE_TIMEOUT?parseInt({}.EVENT_PROMISE_TIMEOUT,10):1e4;return this.safeEmitAsPromiseWithTimeout(e,n,...r)})}safeEmitAsPromiseWithTimeout(e,r,...n){return u(this,null,function*(){return new Promise((i,s)=>{setTimeout(s,r,"event request timeout");try{this.emit(e.toString(),...n,i,s)}catch(a){l.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:a}),s(a)}})})}}function u1(t,e){const r=new Error(e);return r.name=t,r}class mi extends _{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,mi):this.stack=new Error(e).stack}}class et extends _{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,et):this.stack=new Error(e).stack}}class tv extends _{constructor(e){super(e),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,et):this.stack=new Error(e).stack}}class rv extends _{constructor(e){super(e),this.name="DataChannelRequestError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,et):this.stack=new Error(e).stack}}var Dc,Oc,Nc,Lc,Hr,xc,Fc,br,os,Vc,Uc,Bc,ku,_u,nv,bu,iv;class sv extends pi{constructor({id:e,localId:r,producerId:n,producingPeerId:i,producingTransportId:s,handler:a,track:o,appData:d,paused:h,reuseTrack:p,rtpReceiver:m}){super(),T(this,Bc),T(this,_u),T(this,bu),f(this,"rtpReceiver"),f(this,"observer"),T(this,Dc,void 0),T(this,Oc,void 0),T(this,Nc,void 0),T(this,Lc,void 0),T(this,Hr,void 0),T(this,xc,void 0),T(this,Fc,void 0),T(this,br,void 0),T(this,os,void 0),T(this,Vc,void 0),T(this,Uc,void 0),S(this,Dc,e),S(this,Oc,r),S(this,Fc,a),S(this,Uc,d),S(this,Vc,i),S(this,Lc,s),S(this,Hr,!1),S(this,Nc,n),S(this,br,o),S(this,os,h!=null?h:!1),S(this,xc,p),this.observer=new pi,this.rtpReceiver=m,Je(this,_u,nv).call(this)}get id(){return c(this,Dc)}get peerId(){return c(this,Vc)}get localId(){return c(this,Oc)}get producerId(){return c(this,Nc)}get producingTransportId(){return c(this,Lc)}get closed(){return c(this,Hr)}get kind(){return c(this,br).kind}get track(){return c(this,br)}get paused(){return c(this,os)}get remotelyPaused(){return this.paused}get appData(){return c(this,Uc)}close(e){c(this,Hr)||(l.debug("Consumer::close() with reason:",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,closureReason:e,kind:this.kind}}),S(this,Hr,!0),c(this,xc)||Je(this,bu,iv).call(this),this.emit("close",e),this.observer.safeEmit("close",e))}getStats(){return u(this,null,function*(){if(c(this,Hr))throw new et("closed");return c(this,Fc).getReceiverStats(this.localId)})}pause(){if(l.debug("consumer::pause()",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}),c(this,Hr)){l.error("consumer::pause() | Consumer closed",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}});return}S(this,os,!0),c(this,br).enabled=!1,this.observer.safeEmit("pause")}resume(){if(l.debug("consumer::resume()",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}),c(this,Hr)){l.error("Consumer::resume() | Consumer closed",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}});return}S(this,os,!1),c(this,br).enabled=!0,this.observer.safeEmit("resume")}}Dc=new WeakMap,Oc=new WeakMap,Nc=new WeakMap,Lc=new WeakMap,Hr=new WeakMap,xc=new WeakMap,Fc=new WeakMap,br=new WeakMap,os=new WeakMap,Vc=new WeakMap,Uc=new WeakMap,Bc=new WeakSet,ku=function(){l.debug('Consumer::track "ended" event',{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}),this.safeEmit("trackended"),this.observer.safeEmit("trackended")},_u=new WeakSet,nv=function(){c(this,br).addEventListener("ended",Je(this,Bc,ku).bind(this))},bu=new WeakSet,iv=function(){try{c(this,br).removeEventListener("ended",Je(this,Bc,ku)),c(this,br).stop()}catch(t){l.error("Consumer::destroyTrack()",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind},error:t})}};let h1=class extends sv{};const av=t=>new Promise(e=>setTimeout(e,t));function wr(t,e){return u(this,null,function*(){return new Promise((r,n)=>u(this,null,function*(){const{strategy:i,maxRetryCount:s,delayTime:a}=U({strategy:"linear",maxRetryCount:3,delayTime:10},e);let o=0,d,h=!1;const p=m=>{h=!0,n(m)};for(;o<s;){try{const m=yield t(o,p);return r(m)}catch(m){if(d=m,h)break;if(o<s)i==="linear"?yield av(a*(o+1)):i==="exponential"&&(yield av(a*(o+Math.max(0,o-1))));else break}o+=1}return n(d)}))})}function jc(t){if(Promise.allSettled)return Promise.allSettled(t);const e=t.map(r=>r.then(n=>({status:"fulfilled",value:n})).catch(n=>({status:"rejected",reason:n})));return Promise.all(e)}function p1(t,e){return typeof t=="undefined"?e:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(t):JSON.parse(JSON.stringify(t))}function ov(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function wu(t){return Math.random().toString(36).substring(2,2+t)}const Hc=1;function cv(t){const e=t;return delete e.payload._bolt,e}function m1(t){return t.payload&&ov(t.payload)}function Wc(t){var e,r;return m1(t)&&(r=(e=t.payload._bolt)==null?void 0:e.id)!=null?r:""}var fi;const va=class extends ht.EventEmitter{constructor(t,e,r){super(),f(this,"channel"),f(this,"queue"),f(this,"serverProtocolVersion"),T(this,fi,new Map),f(this,"respond",(n,i,s=!1)=>{let a;s?a=va.createErrorResponse(n,i):a=va.createResponse(n,i),this.channel.send(JSON.stringify(a))}),f(this,"notify",n=>{const i=va.createNotification(n);this.channel.send(JSON.stringify(i))}),f(this,"request",n=>u(this,null,function*(){const i=va.createRequest(n),s=new Promise((a,o)=>{const d=1e3*(5+.1*this.queue.size),{id:h}=i.payload._bolt,p={id:h,method:i.type,resolve:m=>{this.queue.delete(h)&&(clearTimeout(p.timer),a(m))},timer:setTimeout(()=>{this.queue.delete(h)&&o(new Error(`request timeout for message id: ${h}`))},d),cancel:m=>{this.queue.delete(h)&&(clearTimeout(p.timer),o(m))}};this.queue.set(h,p)});return this.channel.send(JSON.stringify(i)),s})),f(this,"send",n=>{const i=JSON.stringify(n),s=16384;if(i.length>s){const a=s-200,o=Math.ceil(i.length/a),d=[];for(let p=0;p<o;p+=1){const m=p*a,g=(p+1)*a;d.push(i.slice(m,g))}const h=Un();for(let p=0;p<o;p+=1){const m=d[p],g=JSON.stringify({id:h,count:o,chunkIndex:p,chunk:m});l.debug(`Sending message chunk over dc: ${g}`),this.channel.send(g)}}else l.debug(`Sending message over dc: ${i}`),this.channel.send(i)}),f(this,"processMessage",n=>{var i;c(this,fi).has(n.id)||c(this,fi).set(n.id,[]);const s=c(this,fi).get(n.id);if(s[n.chunkIndex]=n,(s==null?void 0:s.length)===n.count&&!s.some(a=>a===void 0)){const a=c(this,fi).get(n.id),o=a==null?void 0:a.reduce((h,p)=>h+p.chunk,"");c(this,fi).delete(n.id);const d=JSON.parse(o);if(!d.payload||!ov(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=(i=d.payload._bolt)==null?void 0:i.version,!this.processResponseMsg(d))return d}}),f(this,"processResponseMsg",n=>{const{id:i}=n.payload._bolt,s=this.queue.get(i);return s?(l.debug(`resolving pending request with id: ${i}, complete response: ${JSON.stringify(n)}`),n.type==="error"?s.cancel(cv(n)):s.resolve(cv(n)),!0):!1}),f(this,"processBoltHandshake",n=>{var i,s;return n.type==="_bolt"||n.type==="handshake"?(this.respond((s=(i=n.payload._bolt)==null?void 0:i.id)!=null?s:wu(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1}),this.label=e,this.transportId=r,this.channel=t,this.queue=new Map}};let ya=va;fi=new WeakMap,f(ya,"createRequest",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:X(U({},t.payload),{_bolt:{id:wu(8),type:"REQUEST",version:Hc}})}}),f(ya,"createResponse",(t,e)=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:X(U({},e.payload),{_bolt:{id:t,type:"RESPONSE",version:Hc}})}}),f(ya,"createNotification",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:X(U({},t.payload),{bolt:{id:wu(8),type:"NOTIFY",version:Hc}})}}),f(ya,"createErrorResponse",(t,e)=>({type:"error",payload:{error:e.message,_bolt:{id:t,type:"RESPONSE",version:Hc}}}));const Iu="transport closed";class dv extends pi{constructor({id:e,direction:r,handlerFactory:n,iceServers:i,iceTransportPolicy:s,proprietaryConstraints:a,additionalSettings:o,appData:d,config:h}){var p,m;super(),f(this,"awaitQueue"),f(this,"observer"),f(this,"id"),f(this,"serverId"),f(this,"closed",!1),f(this,"direction"),f(this,"maxSctpMessageSize"),f(this,"handler"),f(this,"connectionState","new"),f(this,"producers"),f(this,"consumers"),f(this,"datachannels"),f(this,"connected",!1),f(this,"eventsDCReadyPromise"),f(this,"eventsDCReadyPromiseResolver"),f(this,"eventsDCFailureTimer"),f(this,"transportConnectionPromise"),f(this,"consumerTrackEvents"),f(this,"unknownTracksMap"),f(this,"consumerTrackPool"),f(this,"appData"),l.debug(`constructor() [id: ${e}, direction: ${r}]`),this.id=e,this.direction=r;const g=p1(o,{});delete g.iceServers,delete g.iceTransportPolicy,delete g.bundlePolicy,delete g.rtcpMuxPolicy,delete g.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.consumerTrackPool=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new as,this.observer=new pi,this.handler=n(),this.handler._enableHighBitrate=(p=h==null?void 0:h.enableHighBitrate)!=null?p:!1,this.handler._enableStereo=(m=h==null?void 0:h.enableStereo)!=null?m:!1,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:r,iceServers:i,iceTransportPolicy:s,additionalSettings:o,proprietaryConstraints:a}),this.appData=d||{},this.transportConnectionPromise=new Promise(v=>{this.observer.once("connected",()=>{v(!0)}),this.observer.once("disconnect",()=>{v(!1)}),this.observer.once("close",()=>{v(!1)})}),this.eventsDCReadyPromise=new Promise(v=>{this.eventsDCReadyPromiseResolver=v}),this.handler.on("@connectionstatechange",v=>{v!==this.connectionState&&(l.debug(`connection state changed to ${v}`),this.connectionState=v,v==="connected"&&(this.connected=!0,this.observer.emit("connected")),v==="disconnected"&&(this.connected=!1,this.observer.emit("disconnect")),(v==="failed"||v==="closed")&&(this.connected=!1,this.observer.emit("close")),this.closed||this.safeEmit("connectionstatechange",v))}),this.handler.on("@icecandidate",({candidate:v})=>{this.closed||this.safeEmit("icecandidate",v)}),this.handler.on("dc_open",v=>{let I=this.datachannels.get(v.label);I||(I||(I=new ya(v,v.label,this.serverId),this.datachannels.set(v.label,I)),this.eventsDCFailureTimer=setTimeout(()=>{v.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",v.label))},5e3))}),this.handler.on("datachannel",(v,I)=>{v.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const A=this.datachannels.get(v.label);if(!A){l.error("unregistered datachannel for message",{rtcChannel:{label:v.label,message:I}});return}try{const P=JSON.parse(I);l.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:P.id,count:P.count,chunkIndex:P.chunkIndex,chunk:P.chunk,transprtId:this.serverId}});const D=A.processMessage(P);if(!D)return;l.debug(`datachannel message with id:${P.id} on transport:${this.serverId}complete - ${JSON.stringify(D)}`),this.emit(`datachannel:${v.label}`,A.label,D)}catch(P){l.error("error parsing message",{error:P})}})}get isConnected(){return this.transportConnectionPromise}setServerId(e){this.serverId=e}getDatachannel(e){return this.datachannels.get(e)}get isEventsDCReady(){return this.eventsDCReadyPromise}close(){this.closed||(l.debug("Transport close called"),this.connected=!1,this.closed=!0,this.handler.close(),Array.from(this.producers.values()).forEach(e=>{e.close(Iu).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(Iu)}),this.consumers.clear(),this.consumerTrackPool.clear(),this.consumerTrackEvents.clear(),this.emit("close"),this.observer.emit("close"))}getStats(){return u(this,null,function*(){if(this.closed)throw new et("closed");return this.handler.getTransportStats()})}restartIce(){return u(this,null,function*(){if(l.debug("restartIce()"),this.closed)throw new et("closed");return this.handler.restartIce()})}updateIceServers(){return u(this,arguments,function*({iceServers:e}={}){if(l.debug("updateIceServers()"),this.closed)throw new et("closed");return this.handler.updateIceServers(e)})}setRemoteOffer(e){return u(this,null,function*(){yield this.setRemoteDescription(e);const r=yield this.handler.pc.createAnswer(),n=Md(r.sdp);return n.media=n.media.map(i=>{if(i.type==="audio"){const s=U({},i),a=s.fmtp.find(o=>o.payload===111);return a&&(a.config+=";stereo=1;sprop-stereo=1"),s.rtcpFb||(s.rtcpFb=[]),s.rtcpFb.some(o=>o.type==="nack")||s.rtcpFb.push({payload:parseInt(s.payloads,10),type:"nack"}),s}return i}),r.sdp=Yy(n),yield this.setLocalDescription(r),r})}sendErrorOverDC(e,r,n){const i=this.getDatachannel(e);if(!i)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});i.respond(r,n,!0)}sendResponseOverDC(e,r,n){const i=this.getDatachannel(e);if(!i)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});i.respond(r,n)}setRemoteDescription(e){return u(this,null,function*(){yield this.handler.pc.setRemoteDescription(e)})}setLocalDescription(e){return u(this,null,function*(){l.debug(`${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),yield this.handler.pc.setLocalDescription(e)})}createConsumersOverDataChannel(e){return u(this,null,function*(){const r=this.getDatachannel("events");if(!r)throw u1("DC_NOT_READY","events datachannel not ready");if(!e||e&&e.length===0)throw new Error("list of producers is required");const n={type:"create_consumer",payload:{producers:e.map(({producerId:o,producingTransportId:d})=>({producerId:o,producingTransportId:d}))}},i=new Map;e.forEach(o=>i.set(o.producerId,o));const s=(yield r.request(n)).payload;l.info(`createConsumersOverDataChannel::response ${JSON.stringify(s)}`);const a=new Map;return Object.entries(s).forEach(([o,d])=>{const h=i.get(d.producerId);if(!h){l.error(`unknown entry in create consumer response, producerId: ${d.producerId}`,{consumerState:d});return}a.set(d.producerId,{consumerId:o,producingTransportId:h.producingTransportId,producingPeerId:h.producingPeerId,kind:h.kind,paused:h.pause,streamId:d.streamId,trackId:d.trackId,screenShare:h.screenShare,appData:{}})}),a})}}class lv extends pi{constructor({id:e,localId:r,track:n,stopTracks:i,disableTrackOnPause:s,zeroRtpOnPause:a,handler:o,appData:d,rtpSender:h}){super(),f(this,"_id"),f(this,"_localId"),f(this,"_closed",!1),f(this,"_handler"),f(this,"_track"),f(this,"_kind"),f(this,"_paused"),f(this,"_maxSpatialLayer"),f(this,"_stopTracks"),f(this,"_disableTrackOnPause"),f(this,"_zeroRtpOnPause"),f(this,"_appData"),f(this,"observer"),f(this,"rtpSender"),this._id=e,this._localId=r,this._track=n,this._kind=n.kind,this._paused=s?!n.enabled:!1,this._maxSpatialLayer=void 0,this._stopTracks=i,this._disableTrackOnPause=s,this._zeroRtpOnPause=a,this._appData=d||{},this._onTrackEnded=this._onTrackEnded.bind(this),this._handler=o,this.rtpSender=h,this.observer=new pi,this._handleTrack()}get id(){return this._id}get localId(){return this._localId}get closed(){return this._closed}get kind(){return this._kind}get track(){return this._track}get paused(){return this._paused}get maxSpatialLayer(){return this._maxSpatialLayer}get appData(){return this._appData}set appData(e){throw new Error("cannot override appData object")}close(e){return u(this,null,function*(){if(this._closed)return;if(l.debug("Producer::close() with reason:"),this._closed=!0,this._destroyTrack(),e===Iu){this.observer.emit("close");return}const{offerSdp:r,callback:n}=yield this._handler.stopSending(this.localId);this.observer.emit("close");const{answer:i}=yield this.safeEmitAsPromise("close",{offer:r,reason:e});n(i)})}getStats(){return u(this,null,function*(){if(this._closed)throw new et("closed");return this._handler.getSenderStats(this.localId)})}pause(){l.debug("Producer::pause()",{producer:{id:this.id,appData:this.appData,kind:this.kind}}),this._closed&&l.error("Producer::pause() | Producer closed",{producer:{id:this.id,appData:this.appData,kind:this.kind}}),this._paused=!0,this._track&&this._disableTrackOnPause&&(this._track.enabled=!1),this._zeroRtpOnPause&&this._handler.replaceTrack(this.localId,null),this.observer.emit("pause")}resume(){if(l.debug("Producer::resume()",{producer:{id:this.id,appData:this.appData,kind:this.kind}}),this._closed){l.error("Producer::resume() | Producer closed",{producer:{id:this.id,appData:this.appData,kind:this.kind}});return}this._paused=!1,this._track&&this._disableTrackOnPause&&(this._track.enabled=!0),this._zeroRtpOnPause&&this._handler.replaceTrack(this.localId,this._track),this.observer.emit("resume")}replaceTrack(e){return u(this,arguments,function*({track:r}){if(l.debug("Producer::replaceTrack()",{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:r==null?void 0:r.id}}),this._closed){if(r&&this._stopTracks)try{r.stop()}catch(n){l.error("Producer::replaceTrack",{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:r==null?void 0:r.id},error:n})}throw new et("closed")}else if(r&&r.readyState==="ended")throw new et("track ended");if(r===this._track){l.debug("replaceTrack() | same track, ignored",{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:r==null?void 0:r.id}});return}(!this._zeroRtpOnPause||!this._paused)&&(yield this._handler.replaceTrack(this.localId,r)),this._destroyTrack(),this._track=r,this._handleTrack()})}setMaxSpatialLayer(e){return u(this,null,function*(){if(this._closed)throw new et("closed");if(this._kind!=="video")throw new mi("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");yield this._handler.setMaxSpatialLayer(this.localId,e),this._maxSpatialLayer=e})}setRtpEncodingParameters(e){return u(this,null,function*(){if(this._closed)throw new et("closed");if(typeof e!="object")throw new TypeError("invalid params");yield this._handler.setRtpEncodingParameters(this.localId,e)})}_onTrackEnded(){l.debug('Producer::track "ended" event',{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:this.track.id}}),this.observer.emit("trackended"),this.safeEmit("trackended",this.track.id)}_handleTrack(){this._track&&this._track.addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(this._track)try{this._track.removeEventListener("ended",this._onTrackEnded),this._stopTracks&&this._track.stop()}catch(r){l.error("Producer::_destroyTrack",{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:(e=this._track)==null?void 0:e.id},error:r})}}}let f1=class extends lv{},g1=class extends dv{consume(t){return u(this,null,function*(){if(l.debug(`consume() producers: ${JSON.stringify(t)}`),this.closed)throw new et("closed");if(this.direction!=="recv")throw new mi("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.isConnected))throw new tv("transport not connected");let e;try{e=yield this.createConsumersOverDataChannel(t)}catch(n){throw new rv(n.message)}const r=[];return e.forEach((n,i)=>{const{consumerId:s,trackId:a,screenShare:o,paused:d,streamId:h,kind:p,appData:m,producingTransportId:g,producingPeerId:v}=n;r.push(this.consumerCreationTask({consumerId:s,trackId:a,streamId:h,kind:p,producerId:i,producingPeerId:v,producingTransportId:g,paused:d,screenShare:o,appData:m}))}),jc(r)})}connect(){return u(this,null,function*(){try{const{offerSdp:t,callback:e}=yield this.handler.connect(),{answer:r}=yield this.safeEmitAsPromise("connect",{offer:t});if(yield e(r),!(yield this.isConnected))throw new Error("ice connection failed");if(!(yield this.isEventsDCReady))throw new Error("events datachannel not open")}catch(t){throw l.error("transport failed to connect:",t),t}})}_ontrack(t){const{track:e,transceiver:r,streams:n}=t;l.info(`track event received [trackId: ${e.id}]`);const i=`${n[0].id}:${e.kind}`;e.addEventListener("ended",()=>{l.info(`rtc consumer track ended [trackId: ${e.id}]`),this.consumerTrackPool.delete(e.id),this.unknownTracksMap.delete(i)}),this.consumerTrackPool.set(e.id,[e,r]);const s=this.consumerTrackEvents.get(i);s?(s(e,r),this.consumerTrackEvents.delete(i)):(l.warn(`track event handler not found ${i}`),this.unknownTracksMap.set(i,t))}consumerCreationTask(t){return u(this,arguments,function*({consumerId:e,producerId:r,producingPeerId:n,producingTransportId:i,streamId:s,trackId:a,paused:o,screenShare:d,appData:h,kind:p}){const m=`${s}:${p}`,g={consumerId:e,producerId:r,producingPeerId:n,producingTransportId:i,streamId:s,trackId:a,appData:h,kind:p,paused:o,screenShare:d,name:"consumer creation task error",message:"consumer creation failed"};return new Promise((v,I)=>{const A=setTimeout(()=>{this.consumerTrackEvents.delete(m),g.isTimedout=!0,I(g)},5e3),P=(J,C)=>{try{if(J.readyState==="ended")clearTimeout(A),I(g);else{const G=J;G.enabled=!0,this.handler.midTransceiverMap.set(C.mid,C);const W=new h1({id:e,localId:C.mid,track:G,paused:o,producerId:r,producingPeerId:n,producingTransportId:i,handler:this.handler,appData:X(U({},h),{screenShare:d,peerId:n}),reuseTrack:!0,rtpReceiver:C.receiver});this.consumers.set(e,W),W.once("close",()=>{this.consumers.delete(W.id),this.handler.midTransceiverMap.delete(C.mid)}),l.info("consumer created for ",{consumer:{id:e,kind:p,appData:{screenShare:d},peerId:n,producerId:r}}),this.observer.emit("newconsumer",W),clearTimeout(A),v(W)}}catch(G){l.warn("error while creating consumer:",G),clearTimeout(A),I(g)}},D=this.consumerTrackPool.get(e);if((D==null?void 0:D.length)===2){P(D[0],D[1]);return}const N=this.unknownTracksMap.get(m);N?(this.unknownTracksMap.delete(m),P(N.track,N.transceiver)):this.consumerTrackEvents.set(m,P)})})}retryFailedConsumerCreationTasks(t){return u(this,null,function*(){return jc(t.map(e=>u(this,null,function*(){return wr(r=>u(this,null,function*(){return r>0&&l.warn(`retrying failed consumer creation task: ${JSON.stringify(e)}`),this.consumerCreationTask(U({},e))}))})))})}produce(){return u(this,arguments,function*({track:t,encodings:e,codecOptions:r,stopTracks:n=!0,disableTrackOnPause:i=!0,zeroRtpOnPause:s=!1,appData:a={}}={}){if(l.debug(`produce() [track:${t.id}]`),t){if(this.direction!=="send")throw new mi("not a sending Transport");if(t.readyState==="ended")throw new et("track ended");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("produce")===0)throw new TypeError('no "produce" listener set into this transport');if(a&&typeof a!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!(yield this.isConnected))return Promise.reject(new Error("Transport not connected"));const{producerId:o,localId:d,rtpSender:h}=yield this.awaitQueue.push(()=>u(this,null,function*(){const{offerSdp:m,callback:g,sender:v,mid:I}=yield this.handler.send({track:t,encodings:e,codecOption:r,screenShare:a==null?void 0:a.screenShare}),{answer:A,producerId:P}=yield this.safeEmitAsPromise("produce",{offer:m,kind:t.kind,paused:i?!t.enabled:!1,appData:X(U({},a||{}),{mid:I})}),D=yield g(A);return{producerId:P,localId:D,rtpSender:v}}),"producer"),p=new f1({id:o,localId:d,track:t,stopTracks:n,disableTrackOnPause:i,zeroRtpOnPause:s,appData:a,handler:this.handler,rtpSender:h});return this.producers.set(o,p),p.observer.on("close",()=>{this.producers.delete(p.id)}),this.emit("newproducer",p),this.observer.emit("newproducer",p),p})}};class Cu extends pi{constructor(){super(),f(this,"_mapMidTransceiver",new Map),f(this,"_enableHighBitrate",!1),f(this,"_enableStereo",!1),this._mapMidTransceiver=new Map,this._enableHighBitrate=!1}get midTransceiverMap(){return this._mapMidTransceiver}}class Pu extends Cu{constructor(){super(),f(this,"_direction"),f(this,"_pc"),f(this,"_sendWebStream",new MediaStream),f(this,"_sendScreenShareStream",new MediaStream),f(this,"_transportReady",!1)}static createFactory(){return()=>new Pu}get name(){return"Chrome74"}get pc(){return this._pc}close(){if(l.debug("close()"),this._pc)try{this._pc.close()}catch(e){l.error("pc.close()",e)}}init({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,onTrackHandler:a}){this._direction=e,this._pc=new RTCPeerConnection(U({iceServers:r||[],iceTransportPolicy:n||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"},i),s),a&&this._pc.addEventListener("track",o=>{a(o)}),this._addEventListeners()}connect(){return u(this,null,function*(){const e=this._pc.createDataChannel("dyte"),r=yield this._pc.createOffer();return l.info(`connect offer: ${JSON.stringify(r)}`),yield this._pc.setLocalDescription(r),{offerSdp:r,callback:n=>u(this,null,function*(){l.debug(`Chrome74::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(n)}]`),yield this._pc.setRemoteDescription(n),e.close()})}})}updateIceServers(e){return u(this,null,function*(){l.debug("updateIceServers()");const r=this._pc.getConfiguration();r.iceServers=e,this._pc.setConfiguration(r)})}restartIce(){return u(this,null,function*(){l.debug("restartIce()");const e=yield this.pc.createOffer({iceRestart:!0});return l.debug(`restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:r=>u(this,null,function*(){l.info(`restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(r)}]`),yield this._pc.setRemoteDescription(r)})}})}getTransportStats(){return u(this,null,function*(){return this._pc.getStats()})}send(e){return u(this,arguments,function*({track:r,encodings:n,codecOption:i,screenShare:s}){var a;this._assertSendDirection(),l.debug(`send() [kind:${r.kind}, track.id:${r.id}]`);const o=this._pc.addTransceiver(r,{direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream],sendEncodings:n});if(!navigator.isReactNative){l.debug("creating new transceiver");const h=RTCRtpSender.getCapabilities(r.kind);l.info(`senders available params: ${JSON.stringify(h)}`);const p=[];if(i){const m=h.codecs.find(g=>g.mimeType.includes(i.name));if(i.parameters){l.info(`codecOption.parameters:${JSON.stringify(i.parameters)}`);const g=((a=m.sdpFmtpLine)==null?void 0:a.split(";"))||[];g.push(...i.parameters);const v=Array.from(new Set(g).values());m.sdpFmtpLine=v.join(";")}p.push(m)}l.info(`selected codecs: ${JSON.stringify(p)}`),o.setCodecPreferences(p)}const d=yield this._pc.createOffer();if(!this._transportReady)throw new Error("webrtc transport not connected");if(yield this._pc.setLocalDescription(d),i&&i.name==="opus"){const h=this._enableStereo,p=this._enableHighBitrate?h?128e3:64e3:h?64e3:32e3;d.sdp=d.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;usedtx=1${h?"":";stereo=1;sprop-stereo=1"};maxaveragebitrate=${p}`),d.sdp+=`a=rtcp-fb:111 nack\r
20
+ `}return{offerSdp:d,callback:h=>u(this,null,function*(){return l.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),yield this._pc.setRemoteDescription(h),this.midTransceiverMap.set(o.mid,o),o.mid}),sender:o.sender,mid:o.mid}})}stopSending(e){return u(this,null,function*(){this._assertSendDirection(),l.debug(`stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.sender.replaceTrack(null),this._pc.removeTrack(r.sender),r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}replaceTrack(e,r){return u(this,null,function*(){this._assertSendDirection(),r?l.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):l.debug(`replaceTrack() [localId:${e}, no track]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");yield n.sender.replaceTrack(r)})}setMaxSpatialLayer(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,a)=>{a<=r?s.active=!0:s.active=!1}),yield n.sender.setParameters(i)})}setRtpEncodingParameters(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,a)=>{i.encodings[a]=U(U({},s),r)}),yield n.sender.setParameters(i)})}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}stopReceiving(e){return u(this,null,function*(){throw this._assertRecvDirection(),l.debug(`stopReceiving() [localId:${e}]`),Error("method not implemented")})}pauseReceiving(e){return u(this,null,function*(){throw this._assertRecvDirection(),l.debug(`pauseReceiving() [localId:${e}]`),Error("method not implemented")})}resumeReceiving(e){return u(this,null,function*(){throw this._assertRecvDirection(),l.debug(`resumeReceiving() [localId:${e}]`),Error("method not implemented")})}getReceiverStats(e){return u(this,null,function*(){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.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')}_generateOffer(){return u(this,null,function*(){const e=yield this._pc.createOffer();return yield this._pc.setLocalDescription(e),e})}_setAnswer(e){return u(this,null,function*(){l.debug(`setAnswer() | calling pc.setRemoteDescription() [answer:${JSON.stringify(e)}]`),yield this._pc.setRemoteDescription(e)})}_addEventListeners(){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:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this._pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),l.debug("negotiationneeded")}),this._pc.addEventListener("icegatheringstatechange",()=>{switch(this._pc.iceGatheringState){case"gathering":l.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":l.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidateerror",e=>{l.error("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this._pc.addEventListener("datachannel",e=>{l.info("data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{l.info("data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{l.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{l.error("data channel error: ",{rtcChannel:{label:e.channel.label}})},r.onmessage=n=>{this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(n.data)))}})}}class $c extends Cu{constructor(e){super(),f(this,"_direction"),f(this,"_pc"),f(this,"_sendWebStream",new MediaStream),f(this,"_sendScreenShareStream",new MediaStream),f(this,"_transportReady",!1),f(this,"supportsSendEncodings",!1),this.supportsSendEncodings=e.supportsSendEncodings}static createFactory(e){return()=>new $c(e)}get name(){return"Firefox60"}get pc(){return this._pc}close(){if(l.debug("Firefox60::close()"),this._pc)try{this._pc.close()}catch(e){l.error("Firefox60::pc.close()",{error:e})}}init({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,onTrackHandler:a}){l.debug("Firefox60::init()"),this._direction=e,this._pc=new RTCPeerConnection(U({iceServers:r||[],iceTransportPolicy:n||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"},i),s),a&&this._pc.addEventListener("track",o=>{a(o)}),this._addEventListeners()}connect(){return u(this,null,function*(){const e=this._pc.createDataChannel("dyte"),r=yield this._pc.createOffer();return l.info(`Firefox60::connect offer: ${JSON.stringify(r)}`),yield this._pc.setLocalDescription(r),{offerSdp:r,callback:n=>u(this,null,function*(){l.debug(`Firefox60::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(n)}]`),yield this._pc.setRemoteDescription(n),e.close()})}})}updateIceServers(e){return u(this,null,function*(){throw l.debug("Firefox60::updateIceServers()"),new Error("not supported")})}restartIce(){return u(this,null,function*(){l.debug("Firefox60::restartIce()");const e=yield this.pc.createOffer({iceRestart:!0});return l.debug(`Firefox60::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:r=>u(this,null,function*(){l.info(`Firefox60::restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(r)}]`),yield this._pc.setRemoteDescription(r)})}})}getTransportStats(){return u(this,null,function*(){return this._pc.getStats()})}send(e){return u(this,arguments,function*({track:r,encodings:n,screenShare:i}){this._assertSendDirection(),l.debug(`Firefox60::send() [kind:${r.kind}, track.id:${r.id}]`),l.debug("Firefox60::creating new transceiver");const s=this.supportsSendEncodings&&n!==void 0?{sendEncodings:n}:{},a=this._pc.addTransceiver(r,U({direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream]},s));if(!this.supportsSendEncodings&&n){n.reverse();const d=a.sender.getParameters();d.encodings=n,yield a.sender.setParameters(d)}const o=yield this._pc.createOffer();if(!this._transportReady)throw new Error("webrtc transport not connected");if(yield this._pc.setLocalDescription(o),r.kind==="audio"){const d=this._enableStereo,h=this._enableHighBitrate?d?128e3:64e3:d?64e3:32e3;o.sdp=o.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;usedtx=1${this.supportsSendEncodings?"":`${d?"":";stereo=1;sprop-stereo=1"};maxaveragebitrate=${h}`}`)}return{offerSdp:o,callback:d=>u(this,null,function*(){return l.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),yield this._pc.setRemoteDescription(d),this.midTransceiverMap.set(a.mid,a),a.mid}),sender:a.sender,mid:a.mid}})}stopSending(e){return u(this,null,function*(){this._assertSendDirection(),l.debug(`Firefox60::stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated transceiver not found");r.sender.replaceTrack(null),this._pc.removeTrack(r.sender),r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}replaceTrack(e,r){return u(this,null,function*(){this._assertSendDirection(),r?l.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):l.debug(`Firefox60::replaceTrack() [localId:${e}, no track]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");yield n.sender.replaceTrack(r)})}setMaxSpatialLayer(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters(),s=i.encodings.length-1-r;i.encodings.forEach((a,o)=>{o>=s?a.active=!0:a.active=!1}),yield n.sender.setParameters(i)})}setRtpEncodingParameters(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,a)=>{i.encodings[a]=U(U({},s),r)}),yield n.sender.setParameters(i)})}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}stopReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Firefox60::stopReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive",l.info(`Firefox60::active transcievers: ${JSON.stringify(this._pc.getTransceivers())}`);const n=yield this._pc.createOffer();return l.debug(`Firefox60::stopRecieving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`Firefox60::stopRecieving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}pauseReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Firefox60::pauseReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`pauseReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`pauseReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i)})}})}resumeReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Firefox60::resumeReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="recvonly";const n=yield this._generateOffer();return l.debug(`resumeReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`resumeReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i)})}})}getReceiverStats(e){return u(this,null,function*(){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.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')}_generateOffer(){return u(this,null,function*(){const e=yield this._pc.createOffer();return yield this._pc.setLocalDescription(e),e})}_setAnswer(e){return u(this,null,function*(){l.debug(`_setAnswer() | calling pc.setRemoteDescription() [answer:${JSON.stringify(e)}]`),yield this._pc.setRemoteDescription(e)})}_addEventListeners(){this._pc.addEventListener("datachannel",e=>{l.info("Firefox60::data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{l.info("Firefox60::data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{l.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{l.error("Firefox60::data channel error: ",{rtcChannel:{label:e.channel.label}})},r.onmessage=n=>u(this,null,function*(){const i=yield n.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(i)))})}),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:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this._pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),l.debug("Firefox60::negotiationneeded")}),this._pc.addEventListener("icegatheringstatechange",()=>{switch(this._pc.iceGatheringState){case"gathering":l.debug("Firefox60::icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":l.debug("Firefox60::icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidateerror",e=>{l.error("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})})}}class Ru extends Cu{constructor(){super(),f(this,"_direction"),f(this,"_pc"),f(this,"_sendWebStream",new MediaStream),f(this,"_sendScreenShareStream",new MediaStream),f(this,"_transportReady",!1)}static createFactory(){return()=>new Ru}get name(){return"Chrome74"}get pc(){return this._pc}close(){if(l.debug("Safari12::close()"),this._pc)try{this._pc.close()}catch(e){l.error("Safari12::pc.close()",e)}}init({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,onTrackHandler:a}){l.debug("Safari12::init()"),this._direction=e,this._pc=new RTCPeerConnection(U({iceServers:r||[],iceTransportPolicy:n||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"},i),s),a&&this._pc.addEventListener("track",o=>{a(o)}),this._addEventListeners()}connect(){return u(this,null,function*(){const e=this._pc.createDataChannel("dyte"),r=yield this._pc.createOffer();return l.info(`Safari12::connect offer: ${JSON.stringify(r)}`),yield this._pc.setLocalDescription(r),{offerSdp:r,callback:n=>u(this,null,function*(){l.debug(`Safari12::connect() | calling pc.setRemoteDescription() [answer: ${JSON.stringify(n)}]`),yield this._pc.setRemoteDescription(n),e.close()})}})}updateIceServers(e){return u(this,null,function*(){l.debug("Safari12::updateIceServers()");const r=this._pc.getConfiguration();r.iceServers=e,this._pc.setConfiguration(r)})}restartIce(){return u(this,null,function*(){l.debug("Safari12::restartIce()");const e=yield this.pc.createOffer({iceRestart:!0});return l.debug(`restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:r=>u(this,null,function*(){l.info(`restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(r)}]`),yield this._pc.setRemoteDescription(r)})}})}getTransportStats(){return u(this,null,function*(){return this._pc.getStats()})}send(e){return u(this,arguments,function*({track:r,encodings:n,codecOption:i,screenShare:s}){var a;this._assertSendDirection(),l.debug(`Safari12::send() [kind: ${r.kind}, track.id: ${r.id}]`),l.debug("Safari12::creating new transceiver");const o=this._pc.addTransceiver(r,{direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream],sendEncodings:n}),d=RTCRtpSender.getCapabilities(r.kind);l.info(`Safari12::senders available params: ${JSON.stringify(d)}`);const h=[];if(i){const m=d.codecs.find(g=>g.mimeType.includes(i.name));if(i.parameters){l.info(`Safari12::codecOption.parameters:, ${JSON.stringify(i.parameters)}`);const g=((a=m.sdpFmtpLine)==null?void 0:a.split(";"))||[];g.push(...i.parameters);const v=[...new Set(g).values()];m.sdpFmtpLine=v.join(";")}h.push(m)}l.info(`Safari12::selected codecs: ${JSON.stringify(h)}`),o.setCodecPreferences(h);const p=yield this._pc.createOffer();if(!this._transportReady)throw new Error("webrtc transport not connected");if(yield this._pc.setLocalDescription(p),r.kind==="audio"){const m=this._enableStereo,g=this._enableHighBitrate?m?128e3:64e3:m?64e3:32e3;p.sdp=p.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;usedtx=1${m?"":";stereo=1;sprop-stereo=1"};maxaveragebitrate=${g}`)}return{offerSdp:p,callback:m=>u(this,null,function*(){return l.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(m)}]`),yield this._pc.setRemoteDescription(m),this.midTransceiverMap.set(o.mid,o),o.mid}),sender:o.sender,mid:o.mid}})}stopSending(e){return u(this,null,function*(){this._assertSendDirection(),l.debug(`Safari12::stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.sender.replaceTrack(null),this._pc.removeTrack(r.sender),r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`Safari12::stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`Safari12::stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}replaceTrack(e,r){return u(this,null,function*(){this._assertSendDirection(),r?l.debug(`Safari12::replaceTrack() [localId:${e}, track.id:${r.id}]`):l.debug(`Safari12::replaceTrack() [localId:${e}, no track]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");yield n.sender.replaceTrack(r)})}setMaxSpatialLayer(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,a)=>{a<=r?s.active=!0:s.active=!1}),yield n.sender.setParameters(i)})}setRtpEncodingParameters(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,a)=>{i.encodings[a]=U(U({},s),r)}),yield n.sender.setParameters(i)})}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}receive(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`recieve() | calling pc.setLocalDescription() [answer:${JSON.stringify(e)}]`);const r=this._pc.getTransceivers().at(-1);return l.info("Safari12::Transceiver is now receiving"),this.midTransceiverMap.set(r.mid,r),{track:r.receiver.track,localId:r.mid}})}stopReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Safari12::stopReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive",l.info(`Safari12::active transcievers: ${JSON.stringify(this._pc.getTransceivers())}`);const n=yield this._pc.createOffer();return l.debug(`stopRecieving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`stopRecieving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}pauseReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Safari12::pauseReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`pauseReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`pauseReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i)})}})}resumeReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Safari12::resumeReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="recvonly";const n=yield this._generateOffer();return l.debug(`Safari12::resumeReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`Safari12::resumeReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i)})}})}getReceiverStats(e){return u(this,null,function*(){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.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')}_generateOffer(){return u(this,null,function*(){const e=yield this._pc.createOffer();return yield this._pc.setLocalDescription(e),e})}_setAnswer(e){return u(this,null,function*(){l.debug(`Safari12::_setAnswer() | calling pc.setRemoteDescription() [answer:${JSON.stringify(e)}]`),yield this._pc.setRemoteDescription(e)})}_addEventListeners(){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:l.warn("Safari12::unknown state");break}}),this._pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this._pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),l.debug("Safari12::negotiationneeded")}),this._pc.addEventListener("icegatheringstatechange",()=>{switch(this._pc.iceGatheringState){case"gathering":l.debug("Safari12::icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":l.debug("Safari12::icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:l.warn("Safari12::unknown state");break}}),this._pc.addEventListener("icecandidateerror",e=>{l.error("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this._pc.ondatachannel=e=>{l.info("Safari12::data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{l.info("Safari12::data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{l.warn("Safari12::data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{l.error("Safari12::data channel error: ",{rtcChannel:{label:e.channel.label}})},r.onmessage=n=>u(this,null,function*(){const i=String.fromCharCode(...new Uint8Array(n.data));this.safeEmit("datachannel",e.channel,i)})}}}function v1(){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){l.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return l.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=Xu.getParser(t),r=e.getEngine();if(e.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(e.satisfies({chrome:">=70",chromium:">=70"}))return"Chrome70";if(e.satisfies({chrome:">=67",chromium:">=67"}))return"Chrome67";if(e.satisfies({chrome:">=55",chromium:">=55"}))return"Chrome55";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"}))return"Safari11";if(e.satisfies({"microsoft edge":">=11"})&&e.satisfies({"microsoft edge":"<=18"}))return"Edge11";if(r.name&&r.name.toLowerCase()==="blink"){const n=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);if(n){const i=Number(n[1]);return i>=74?"Chrome74":i>=70?"Chrome70":i>=67?"Chrome67":"Chrome55"}return"Chrome74"}if(r.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":"Safari11";l.warn("Device::this._detectDevice() | browser not supported");return}l.warn("Device::this._detectDevice() | unknown device")}class uv{constructor({handlerName:e,handlerFactory:r}={}){if(f(this,"handlerFactory"),f(this,"_handlerName"),f(this,"_observer"),l.debug("constructor()"),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)l.debug(`Device::constructor() | handler given: ${e}`);else if(e=v1(),e)l.debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=Pu.createFactory();break;case"Safari12":this.handlerFactory=Ru.createFactory();break;case"Firefox60":this.handlerFactory=$c.createFactory({supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=$c.createFactory({supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}const n=this.handlerFactory();this._handlerName=n.name,n.close(),this._observer=new ht}get handlerName(){return this._handlerName}createSendTransport({iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s,config:a}){return l.debug("Device::createSendTransport()"),this.createTransport({direction:"send",iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s,config:a})}createRecvTransport({iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s}){return l.debug("Device::createRecvTransport()"),this.createTransport({direction:"recv",iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s})}}let y1=class extends uv{createTransport({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s,config:a}){const o=Un(),d=new g1({id:o,direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s,handlerFactory:this.handlerFactory,config:a});return this._observer.emit("newtransport",d),d}};var It;class S1{constructor(e){T(this,It,void 0),S(this,It,e)}joinRoom(e,r,n=!1,i=null){return u(this,null,function*(){const s={roomUuid:e,displayName:r,prejoined:n};return i&&(s.location=i),(yield c(this,It).sendMessagePromiseWithTimeout({event:oe.joinRoom,protobuf:gf.toBinary(s),timeout:5e3})).payload})}connectTransport(e){return u(this,null,function*(){const r=(yield c(this,It).sendMessagePromise(oe.createWebRTCTransport,lf.toBinary(e))).payload,{transportId:n,description:i}=_l.fromBinary(r),s={sdp:i==null?void 0:i.sdp,type:i.type};return{transportId:n,answer:s}})}produce(e){return u(this,null,function*(){var r,n;const i=(yield c(this,It).sendMessagePromise(oe.produce,Sf.toBinary(e))).payload,s=Mf.fromBinary(i);return{answer:{sdp:(r=s==null?void 0:s.description)==null?void 0:r.sdp,type:(n=s==null?void 0:s.description)==null?void 0:n.type},producerId:s.producerId}})}consume(e){return u(this,null,function*(){const r=(yield c(this,It).sendMessagePromise(oe.consume,bl.toBinary(e))).payload,{consumerIdsMap:{map:n}}=Af.fromBinary(r);return n})}closeProducer(e){return u(this,null,function*(){const r=(yield c(this,It).sendMessagePromise(oe.closeProducer,Tf.toBinary(e))).payload,{description:n}=Df.fromBinary(r);return n})}closeConsumer(e){return u(this,null,function*(){return(yield c(this,It).sendMessagePromise(oe.closeConsumer,kf.toBinary(e))).payload})}hostControlForPeer(e,r){return u(this,null,function*(){const n={audio:r==="audio",screeShare:!1,video:r==="video",participantId:e},i=(yield c(this,It).sendMessagePromise(oe.hostControlPeer,wf.toBinary(n))).payload;if(!i)return!1;const{status:s}=Lf.fromBinary(i);return s==="success"})}hostControlForAll(e){return u(this,null,function*(){const r={audio:e==="audio",screenShare:!1,video:e==="video"},n=(yield c(this,It).sendMessagePromise(oe.hostControlAllPeers,If.toBinary(r))).payload;if(!n)return!1;const{status:i}=xf.fromBinary(n);return i==="success"})}kickAll(){return u(this,null,function*(){const e={propagateKickAcrossRooms:!1},r=(yield c(this,It).sendMessagePromise(oe.kickAll,wl.toBinary(e))).payload;if(!r)return!1;const{status:n}=Nf.fromBinary(r);return n==="success"})}kickPeer(e){return u(this,null,function*(){const r=(yield c(this,It).sendMessagePromise(oe.kickPeer,_f.toBinary(e))).payload;if(!r)return!1;const{status:n}=Of.fromBinary(r);return n==="success"})}changeDisplayName(e){return u(this,null,function*(){const r=(yield c(this,It).sendMessagePromise(oe.changeDisplayName,bf.toBinary(e))).payload;if(!r)return!1;const{status:n}=Ff.fromBinary(r);return n==="success"})}notifySelfJoinComplete(){return u(this,null,function*(){const e={},r=(yield c(this,It).sendMessagePromise(oe.selfJoinComplete,vf.toBinary(e))).payload;return qo.fromBinary(r)})}}It=new WeakMap;var er=(t=>(t.NEW="new",t.CONNECTING="connecting",t.RECONNECTING="reconnecting",t.DISCONNECTED="disconnected",t.CONNECTED="connected",t.FAILED="failed",t))(er||{}),cs=(t=>(t[t.HIVE=1]="HIVE",t[t.ROOM_NODE=2]="ROOM_NODE",t[t.CF=3]="CF",t))(cs||{});const E1=2e3;var ds,Sa,Wr;class T1 extends ev{constructor(e,r){super(),T(this,ds),f(this,"_device"),f(this,"_sendTransport"),f(this,"_recvTransport"),f(this,"_consumers"),f(this,"_producers"),f(this,"_producerStatus"),f(this,"_producerIdToConsumerIdMap"),f(this,"_socket"),f(this,"_socketHandler"),f(this,"_metrics",{sendTransportFailureCount:0,recvTransportFailureCount:0,consumerCreationFailureCount:0,producerCreationFailureCount:0,lastConnectionTime:0}),f(this,"_transportDisconnectedTimer"),f(this,"_iceTransportPolicy","all"),f(this,"_producerNotReadyFailureCount",0),f(this,"transportConnectionStatus"),f(this,"transportState"),f(this,"transportDisconnected"),T(this,Wr,void 0),S(this,Wr,e),this._device=new y1({}),this._socket=r,c(this,ds,Sa).mediaState={recv:{state:er.NEW,reconnected:!1},send:{state:er.NEW,reconnected:!1}},this.transportDisconnected={recv:!1,send:!1},this._socketHandler=new S1(r),this.reset()}get socket(){return this._socket}get producers(){return this._producers}get consumers(){return this._consumers}get producerIdToConsumerIdMap(){return this._producerIdToConsumerIdMap}get hiveSocketHandler(){return this._socketHandler}get sendTransport(){return this._sendTransport}get recvTransport(){return this._recvTransport}reset(){this._producers=new Map,this._consumers=new Map,this._producerStatus=new Map,this._producerIdToConsumerIdMap=new Map,this._transportDisconnectedTimer={recv:void 0,send:void 0}}setupTransports(e){return u(this,null,function*(){var r,n,i,s,a,o,d,h;Q.hasFeature(ie.FORCE_RELAY)&&(l.info("Forcing relay"),this._iceTransportPolicy="relay");const p=yield qe().getICEServers().catch(g=>(l.warn(`failed to get iceservers from server: ${g.message}`),[])),m=[];if(e.send){const g=this.createSendTransport({iceServers:p,additionalSettings:{encodedInsertableStreams:(r=c(this,Wr).getValue("modules").e2ee)==null?void 0:r.enabled},config:{enableHighBitrate:(s=(i=(n=c(this,Wr).getValue("defaults").mediaConfiguration)==null?void 0:n.audio)==null?void 0:i.enableHighBitrate)!=null?s:!1,enableStereo:(d=(o=(a=c(this,Wr).getValue("defaults").mediaConfiguration)==null?void 0:a.audio)==null?void 0:o.enableStereo)!=null?d:!1},iceTransportPolicy:this._iceTransportPolicy});m.push(g)}if(e.recv){const g=this.createRecvTransport({iceServers:p,additionalSettings:{encodedInsertableStreams:(h=c(this,Wr).getValue("modules").e2ee)==null?void 0:h.enabled},iceTransportPolicy:this._iceTransportPolicy});m.push(g)}yield Promise.all(m)})}stopAllTransports(){var e,r,n,i;l.info("closing all the transports"),(e=this._sendTransport)==null||e.close(),(r=this._sendTransport)==null||r.removeAllListeners(),(n=this._recvTransport)==null||n.close(),(i=this._recvTransport)==null||i.removeAllListeners(),this._sendTransport=void 0,this._recvTransport=void 0,this.reset()}createSendTransport(e){return u(this,null,function*(){var r,n;l.info("sendTransport::initializing_transport",{transport:{id:(r=this._sendTransport)==null?void 0:r.id,serverId:(n=this._sendTransport)==null?void 0:n.serverId,type:"send"}});const i=this._device.createSendTransport(e);this._transportDisconnectedTimer.send=void 0,l.info("sendTransport::initialized_transport",{transport:{id:i==null?void 0:i.id,serverId:i==null?void 0:i.serverId,type:"send"}}),this.handleTransport(i),l.info("sendTransport::connecting_transport",{transport:{id:i==null?void 0:i.id,serverId:i==null?void 0:i.serverId,type:"send"}});try{yield wr((s,a)=>u(this,null,function*(){var o,d;if(this._sendTransport&&this._sendTransport.connected){l.info("sendTransport::already_exists_in_connected_state",{transport:{id:(o=this._sendTransport)==null?void 0:o.id,serverId:(d=this._sendTransport)==null?void 0:d.serverId,type:"send"}});return}if(!this.socket.isConnected){a(new Error("socket is not connected"));return}if(i.connectionState==="closed"){a(new Error("transport is closed"));return}s>0&&l.debug(`retrying transport connect, count: ${s}`,{transport:{id:i.id,serverId:i.serverId,type:"send"}});try{yield i.connect()}catch(h){if(l.error(`failed to connect send transport: ${i.id}`,{error:h,transport:{id:i.id,serverId:i.serverId,type:"send"},country:y.location.country}),h.message==="ice connection failed"){a(h);return}throw this._metrics.sendTransportFailureCount+=1,h}}),{delayTime:100,strategy:"exponential",maxRetryCount:Q.hasFeature(ie.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),l.info("sendTransport::connected_transport",{transport:{id:i==null?void 0:i.id,serverId:i==null?void 0:i.serverId,type:"send"}}),this._producerNotReadyFailureCount=0,this._sendTransport=i,$.configureSendTransport(i)}catch(s){throw l.error(`failed to connect send transport after retry:${i.id}`,{error:s,transport:{id:i==null?void 0:i.id,serverId:i==null?void 0:i.serverId,type:"send"}}),i.close(),i.removeAllListeners(),this._metrics.sendTransportFailureCount+=1,this.handleErrors("rejoin"),s}})}createRecvTransport(e){return u(this,null,function*(){var r,n,i;l.info("recvTransport::initializing_transport",{transport:{id:(r=this._recvTransport)==null?void 0:r.id,serverId:(n=this._recvTransport)==null?void 0:n.serverId,type:"recv"}});const s=this._device.createRecvTransport(X(U({},e),{additionalSettings:X(U({},(i=e.additionalSettings)!=null?i:{}),{rtcAudioJitterBufferMaxPackets:25,rtcAudioJitterBufferFastAccelerate:!0,rtcAudioJitterBufferMinDelayMs:20})}));this._transportDisconnectedTimer.recv=void 0,l.info("recvTransport::initialized_transport",{transport:{id:s==null?void 0:s.id,serverId:s==null?void 0:s.serverId,type:"recv"}}),this.handleTransport(s),l.info("recvTransport::connecting_transport",{transport:{id:s==null?void 0:s.id,serverId:s==null?void 0:s.serverId,type:"recv"}});try{yield wr((a,o)=>u(this,null,function*(){var d,h;if(this._recvTransport&&this._recvTransport.connected){l.info("recvTransport::already_exists_in_connected_state",{transport:{id:(d=this._recvTransport)==null?void 0:d.id,serverId:(h=this._recvTransport)==null?void 0:h.serverId,type:"recv"}});return}if(!this.socket.isConnected){o(new Error("socket is not connected"));return}if(s.connectionState==="closed"){o(new Error("transport is closed"));return}a>0&&l.debug(`retrying transport connect, count: ${a}`,{transport:{id:s==null?void 0:s.id,serverId:s==null?void 0:s.serverId,type:"recv"}});try{yield s.connect()}catch(p){if(l.error(`fail to connect recv transport: ${s.id}`,{error:p,transport:{id:s==null?void 0:s.id,serverId:s==null?void 0:s.serverId,type:"recv"},country:y.location.country}),p.message==="ice connection failed"){o(p);return}throw this._metrics.recvTransportFailureCount+=1,p}}),{delayTime:100,strategy:"exponential",maxRetryCount:Q.hasFeature(ie.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),l.info("recvTransport::connected_transport",{transport:{id:s==null?void 0:s.id,serverId:s==null?void 0:s.serverId,type:"recv"}}),this.producerIdToConsumerIdMap.clear(),this._recvTransport=s,$.configureRecvTransport(s)}catch(a){throw l.error(`failed to connect recv transport after retry:${s.id}`,{error:a,transport:{id:s==null?void 0:s.id,serverId:s==null?void 0:s.serverId,type:"recv"}}),s.close(),s.removeAllListeners(),this._metrics.recvTransportFailureCount+=1,this.handleErrors("rejoin"),a}})}handleTransport(e){const{direction:r,id:n}=e,i=r==="recv";if(e.on("connect",(s,a,o)=>u(this,[s,a,o],function*({offer:d},h,p){try{const m={consuming:i,description:{sdp:d.sdp,type:d.type,target:i?Ht.SUBSCRIBER:Ht.PUBLISHER}},{transportId:g,answer:v}=yield this._socketHandler.connectTransport(m);e.setServerId(g),h({answer:v})}catch(m){l.error(`${i?"consumer":"producer"} transport connection error:`,{error:m,transport:{id:n,serverId:e.serverId,type:r},country:y.location.country}),p(m)}})),e.on("connectionstatechange",s=>u(this,null,function*(){this.updateTransportState({state:s,direction:r}),l.info(`${i?"consumer":"producer"} transport connectionState:`,{transport:{id:n,serverId:e.serverId,type:r,status:s}});const a=()=>{const o=this._transportDisconnectedTimer[r];o!==void 0&&(clearTimeout(o),this._transportDisconnectedTimer[r]=void 0)};switch(s){case"connected":a(),this._metrics.lastConnectionTime=performance.now();break;case"disconnected":this._transportDisconnectedTimer[r]=setTimeout(()=>{this.triggerTransportReconnection(e)},E1);break;case"failed":if(e.closed)return;a(),this.triggerTransportReconnection(e);break}})),e.on("icecandidate",s=>u(this,null,function*(){l.debug("sending icecandidate:",{iceCandidate:s})})),e.on("datachannel:events",(s,a)=>u(this,null,function*(){var o,d;l.debug("got data channel message on event:",{rtcChannel:{label:s,message:a}});try{switch(a.type){case"negotiation":{e.awaitQueue.push(()=>u(this,null,function*(){return this.negotiateOverDC(a,Wc(a),s,e)}));break}case"handshake":{const h={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(s,Wc(a),h);break}case"consumer_toggle":{this.handleConsumerToggle(a.payload);break}case"hub-disconnect":{l.debug(`media hub disconnected, full_reconnect: ${(o=a.payload)==null?void 0:o.full_reconnect}`),((d=a.payload)==null?void 0:d.full_reconnect)===!0&&this.handleErrors("rejoin");break}case"error":{this.handleErrorOverDC(a.payload,e.id);break}default:l.warn(`unknown event received from hive node, event: ${a.type}`);break}}catch(h){l.error(`Unable to handle the incoming datachannel message on channel ${s}`)}})),e.on("dc_error",()=>{e.direction==="recv"&&(l.warn("events datachannel did not open in 5s",{country:y.location.country}),this.handleErrors("reconnectRecvTransport"))}),e.on("negotiate",(s,a,o)=>u(this,[s,a,o],function*({description:d},h,p){try{const m={sdp:d==null?void 0:d.sdp,type:d==null?void 0:d.type},g=yield this.negotiate(e,m);h({answer:g})}catch(m){l.error("negotiate error:",{transport:{id:e.id,serverId:e.serverId,type:e.direction},error:m}),p(m)}})),!i){e.on("produce",(s,a,o)=>u(this,[s,a,o],function*({offer:d,kind:h,paused:p,appData:m},g,v){var I;const A=Md(d.sdp).media.filter(D=>h==="video"?D.type==="video":D.type==="audio").at(-1).msid,P={description:{sdp:d.sdp,type:d.type,target:Ht.PUBLISHER},paused:p,kind:h,msid:A,appData:JSON.stringify(m),screenShare:(I=m.screenShare)!=null?I:!1};try{const{answer:D,producerId:N}=yield this._socketHandler.produce(P);g({answer:D,producerId:N})}catch(D){l.error("create producer error:",D),v(D)}}));return}e.on("consume_peer",(s,a,o)=>u(this,[s,a,o],function*({producingPeerId:d,producerId:h},p,m){l.info("consumePeer:",d);const g={producingPeerId:d,producerId:h};try{const v=yield this._socketHandler.consume(g);l.debug(`consumePeer response for ${d}:`,{consumerStateMap:v});const I=new Map;Object.entries(v).forEach(([A,P])=>{var D,N,J;let C={};try{C=JSON.parse(P.producerState.appData)}catch(G){}I.set(A,{consumerId:P.consumerId,trackId:(D=P.producerTrack)==null?void 0:D.trackId,streamId:P.producerTrack.streamId,kind:P.producerState.kind===Lt.VIDEO?"video":"audio",appData:C,screenShare:(N=P.producerState)==null?void 0:N.screenShare,paused:(J=P.producerState)==null?void 0:J.pause,producingPeerId:d})}),p({consumersMap:I})}catch(v){l.error("consumePeer error:",{error:v}),m(v)}})),e.on("consume",(s,a,o)=>u(this,[s,a,o],function*({producerId:d,producingPeerId:h},p,m){var g,v,I,A,P,D,N,J,C;const G={producingPeerId:h,producerId:d};try{const W=(yield this._socketHandler.consume(G))[d];let de={};try{de=JSON.parse((g=W.producerState)==null?void 0:g.appData)}catch(ae){}l.info("consumer create response:",{consumer:{remotelyPaused:(v=W.producerState)==null?void 0:v.pause,producerId:(I=W.producerState)==null?void 0:I.producerId,kind:(P=(A=W.producerState)==null?void 0:A.kind)==null?void 0:P.toString(),appData:X(U({},de),{screenShare:(D=W.producerState)==null?void 0:D.screenShare}),id:W.consumerId},consumerState:W}),p({consumerId:W.consumerId,screenShare:(N=W.producerState)==null?void 0:N.screenShare,trackId:(J=W.producerTrack)==null?void 0:J.trackId,streamId:W.producerTrack.streamId,kind:W.producerState.kind===Lt.VIDEO?"video":"audio",paused:(C=W.producerState)==null?void 0:C.pause,appData:de})}catch(W){l.error("error during consuming on server:",W),m(W)}}))}createProducer(e,r,n){return u(this,null,function*(){var i;if(this._sendTransport===void 0||this._sendTransport.closed)return null;l.info("createProducer::initializing_producer",{producer:{id:"TO_BE_CREATED",kind:e,status:"initializing",appData:r==null?void 0:r.appData}});const s=this._producerStatus.get(e);if((s==null?void 0:s.trackId)===r.track.id&&(s==null?void 0:s.status)===jr.INITIALIZING)return l.info("createProducer::producer getting initializing",{producer:{id:"GETTING_CREATED",status:"initializing",kind:e,appData:r==null?void 0:r.appData}}),null;this._producerStatus.set(e,{trackId:r.track.id,status:jr.INITIALIZING});try{const a=yield this._sendTransport.produce(r);return(i=r.appData)!=null&&i.e2ee&&b.emit(w.E2EE_ACTIVE_PRODUCER,a),l.info("createProducer::initialized_producer",{producer:{id:a==null?void 0:a.id,kind:e,status:"producing",appData:r==null?void 0:r.appData}}),a.on("close",(o,d)=>u(this,[o,d],function*({offer:h,reason:p},m){l.info("producer::closing",{debuggingHint:p,producer:{id:a==null?void 0:a.id,kind:e,status:"closing",appData:r==null?void 0:r.appData}});const g={producerId:a.id,description:{sdp:h.sdp,type:h.type,target:Ht.PUBLISHER}};try{const v=yield this._socketHandler.closeProducer(g),I={sdp:v==null?void 0:v.sdp,type:v==null?void 0:v.type};l.info("producer::closed",{producer:{id:a==null?void 0:a.id,kind:e,status:"closed",appData:r==null?void 0:r.appData}}),m({answer:I})}catch(v){l.error("producer close error",v)}this._producerStatus.delete(e),this._producers.delete(e),n(),this.reconfigureWebcamLayers()})),a.on("trackended",()=>{l.info("producer::trackended",{producer:{id:a==null?void 0:a.id,kind:e,status:"UNKNOWN",appData:a==null?void 0:a.appData}}),[ne.MIC,ne.WEBCAM].includes(e)||n()}),this._producers.set(e,a),this._producerStatus.set(e,{trackId:r.track.id,status:jr.INITIALIZED}),this.reconfigureWebcamLayers(),a.track}catch(a){throw this._producerStatus.set(e,{status:jr.NOT_INITIALIZED,trackId:r.track.id}),l.error("createProducer::transport_initialization_failed",{producer:{id:"FAILED_TO_CREATE",kind:e,status:"failed",appData:r==null?void 0:r.appData,error:a}}),this._metrics.producerCreationFailureCount+=1,a}})}reconfigureWebcamLayers(){return u(this,null,function*(){if(!Q.hasFeature(ie.DISABLE_WEBCAM_LAYERS_ON_SCREENSHARE))return;const e=this.producers.get(ne.WEBCAM);e&&(yield this._switchProducerSpatialLayer(e,this.producers.get(ne.SCREENSHARE_VIDEO)?0:3))})}_switchProducerSpatialLayer(e,r){return u(this,null,function*(){try{l.debug("switching layer of webcam producer to:",{media:{video:{layer:r}},producer:{id:e.id,kind:e.kind,appData:e.appData}}),yield e.setMaxSpatialLayer(r)}catch(n){l.error("failed to switch spatial layer",{error:n})}})}_initConsumer(e){e&&(e.observer.on("close",r=>u(this,null,function*(){l.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),this._consumers.delete(e.id),b.emit(w.CONSUMER_CLOSED,{id:e.id})})),this._consumers.set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),b.emit(w.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId}))}createConsumers(e){return u(this,null,function*(){if(this._recvTransport===void 0||this._recvTransport.closed||!this._recvTransport.connected)return;if(e.every(i=>this.getProducer(i.producerId))){l.warn("Cancelled consumer creation for local producer");return}const r=3,n=(i,s=0)=>u(this,null,function*(){try{return yield this._recvTransport.consume(i)}catch(a){if(a instanceof rv){if(this._metrics.consumerCreationFailureCount+=1,s<=r)return n(i,s+1);throw a}throw a instanceof tv&&(this._metrics.recvTransportFailureCount+=1),l.error("Error in consume request",a),a}});try{let i=yield n(e);yield wr(s=>u(this,null,function*(){s>0&&l.warn(`retrying consumers: attempt: ${s}`,{peerIds:e.map(({producingPeerId:o})=>o)});const a=[];i.forEach((o,d)=>{if(o.status==="rejected"){this._metrics.consumerCreationFailureCount+=1,a.push(e[d]);return}this._initConsumer(o.value)}),a.length&&(i=yield n(a))}))}catch(i){l.error("failed to create consumers",{error:i}),this._metrics.consumerCreationFailureCount+=1,this.handleErrors("reconnectRecvTransport")}})}pauseProducer(e){return u(this,null,function*(){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.pause(),r.appData.e2ee&&b.emit(w.E2EE_INACTIVE_PRODUCER,r),l.info(`Paused the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})})}resumeProducer(e){return u(this,null,function*(){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.resume(),l.info(`Resumed the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})})}replaceTrack(e,r){return u(this,null,function*(){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}yield n.replaceTrack({track:r}),l.info(`Replaced track for the producer of type: ${n.kind}`,{producer:{id:n.id,kind:n.kind,appData:n.appData,trackId:r.id}})})}removeProducer(e,r){return u(this,null,function*(){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}r&&n.track.stop(),yield this.sendTransport.awaitQueue.push(n.close.bind(n),"producer").then(()=>{c(this,Wr).getValue("modules").e2ee.enabled&&b.emit(w.E2EE_INACTIVE_PRODUCER,n)}).catch(i=>{l.error("failed to close producer on server",i)})})}pauseConsumer(e){return u(this,null,function*(){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}this.toggleConsumerOverDC(e,!0),l.info(`Paused the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})})}pauseConsumerOverSocket(e){return u(this,null,function*(){try{const r={consumerId:e.id,pause:!0};yield this.socket.sendMessagePromise(oe.toggleConsumer,Go.toBinary(r)),e.pause(),b.emit(w.CONSUMER_PAUSED,{id:e.id}),l.info(`Paused the consumer of type: ${e.kind} over socket`,{consumer:{id:e.id,kind:e.kind,appData:e.appData}})}catch(r){l.error("error on pausing consumer",{error:r,consumer:{id:e.id,kind:e.kind,appData:e.appData}})}})}toggleConsumerOverDC(e,r){return u(this,null,function*(){const n={type:"consumer_toggle",payload:{consumerId:e,mute:r}},i=this._recvTransport.getDatachannel("events");if(!i){l.warn("recvTransport:: events datachannel not found");return}yield i.request(n),l.info(`HiveSFUHandler::consumer toggled, consumerId: ${e}, muted: ${r}`)})}resumeConsumer(e){return u(this,null,function*(){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}if(!r.paused){l.warn(`consumer with id:${e} is not paused so not resuming`);return}try{const n={consumerId:e,pause:!1};yield this.socket.sendMessagePromise(oe.toggleConsumer,Go.toBinary(n)),r.resume(),b.emit(w.CONSUMER_RESUMED,{id:r.id}),l.info(`Resumed the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})}catch(n){l.error("error on resuming consumer",n)}})}closeConsumer(e,r){return u(this,null,function*(){return this.closeConsumers([e],r)})}closeConsumers(e,r=!1){return u(this,null,function*(){l.info(`Closing consumers: ${JSON.stringify(e)} with force: ${r}`);let n=!0;const i=e.filter(o=>this._consumers.get(o)?!0:(l.warn(`consumer with id: ${o} not found`),!1));if(!i.length)return;const s={consumerIds:i},a=()=>u(this,null,function*(){var o;return(o=this._recvTransport)==null?void 0:o.awaitQueue.push(()=>u(this,null,function*(){yield this._socketHandler.closeConsumer(s)}),"close_consumer").catch(d=>{l.warn("error on closing consumer:",{error:d}),n=r})});r?a():yield a(),n&&i.forEach(o=>{const d=this.consumers.get(o);d&&(this.producerIdToConsumerIdMap.delete(d.producerId),d.close(r?"force closed":void 0))})})}cleanupConsumers(e){return u(this,null,function*(){l.debug("cleaning up all consumers");const r=[];this._consumers.forEach(n=>{e?n.peerId===e&&r.push(n.id):r.push(n.id)}),this.closeConsumers(r,!0)})}stopAllProducers(){return u(this,null,function*(){l.info("stopping all available producers"),this._producers.forEach((e,r)=>{l.debug(`closing producer type: ${r}`,{producer:{id:e==null?void 0:e.id,kind:e.kind,appData:e.appData}}),e.close()})})}getProducer(e){return Array.from(this.producers.values()).filter(r=>r.id===e).at(0)}hasProducer(e){return this.getProducer(e)!==void 0}negotiate(e,r){return u(this,null,function*(){l.debug(`setting remote offer : ${JSON.stringify(r)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}});const n=yield e.setRemoteOffer(r),i={transportId:e.serverId,description:{sdp:n.sdp,type:n.type,target:Ht.SUBSCRIBER}};return l.debug(`sending renegotiate request: ${JSON.stringify(i)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),yield this.socket.sendMessagePromise(oe.renegotiateSessionDescription,uf.toBinary(i)),l.info("renegotiation done",{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),n})}negotiateOverDC(e,r,n,i){return u(this,null,function*(){const{sdp:s}=e.payload,a={sdp:s,type:"offer"};try{l.debug(`got offer over dc: ${s} for transport: ${i.id}`);const o=yield i.setRemoteOffer(a),d={type:"answer",payload:{type:o.type,sdp:o.sdp}};l.debug(`datachannel answer: ${JSON.stringify(d)}`),i.sendResponseOverDC(n,r,d)}catch(o){l.error("datachannel:events::Error:",o),o.code!=="DC_NOT_FOUND"&&i.sendErrorOverDC(n,r,o)}})}handleConsumerToggle(e){const{mute:r,trackId:n}=e;l.info(`consumer toggled for trackId: ${n} muted: ${r}`);const i=this.consumers.get(n);if(!i){l.warn(`consumer with trackId: ${n} not found`);return}i.paused!==r&&(l.debug("consumer state is not same",{consumer:{id:i.id,remotelyPaused:i.paused}}),r?(i.pause(),b.emit(w.CONSUMER_PAUSED,{id:i.id})):(i.resume(),b.emit(w.CONSUMER_RESUMED,{id:i.id})))}handleErrorOverDC(e,r){return u(this,null,function*(){l.error(`got error over dc: ${JSON.stringify(e)} for transport: ${r}`);const{type:n,error:i,id:s}=e;switch(n){case"consumer":{this._metrics.consumerCreationFailureCount+=1,l.error(`Error in consumer creation, this should not happen: ${n}, ${i}, ${s}`);return}case"producer":{if(i==="ready-fail"){if(this._producerNotReadyFailureCount>=2){this.handleErrors("reconnectSendTransport");return}this._producerNotReadyFailureCount+=1,this._metrics.producerCreationFailureCount+=1;const[a]=Array.from(this.producers.entries()).find(o=>o[1].id===s);if(!a)return;yield this.removeProducer(a).catch(o=>{l.error("failed to remove ready-fail producer:",{error:o,producer:{id:s,kind:a,appData:null}})})}else i==="general-failure"&&this.handleErrors("reconnectSendTransport");l.error(`Unrecognized error: ${n}, ${i}, ${s}`);break}default:l.error(`Unrecognized error: ${n}, ${i}, ${s}`)}})}handleErrors(e){return u(this,null,function*(){switch(e){case"rejoin":{l.warn("rejoining room"),this.emit("rejoin");break}case"reconnectSendTransport":{l.warn("reconnecting send transport"),this.triggerTransportReconnection(this._sendTransport);break}case"reconnectRecvTransport":{this.triggerTransportReconnection(this._recvTransport);break}default:l.error(`Could not handle error, unrecognized action ${e}`)}})}triggerTransportReconnection(e){l.info("triggerTransportReconnection::reconnecting_transport",{transport:{type:e.direction,id:e.id,serverId:e.serverId}});const r=Q.hasFeature(ie.ENABLE_HIVE_TRANSPORT_RECONNECTION_ON_ICE_FAILED),n=Q.hasFeature(ie.HIVE_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED);if(!r)return;const i=e.direction==="send"?"sendTransportFailureCount":"recvTransportFailureCount";n&&this._socket.isConnected&&(this._metrics[i]>2&&(l.warn("Multiple disconnections, forcing relay"),this._iceTransportPolicy="relay"),this._metrics[i]+=1),this.updateTransportState({state:er.RECONNECTING,direction:e.direction}),this.emit("reconnect_transport",e)}switchConsumersToLayer(e,r){return u(this,null,function*(){const n=this._recvTransport.getDatachannel("events");if(!n){l.warn("events datachannel not found");return}const i={type:"switch_consumer_layer",payload:{consumerIds:e,layer:r}};yield n.request(i),l.info(`HiveSFUHandler::consumer id: ${e} layer switched to ${r}`)})}updateTransportState(e){const{state:r,direction:n}=e;r==="disconnected"&&(this.transportDisconnected[n]=!0),c(this,ds,Sa).mediaState[n]={state:r,reconnected:r==="connected"?this.transportDisconnected[n]:c(this,ds,Sa).mediaState[n].reconnected},r==="connected"&&(this.transportDisconnected[n]=!1),b.emit(w.TRANSPORT_STATE_UPDATE,U({transport:n},c(this,ds,Sa).mediaState[n]))}}ds=new WeakSet,Sa=function(){return c(this,Wr).getValue("connectionHandler")},Wr=new WeakMap;var k1=Object.defineProperty,_1=Object.getOwnPropertyDescriptor,me=(t,e,r,n)=>{for(var i=n>1?void 0:n?_1(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&k1(e,r,i),i},Ct,ge,$r,ls,gi,vi,Jc,Gc,qc,_n,Ea,Jr,bn,hv;const pv=(hv=class extends Zg{constructor(t,e){var r,n;super(),T(this,Jr),T(this,Ct,void 0),T(this,ge,void 0),T(this,$r,void 0),T(this,ls,void 0),T(this,gi,void 0),T(this,vi,void 0),T(this,Jc,void 0),T(this,Gc,void 0),T(this,qc,void 0),T(this,_n,void 0),T(this,Ea,void 0),f(this,"legacyMode"),f(this,"roomNodeUrl"),f(this,"peerDisplayName"),f(this,"e2ee"),f(this,"partialJoinRoomPromise"),this.context=t;const{roomName:i,authToken:s,legacyMode:a,socketClient:o,meetingTitle:d}=e;this.mediaJoined=!1,this.roomName=i,this.authToken=s,this.legacyMode=a,this.meetingTitle=d,S(this,Ct,o),S(this,$r,!1),S(this,ge,new T1(t,o)),this.maxPreferredStreams=6,S(this,_n,new Set),S(this,ls,!1),S(this,gi,0),S(this,vi,new as),this.e2ee=(n=(r=t.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?n:!1,$.legacySwitch(a),this.handleSocketEvents(),this.handleSFUEvents(),this.handleCallstatsEvents(),S(this,Jc,Mr(()=>u(this,null,function*(){if(!c(this,Jr,bn).mediaJoinAttempted)return;const{roomJoined:h}=yield this.joinRoom(this.peerDisplayName,this.roomUUID,{},!0,!0);h&&(b.emit(w.RESET_PRODUCER_STATE),b.emit(w.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3})),S(this,Gc,Mr(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports({send:!0}),l.info("send transport reconected!"),b.emit(w.RESET_PRODUCER_STATE)}),1e3)),S(this,qc,Mr(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports({recv:!0}),l.info("recv transport reconnected!"),b.emit(w.UPDATE_ACTIVE,{createAllConsumers:!0})}),1e3))}get mediaState(){return c(this,Jr,bn).mediaState}static init(t,e){return u(this,null,function*(){const{legacyMode:r=!0,meetingId:n,authToken:i,meetingTitle:s,socket:a}=e;return new pv(t,{legacyMode:r,authToken:i,socketClient:a,roomName:n,meetingTitle:s})})}get sfuHandler(){return c(this,ge)}get rejoinRoom(){return c(this,Jc)}get mediaJoined(){return c(this,Jr,bn).mediaJoined}set mediaJoined(t){c(this,Jr,bn).mediaJoined=t}reset(t=!0){var e,r,n,i;(r=(e=c(this,ge))==null?void 0:e.cleanupConsumers)==null||r.call(e),(i=(n=c(this,ge))==null?void 0:n.stopAllProducers)==null||i.call(n),c(this,_n).clear(),t&&(this.partialJoinRoomPromise=void 0,c(this,vi).stop(),c(this,ge).stopAllTransports(),c(this,ge).reset(),S(this,vi,new as))}reconnectTransport(t){return u(this,null,function*(){l.info(`HiveNodeClient::Room joining state: ${c(this,$r)}`),!(!t||c(this,$r))&&(t.direction==="send"?yield c(this,Gc).call(this,t):yield c(this,qc).call(this,t))})}setupTransports(){return u(this,null,function*(){yield c(this,ge).setupTransports({send:!0,recv:!0})})}stopAllProducers(){return u(this,null,function*(){yield c(this,ge).stopAllProducers()})}joinRoom(t,e){return u(this,arguments,function*(r,n,i={},s=!1,a=!1){c(this,Jr,bn).mediaJoinAttempted=!0,S(this,$r,!0),this.reset(s);const o=qe().ipInfo;if(o!=null&&o.loc&&!c(this,Ea)){const h=o.loc.split(",");S(this,Ea,{latitude:parseFloat(h[0]),longitude:parseFloat(h[1])})}let d;try{return d=yield c(this,vi).push(()=>this._joinRoom(r,n,i,a,c(this,Ea)),"joinRoom"),d}catch(h){d={roomJoined:!1}}return d.roomJoined||b.emit(w.ROOM_NODE_FAILED),d})}_partialJoinRoom(t,e,r=!1,n=void 0){return u(this,null,function*(){const{ipInfo:i}=qe();let s=n;if(i!=null&&i.loc&&!n){const[a,o]=i.loc.split(",").map(parseFloat);s={latitude:a,longitude:o}}this.maxPreferredStreams=this.context.getValue("maxPreferredStreams"),yield wr((a,o)=>u(this,null,function*(){if(!c(this,Ct).isConnected){o(new Error("socket is not connected"));return}a>0&&l.warn(`retrying sending join room request, count: ${a}`);try{yield this.sfuHandler.hiveSocketHandler.joinRoom(e,t,r,s)}catch(d){throw l.error("failed to send join room request, error:",{error:d}),d}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:Q.hasFeature(ie.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),yield this.setupTransports()})}partialJoinRoom(t,e,r=!1,n=void 0){return u(this,null,function*(){this.partialJoinRoomPromise=c(this,vi).push(()=>this._partialJoinRoom(t,e,r,n))})}_joinRoom(t,e){return u(this,arguments,function*(r,n,i={},s=!1,a=null){this.peerDisplayName=r;try{this.partialJoinRoomPromise?yield this.partialJoinRoomPromise:yield this._partialJoinRoom(r,n,s,a)}catch(o){l.error("error in partial join room",{error:o})}finally{this.partialJoinRoomPromise=void 0}try{return navigator.product!=="ReactNative"&&setTimeout(()=>u(this,null,function*(){const o={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:n,roomViewType:"groupCall",deviceInfo:X(U({},Te.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};$.roomJoined(o)})),{roomJoined:yield this.completeJoinRoom()}}catch(o){return l.error("error on sending join room request",{error:o}),{roomJoined:!1}}})}completeJoinRoom(){return u(this,null,function*(){try{this.mediaJoined=!0;const{maxPreferredStreams:t,roomState:e}=yield this.sfuHandler.hiveSocketHandler.notifySelfJoinComplete();return this.roomUUID=e.roomUuid,S(this,ls,!0),S(this,$r,!1),this.maxPreferredStreams=t!=null?t:6,!0}catch(t){return l.error("error on completing join room:",{error:t}),this.mediaJoined=!1,!1}})}leaveRoom(){return u(this,null,function*(){c(this,ge).stopAllTransports(),S(this,ls,!1),c(this,Jr,bn).mediaJoinAttempted=!1;const t={closeRoom:!1};c(this,Ct).sendMessagePromise(oe.leaveRoom,yf.toBinary(t)).then(e=>{var r;(r=Rf.fromBinary(e.payload))!=null&&r.closed||l.warn("weird state on peer closed and should not happen")}).catch(e=>{l.error("error on sending leave room request",{error:e})}),$.callEnded(),y.destruct()})}getConsumers(){return c(this,ge).consumers}activatePeers(t){return u(this,null,function*(){return this.createConsumers(t)})}deactivatePeers(t,e="default"){return u(this,null,function*(){const r=new Set;t.forEach(i=>{i.screenShare&&i.kind==="video"&&r.add(i.producingPeerId)});const n=e==="default"?t.filter(i=>!r.has(i.producingPeerId)).filter(i=>i.kind!=="audio"):t;yield Promise.all(n.map(i=>{const s=this.sfuHandler.producerIdToConsumerIdMap.get(i.producerId);if(!s){l.warn(`consumer not found in deactivate producers: ${i.producerId}`);return}return this.sfuHandler.closeConsumer(s)}))})}createConsumers(t){return u(this,null,function*(){return t.length===0?Promise.resolve():this.sfuHandler.createConsumers(t)})}pauseConsumers(t){return u(this,null,function*(){t.forEach(e=>{this.sfuHandler.pauseConsumer(e)})})}resumeConsumers(t){return u(this,null,function*(){t.forEach(e=>{this.sfuHandler.resumeConsumer(e)})})}closeConsumers(t){return u(this,null,function*(){const e=t.reduce((r,n)=>{const i=this.sfuHandler.producerIdToConsumerIdMap.get(n.producerId);return i?(r.push(i),r):(l.warn(`consumer not found in deactivate producers: ${n.producerId}`),r)},[]);yield this.sfuHandler.closeConsumers(e)})}shareWebcam(t){return u(this,null,function*(){var e;if(t===void 0)return null;if(c(this,ge).producers.has(ne.WEBCAM)){const i=c(this,ge).producers.get(ne.WEBCAM);if(!i.closed&&!navigator.isReactNative)return yield i.replaceTrack({track:t}),yield this.resumeWebcam(),t;yield c(this,ge).removeProducer(ne.WEBCAM)}const r={track:t,codecOptions:{name:"VP8"},appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1};if(!Ho(this.context,"disableSimulcast")&&Q.hasFeature(ie.ENABLE_HIVE_SIMULCAST)){let i=t.getConstraints().width;i in Vg||(i=320),r.encodings=Vg[i],((e=r.encodings)==null?void 0:e.length)===1&&l.info("Simulcast will not be used for the webcam producer")}else l.info("Simulcast will not be used for the webcam producer");const n=()=>{l.info("Disabling video due to the producer closure"),this.disableWebcam()};return c(this,ge).createProducer(ne.WEBCAM,r,n)})}shareScreen(t){return u(this,null,function*(){const{video:e,audio:r}=t;if(e===void 0)return;const n={track:e,codecOptions:{name:"VP8"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1};let i=()=>{l.info("Disabling screenShare due to the producer closure"),this.disableScreenShare()};if(yield c(this,ge).createProducer(ne.SCREENSHARE_VIDEO,n,i),r){const s={track:r,codecOptions:{name:"opus"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1,zeroRtpOnPause:!0};i=()=>{},yield c(this,ge).createProducer(ne.SCREENSHARE_AUDIO,s,i)}$.screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new et("track undefined");if(c(this,ge).producers.has(ne.MIC)){const n=c(this,ge).producers.get(ne.MIC);if(!n.closed&&!navigator.isReactNative){yield n.replaceTrack({track:t}),yield this.resumeMic();return}yield c(this,ge).removeProducer(ne.MIC,!1)}const e={track:t,encodings:[{priority:"high"}],codecOptions:{name:"opus"},appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!0},r=()=>{l.info("Disabling audio due to the producer closure"),this.disableMic()};yield c(this,ge).createProducer(ne.MIC,e,r)}catch(e){throw new _(e)}})}pauseMic(){const t=c(this,ge).producers.get(ne.MIC);if(!t){l.error("pauseMic::could_not_find_mic_producer");return}if(t.paused){l.info("pauseMic::mic_producer_already_paused");return}t.pause();const e={producerId:t.id,pause:!0};c(this,Ct).sendMessage(oe.toggleProducer,pn.toBinary(e))}pauseWebcam(){return u(this,null,function*(){const t=c(this,ge).producers.get(ne.WEBCAM);if(!t){l.error("pauseWebcam::could_not_find_webcam_producer");return}t.pause();const e={producerId:t.id,pause:!0};c(this,Ct).sendMessage(oe.toggleProducer,pn.toBinary(e))})}resumeMic(){return u(this,null,function*(){const t=c(this,ge).producers.get(ne.MIC);if(!t){l.error("resumeMic::could_not_find_mic_producer");return}if(!t.pause){l.info("resumeMic::mic_producer_already_resumed");return}t.resume(),t.appData.e2ee&&b.emit(w.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,Ct).sendMessage(oe.toggleProducer,pn.toBinary(e))})}resumeWebcam(){return u(this,null,function*(){const t=c(this,ge).producers.get(ne.WEBCAM);if(!t){l.error("resumeWebcam::could_not_find_webcam_producer");return}t.resume(),t.appData.e2ee&&b.emit(w.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,Ct).sendMessage(oe.toggleProducer,pn.toBinary(e))})}disableWebcam(){return u(this,null,function*(){yield c(this,ge).removeProducer(ne.WEBCAM)})}disableMic(){return u(this,null,function*(){yield c(this,ge).removeProducer(ne.MIC)})}disableScreenShare(){return u(this,null,function*(){l.info("screen_sharing_stopped"),$.screenShareStop(),yield c(this,ge).removeProducer(ne.SCREENSHARE_VIDEO),yield c(this,ge).removeProducer(ne.SCREENSHARE_AUDIO),c(this,_n).clear()})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}unmuteSelf(){return u(this,null,function*(){})}resetVideoProducers(t,e){return u(this,null,function*(){t&&(yield c(this,ge).removeProducer(ne.WEBCAM,!1),this.shareWebcam(t)),e&&(yield c(this,ge).removeProducer(ne.SCREENSHARE_VIDEO,!1),this.shareScreen({video:e}))})}changeDisplayName(t,e){return u(this,null,function*(){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!(yield this.sfuHandler.hiveSocketHandler.changeDisplayName(r)))throw new Error("failed to change display name!")})}kick(t){return u(this,null,function*(){const e={participantId:t};if(!(yield this.sfuHandler.hiveSocketHandler.kickPeer(e)))throw new Error("failed to kickout the participant!")})}kickAll(){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.kickAll()))throw new Error("failed to kickout all participant!")})}muteAll(t){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.hostControlForPeer(t,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(t){return u(this,null,function*(){const e={participantId:t!=null?t:""};try{yield c(this,Ct).sendMessagePromise(oe.globalPinPeer,Ef.toBinary(e))}catch(r){l.error("Error in pinning peer:",{error:r})}})}validateScreenShare(t){return this.peerId===t.peerId&&this.sfuHandler.hasProducer(t.producerId)&&c(this,_n).add(t.consumerPeerId),c(this,_n).size}switchConsumersToLayer(t,e){return u(this,null,function*(){this.sfuHandler.switchConsumersToLayer(t,e)})}handleSocketEvents(){return u(this,null,function*(){c(this,Ct).on(oe.peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:r}=Bf.fromBinary(t);if(e===this.peerId)return;l.info(`producer created broadcast: ${e}, producer state: ${r}`),b.emit(w.NEW_PRODUCER,{peerId:e,producer:X(U({},r),{kind:r.kind===Lt.AUDIO?"audio":"video",producingPeerId:e})})}catch(e){l.error("error in peer-producer-create-broadcast",{error:e})}}),c(this,Ct).on(oe.peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:r,producerState:{kind:n,pause:i,producerId:s}}=Cl.fromBinary(t),a=n===Lt.AUDIO?"audio":"video";if(l.info(`producer toggle broadcast: ${e}, producerId: ${s}, kind:${a}, paused:${i}, payload: ${JSON.stringify(Cl.fromBinary(t))}`),e===this.peerId&&r!==this.peerId&&i&&b.emit(a==="audio"?w.MUTE_SELF:w.MUTE_SELF_VIDEO),e===this.peerId)return;b.emit(w.PRODUCER_TOGGLE,{peerId:e,producerId:s,paused:i,kind:a}),Array.from(this.getConsumers().values()).filter(o=>o.producerId===s).forEach(o=>{o.paused!==i&&(l.debug(`consumer state mismatched for ${o.id}. updating consumer pause state ${o.paused} to ${i}`),i?(o.pause(),b.emit(w.CONSUMER_PAUSED,{id:o.id})):(o.resume(),b.emit(w.CONSUMER_RESUMED,{id:o.id})))})}catch(e){l.error("error in producer toggle broadcast handler",{error:e})}}),c(this,Ct).on(oe.peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=zo.fromBinary(t);if(e===this.peerId)return;l.info(`peer left broadcast:${e}`),c(this,_n).delete(e),this.sfuHandler.cleanupConsumers(e),b.emit(w.PEER_CLOSED,{id:e})}catch(e){l.error("error in peer left broadcast",{error:e})}}),c(this,Ct).on(oe.peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=jf.fromBinary(t);if(e===this.peerId)return;l.info(`producer closed broadcast:${e}`),b.emit(w.PRODUCER_CLOSED,{peerId:e,producerId:r});const n=this.sfuHandler.producerIdToConsumerIdMap.get(r);if(!n){l.warn(`no consumer found for producer:${r}`);return}l.info(`closing consumer ${n}, producer id: ${r}`),this.sfuHandler.closeConsumer(n).then(()=>{l.info(`closed consumer: ${n}`),this.sfuHandler.producerIdToConsumerIdMap.delete(r),b.emit(w.CONSUMER_CLOSED,{id:n})}).catch(i=>{l.error("error closing consumer",{error:i})})}catch(e){l.error("error on producer close broadcast",{error:e})}}),c(this,Ct).on(oe.mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!c(this,$r)&&!c(this,ls)||(l.warn("media hub termination broadcast received, rejoining room"),b.emit(w.ROOM_NODE_DISCONNECTED),this.rejoinRoom())})})}handleSFUEvents(){c(this,ge).on("reconnect_transport",t=>u(this,null,function*(){try{yield this.reconnectTransport(t),l.info(`transport reconnected [id:${t.id}]`)}catch(e){l.error("error on reconnection transports",{error:e})}})),c(this,ge).on("rejoin",t=>{var e;if(((e=c(this,Jr,bn).socketState)==null?void 0:e.state)!=="connected"){l.warn("Ignoring rejoin attempt because socket is not connected");return}if(c(this,gi)>3&&!t){l.warn("cannot rejoin more already rejoined 3 times");return}if(c(this,$r)&&!t){l.warn("room joining in progress, cannot start rejoining");return}S(this,gi,c(this,gi)+1),l.warn(`rejoining the room because transports are failing. [rejoinCount: ${c(this,gi)}]`),this.mediaJoined=!1,b.emit(w.ROOM_NODE_DISCONNECTED),this.rejoinRoom()})}handleCallstatsEvents(){$.onConsumerScore(t=>{t.forEach((e,r)=>{const n=this.sfuHandler.consumers.get(r);n&&b.emit(w.CONSUMER_SCORE_UPDATE,{id:r,kind:n.kind,peerId:n.peerId,score:e.score,scoreStats:e})})}),$.onProducerScore(t=>{t.forEach((e,r)=>{const n=Array.from(this.sfuHandler.producers.values()).find(i=>i.id===r);n&&b.emit(w.PRODUCER_SCORE_UPDATE,{id:r,kind:n.kind,appData:n.appData,score:e.score,scoreStats:e})})})}},Ct=new WeakMap,ge=new WeakMap,$r=new WeakMap,ls=new WeakMap,gi=new WeakMap,vi=new WeakMap,Jc=new WeakMap,Gc=new WeakMap,qc=new WeakMap,_n=new WeakMap,Ea=new WeakMap,Jr=new WeakSet,bn=function(){return this.context.getValue("connectionHandler")},hv);let le=pv;me([y.trace("HiveNodeClient.reset",{country:y.location.country})],le.prototype,"reset",1),me([y.trace("HiveNodeClient.reconnect",{country:y.location.country})],le.prototype,"reconnectTransport",1),me([y.trace("HiveNodeClient.setupTransport")],le.prototype,"setupTransports",1),me([y.trace("HiveNodeClient.stopAllProducers")],le.prototype,"stopAllProducers",1),me([y.trace("HiveNodeClient.joinRoom")],le.prototype,"joinRoom",1),me([y.trace("HiveNodeClient.completeJoinRoom")],le.prototype,"completeJoinRoom",1),me([y.trace("HiveNodeClient.leaveRoom")],le.prototype,"leaveRoom",1),me([y.trace("HiveNodeClient.activatePeers")],le.prototype,"activatePeers",1),me([y.trace("HiveNodeClient.deactivatePeers")],le.prototype,"deactivatePeers",1),me([y.trace("HiveNodeClient.createConsumers")],le.prototype,"createConsumers",1),me([y.trace("HiveNodeClient.pauseConsumers")],le.prototype,"pauseConsumers",1),me([y.trace("HiveNodeClient.resumeConsumers")],le.prototype,"resumeConsumers",1),me([y.trace("HiveNodeClient.closeConsumers")],le.prototype,"closeConsumers",1),me([y.trace("HiveNodeClient.shareWebcam")],le.prototype,"shareWebcam",1),me([y.trace("HiveNodeClient.shareScreen")],le.prototype,"shareScreen",1),me([y.trace("HiveNodeClient.shareMic")],le.prototype,"shareMic",1),me([y.trace("HiveNodeClient.pauseMic")],le.prototype,"pauseMic",1),me([y.trace("HiveNodeClient.pauseWebcam")],le.prototype,"pauseWebcam",1),me([y.trace("HiveNodeClient.resumeMic")],le.prototype,"resumeMic",1),me([y.trace("HiveNodeClient.resumeWebcam")],le.prototype,"resumeWebcam",1),me([y.trace("HiveNodeClient.disableWebcam")],le.prototype,"disableWebcam",1),me([y.trace("HiveClient.disableMic")],le.prototype,"disableMic",1),me([y.trace("HiveClient.disableScreenShare")],le.prototype,"disableScreenShare",1),me([y.trace("HiveNodeClient.muteSelf")],le.prototype,"muteSelf",1),me([y.trace("HiveNodeClient.resetVideoProducers")],le.prototype,"resetVideoProducers",1),me([y.trace("HiveNodeClient.changeDisplayName")],le.prototype,"changeDisplayName",1),me([y.trace("HiveNodeClient.kickPeer")],le.prototype,"kick",1),me([y.trace("HiveNodeClient.kickAllPeers")],le.prototype,"kickAll",1),me([y.trace("HiveNodeClient.muteAll")],le.prototype,"muteAll",1),me([y.trace("HiveNodeClient.muteAllVideo")],le.prototype,"muteAllVideo",1),me([y.trace("HiveNodeClient.disableAudio")],le.prototype,"disableAudio",1),me([y.trace("HiveNodeClient.disableVideo")],le.prototype,"disableVideo",1),me([y.trace("HiveNodeClient.pinPeer")],le.prototype,"pinPeer",1),me([y.trace("HiveNodeClient.validateScreenShare")],le.prototype,"validateScreenShare",1),me([y.trace("HiveNodeClient.init")],le,"init",1);class b1{constructor(){f(this,"_orderedArray"),f(this,"_map"),this._map=new Map,this._orderedArray=[]}add(e,r){if(!this._map.has(e))return this._map.set(e,{peerId:e,priority:r}),this._orderedArray.splice(Math.max(r-1,0),0,e),this.index(e);const n=this.index(e);this.delete(e);const i=this.add(e,r);return n!==i?i:-1}delete(e){if(this._map.has(e)){const r=this.index(e);this._map.delete(e),this._orderedArray.splice(r,1)}}index(e){return this._map.has(e)?this._orderedArray.indexOf(e):-1}[Symbol.iterator](){return this._orderedArray[Symbol.iterator]()}}class w1{constructor(){f(this,"_activeSpeakerPeers"),f(this,"_compulsoryPeers"),this._activeSpeakerPeers=new b1,this._compulsoryPeers=new Set}add(e,r){if(!e)return-1;if(r<0)return this._compulsoryPeers.add(e),0;if(this.compulsoryPeers.includes(e)&&(r>0||r===246267631)){if(l.info("DyteSelectedPeer::removing_compulsory_peer",{selectedPeer:{peerId:e}}),this._removeFromCompulsoryPeer(e),r===246267631)return-1}else if(r===229490415)return this.delete(e),-1;return this._activeSpeakerPeers.add(e,r)}delete(e){l.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 mv=new w1;var I1=Object.defineProperty,C1=Object.getOwnPropertyDescriptor,Gt=(t,e,r,n)=>{for(var i=n>1?void 0:n?C1(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&I1(e,r,i),i};const P1=["ACTIVE_GRID","PAGINATED","MANUAL"];var Gr,qr,wn,us,qt,fv;let Pt=(fv=class extends jt{constructor(t,e,r){super(),T(this,qr),f(this,"waitlisted"),f(this,"joined"),f(this,"active"),f(this,"videoSubscribed"),f(this,"audioSubscribed"),f(this,"pinned"),f(this,"all"),T(this,Gr,void 0),T(this,us,void 0),T(this,qt,void 0),f(this,"rateLimitConfig",{maxInvocations:5,period:1}),f(this,"viewMode"),f(this,"currentPage"),f(this,"lastActiveSpeaker"),f(this,"selectedPeers",mv),S(this,Gr,t),S(this,us,e),S(this,qt,r),this.waitlisted=new ga,this.joined=new ga,this.videoSubscribed=new ga,this.audioSubscribed=new ga,this.active=this.videoSubscribed,this.pinned=new ga,this.all=new r1,this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return c(this,Gr).getValue("pip")}get socketJoined(){var t;return((t=c(this,Gr).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0}get mediaJoined(){var t;return((t=c(this,Gr).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}setupEvents(){b.on(w.E2EE_ACTIVE_CONSUMER,({peerId:t})=>{var e;((e=c(this,Gr).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(){return c(this,qr,wn).maxPreferredStreams}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new _("0 <= Max active participants count limit <= 24","1203");c(this,qr,wn).maxPreferredStreams=t,this.mediaJoined&&b.emit(w.UPDATE_ACTIVE)}get pageCount(){if(this.viewMode==="PAGINATED"){const t=this.selectedPeers.compulsoryPeers.length,e=this.joined.toArray().filter(r=>r.stageStatus==="ON_STAGE");return Math.ceil((e.length-t)/(this.maxActiveParticipantsCount-t))}return 0}acceptWaitingRoomRequest(t){var e,r;if(!this.socketJoined)throw new _("Can`t accept waiting room request without joining room","1205");const n=(r=(e=this.waitlisted.get(t))==null?void 0:e.userId)!=null?r:t;return c(this,qt).acceptWaitingRoomRequest([n])}acceptAllWaitingRoomRequest(t){return u(this,null,function*(){const e=t.map(r=>{var n,i;return(i=(n=this.waitlisted.get(r))==null?void 0:n.userId)!=null?i:r});return c(this,qt).acceptWaitingRoomRequest(e)})}rejectWaitingRoomRequest(t){return u(this,null,function*(){var e,r;if(!this.socketJoined)throw new _("Can`t reject waiting room request without joining room","1205");const n=(r=(e=this.waitlisted.get(t))==null?void 0:e.userId)!=null?r:t;c(this,qt).rejectWaitingRoomRequest([n])})}setViewMode(t){return u(this,null,function*(){if(l.info("DyteParticipants::set_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),!(e=>P1.includes(e))(t))throw l.error("DyteParticipants::setViewMode::invalid_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),new _(`Invalid view mode: ${t}. Try ACTIVE_GRID, PAGINATED or MANUAL.`,"1207");if(this.viewMode===t){l.info("DyteParticipants::setViewMode::view_mode_same_as_previous");return}if(t==="MANUAL"&&!(c(this,qr,wn)instanceof le))throw new _("Manual Subscription is not enabled for your Organization. Please contact support.","1208");this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,b.emit(w.UPDATE_ACTIVE,{page:this.currentPage})):t==="ACTIVE_GRID"&&(this.currentPage=0,b.emit(w.UPDATE_ACTIVE)),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})})}subscribe(t){return u(this,arguments,function*(e,r=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new _("MANUAL subscription mode was not activated.","1206");const n=[];e.forEach(i=>{const s=this.joined.get(i);if(s){if(r.includes("audio")){s.manualProducerConfig=X(U({},s.manualProducerConfig),{audio:!0}),this.videoSubscribed.add(s);const a=s.producers.find(o=>o.kind==="audio"&&!o.screenShare);a&&n.push(a)}if(r.includes("video")){s.manualProducerConfig=X(U({},s.manualProducerConfig),{video:!0}),this.audioSubscribed.add(s);const a=s.producers.find(o=>o.kind==="video"&&!o.screenShare);a&&n.push(a)}if(r.includes("screenshareAudio")){s.manualProducerConfig=X(U({},s.manualProducerConfig),{screenshareAudio:!0});const a=s.producers.find(o=>o.kind==="audio"&&o.screenShare);n.push(a)}if(r.includes("screenshareVideo")){s.manualProducerConfig=X(U({},s.manualProducerConfig),{screenshareVideo:!0});const a=s.producers.find(o=>o.kind==="video"&&o.screenShare);n.push(a)}}}),yield c(this,qr,wn).createConsumers(n)})}unsubscribe(t){return u(this,arguments,function*(e,r=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new _("MANUAL subscription mode was not activated.","1206");const n=[];e.forEach(i=>{const s=this.joined.get(i);if(s){if(r.includes("audio")){s.manualProducerConfig=X(U({},s.manualProducerConfig),{audio:!1});const a=s.producers.find(o=>o.kind==="audio"&&!o.screenShare);a&&n.push(a)}if(r.includes("video")){s.manualProducerConfig=X(U({},s.manualProducerConfig),{video:!1});const a=s.producers.find(o=>o.kind==="video"&&!o.screenShare);a&&n.push(a)}if(r.includes("screenshareAudio")){s.manualProducerConfig=X(U({},s.manualProducerConfig),{screenshareAudio:!1});const a=s.producers.find(o=>o.kind==="audio"&&o.screenShare);n.push(a)}if(r.includes("screenshareVideo")){s.manualProducerConfig=X(U({},s.manualProducerConfig),{screenshareVideo:!1});const a=s.producers.find(o=>o.kind==="video"&&o.screenShare);n.push(a)}}}),yield c(this,qr,wn).closeConsumers(n)})}getPeerIdsForCurrentPage(){l.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)),r=Array.from(this.pinned.keys()).filter(a=>!e.includes(a)),n=Array.from(this.joined.toArray().filter(a=>a.stageStatus==="ON_STAGE").map(a=>a.id)),i=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-r.length)),s=this.currentPage*(this.maxActiveParticipantsCount-e.length-r.length);return e.concat(r,n.slice(i,s))}setPage(t){return u(this,null,function*(){if(l.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 l.error("DyteParticipants::invalid_page_number"),new _(`Invalid page: ${t}. Page must be an integer and greater than 0 and less than or equal to .pageCount`,"1202");this.currentPage=t,b.emit(w.UPDATE_ACTIVE,{page:t}),this.emit("pageChanged",{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount})}})}disableAllAudio(t){return u(this,null,function*(){if(l.info("DyteParticipants::disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),!this.mediaJoined)throw new _("Can`t disable all audio without joining room","1205");if(c(this,us).permissions.canAllowParticipantAudio)return c(this,qr,wn).muteAll(t);throw l.error("DyteParticipants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new _("Unauthorized: User does not have permission to disable peer audio.","1201")})}disableAllVideo(){return u(this,null,function*(){if(l.info("DyteParticipants::disable_all_video"),!this.mediaJoined)throw new _("Can`t disable all video without joining room","1205");if(c(this,us).permissions.canAllowParticipantVideo)return c(this,qr,wn).muteAllVideo();throw l.error("DyteParticipants::unauthorized_disable_all_video"),new _("Unauthorized: User does not have permission to disable peer video.","1201")})}disableAudio(t){return u(this,null,function*(){this.joined.get(t).disableAudio()})}disableVideo(t){return u(this,null,function*(){this.joined.get(t).disableVideo()})}kick(t){return u(this,null,function*(){yield b.emitAsync(w.KICK_PEER,{peerId:t})})}kickAll(){return u(this,null,function*(){if(l.info("DyteParticipants::kick_all"),c(this,Gr).getValue("viewType")!=="LIVESTREAM"&&!this.socketJoined)throw new _("Can`t kick all without joining room","1205");if(!c(this,us).permissions.kickParticipant)throw l.error("DyteParticipants::unauthorized_kick_all"),new _("Unauthorized: User does not have permission to kick peers.","1201");const t=Q.hasFeature(ie.PROPAGATE_KICK_ALL);c(this,qt).kickAll(t)})}broadcastMessage(t,e,r){return u(this,null,function*(){if(l.info("DyteParticipants::broadcastMessage"),!this.socketJoined)throw new _("Can`t broadcast message without joining room","1205");if(!(t!=null&&t.trim()))throw new _("`type` must be a non-empty string.","1209");if(r)if("meetingIds"in r)yield c(this,qt).broadcastToMeetings(t,r.meetingIds,e);else{let n=[];"participantIds"in r?n=r.participantIds:n=this.joined.toArray().filter(i=>{var s;return(s=r.presetNames)==null?void 0:s.includes(i.presetName)}).map(i=>i.id),yield c(this,qt).broadcastToPeers(t,n,e)}else yield c(this,qt).broadcastMessage(t,e)})}getAllJoinedPeers(t,e,r){return u(this,null,function*(){return(yield c(this,qt).getRoomPeers(t,e,r)).peers.map(zr.formatSocketServiceMessage)})}updatePermissions(t,e){return u(this,null,function*(){const r=this.joined.toArray().filter(i=>t.includes(i.id)).map(i=>i.userId),n=[...new Set(r)];if(!n.length)throw new _("Cannot update permissions, no valid userIDs found","1204");c(this,qt).updatePermissions(n,e)})}getParticipantsInMeetingPreJoin(){return u(this,null,function*(){return c(this,qt).getRoomPeersNonPaginated()})}},Gr=new WeakMap,qr=new WeakSet,wn=function(){return c(this,Gr).getValue("roomNodeClient")},us=new WeakMap,qt=new WeakMap,fv);Gt([y.trace("DyteParticipants.setViewMode")],Pt.prototype,"setViewMode",1),Gt([y.trace("DyteParticipants.setPage")],Pt.prototype,"setPage",1),Gt([y.trace("DyteParticipants.disableAllAudio")],Pt.prototype,"disableAllAudio",1),Gt([y.trace("DyteParticipants.disableAllVideo")],Pt.prototype,"disableAllVideo",1),Gt([y.trace("DyteParticipants.disablePeerAudio")],Pt.prototype,"disableAudio",1),Gt([y.trace("DyteParticipants.disablePeerVideo")],Pt.prototype,"disableVideo",1),Gt([y.trace("DyteParticipants.kickPeer")],Pt.prototype,"kick",1),Gt([y.trace("DyteParticipants.kickAll")],Pt.prototype,"kickAll",1),Gt([y.trace("DyteParticipants.broadcastMessage"),xt(Ui,"rateLimitConfig")],Pt.prototype,"broadcastMessage",1),Gt([y.trace("DyteParticipants.getAllJoinedPeers"),xt({maxInvocations:10,period:60})],Pt.prototype,"getAllJoinedPeers",1),Gt([y.trace("DyteParticipant.updatePermissions"),xt({maxInvocations:1e3,period:60})],Pt.prototype,"updatePermissions",1),Gt([y.trace("DyteParticipants.getParticipantsInMeetingPreJoin")],Pt.prototype,"getParticipantsInMeetingPreJoin",1),Pt=Gt([vt("1200")],Pt);var R1=Object.defineProperty,A1=Object.getOwnPropertyDescriptor,hs=(t,e,r,n)=>{for(var i=n>1?void 0:n?A1(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&R1(e,r,i),i};const gv=class{constructor(t,e,r){f(this,"participants"),f(this,"self"),f(this,"selectedPeers",mv),f(this,"maxSpatialLayerUpdates",new Map),f(this,"consumerPeerMap"),f(this,"roomSocketHandler"),f(this,"context"),f(this,"videoPeerConsumerMap",new Map),f(this,"updateConsumerSpatialLayers",Mr(()=>{const n={},i=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(i.entries()).forEach(([s,a])=>{n[a]===void 0&&(n[a]={layer:a,consumerIds:[]}),n[a].consumerIds.push(s)}),Object.keys(n).forEach(s=>{const a=n[s];l.log(`Switching max spatial layer to ${a.layer}`,{consumerIds:a.consumerIds}),this.roomNodeClient.switchConsumersToLayer(a.consumerIds,a.layer)})},2e3)),f(this,"updateConsumers",(n,i)=>{l.info("Consuming producers",{producers:n}),l.info("Closing consumers for producers",{producers:i}),this.roomNodeClient.closeConsumers(i).then(()=>{this.roomNodeClient.createConsumers(n).catch(s=>l.error("Error activating peers",{error:s}))}).catch(s=>l.error("Error deactivating peers",{error:s}))}),f(this,"updateConsumersDebounced",Mr(this.updateConsumers,200,{trailing:!0})),this.context=t,this.roomSocketHandler=r,this.participants=new Pt(t,e,this.roomSocketHandler),this.self=e,this.consumerPeerMap=new Map,e.config.viewType!=="CHAT"&&this.setupEventsGlobal()}get mediaJoined(){var t;return((t=this.roomNodeClient)==null?void 0:t.mediaJoined)===!0}get pip(){return this.context.getValue("pip")}waitingRoomRequestHandler(t){const e=t.requests.filter(n=>!this.participants.waitlisted.toArray().find(i=>i.userId===n.userId)),r=this.participants.waitlisted.toArray().filter(n=>!t.requests.find(i=>i.userId===n.userId));e.forEach(n=>this.participants.waitlisted.add(new Br(this.context,{id:n.peerId,displayName:n.displayName,audioMuted:!0,videoEnabled:!1,audioTrack:void 0,videoTrack:void 0,stageStatus:"OFF_STAGE",userId:n.userId,flags:{},isHost:!1,customParticipantId:n.customParticipantId,picture:n.picture,metadata:{preset_name:n.presetName}},this.self,this.roomSocketHandler))),r.forEach(n=>this.participants.waitlisted.delete(n.id))}get maxPreferredStreams(){return this.participants.maxActiveParticipantsCount}selectPagePeers(t){return u(this,null,function*(){const{compulsoryPeers:e}=this.selectedPeers,r=e.filter(o=>this.participants.joined.has(o)),n=Array.from(this.participants.pinned.keys()).filter(o=>!r.includes(o)),i=Array.from(this.participants.joined.toArray().filter(o=>o.stageStatus==="ON_STAGE").map(o=>o.id)),s=Math.max((t-1)*(this.roomNodeClient.maxPreferredStreams-r.length-n.length)),a=t*(this.roomNodeClient.maxPreferredStreams-r.length-n.length);return r.concat(n,i.slice(s,a))})}selectActivePeers(){return u(this,null,function*(){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))),r=this.selectedPeers.peers,n=this.participants.pinned.toArray().reduce((h,p)=>(p.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(p.id):h.push(p.id),h),[]),i=this.self.stageStatus==="ON_STAGE"?1:0,s=this.participants.maxActiveParticipantsCount-i,a=new Set(r.concat(n).filter(h=>h!==this.self.id&&t.has(h)));let o=Array.from(a);const d=s-a.size;if(d>=0){const h=e.filter(p=>!a.has(p)&&p!==this.self.id).slice(0,d);o=Array.from(a).concat(h)}else o=o.slice(0,s);return o})}updateActive(t,e){return u(this,null,function*(){const{page:r,createAllConsumers:n}=e!=null?e:{};let{strategies:i}=e!=null?e:{},s,a;switch(t){case"PAGINATED":{if(!r)return;s=yield this.selectPagePeers(r),l.debug("ParticipantController::updateActive::updating_current_page_peers",{peerIds:s}),i!=null||(i={video:this.updateParticipantsMap.bind(this)}),a=this.updateConsumersDebounced;break}case"ACTIVE_GRID":{s=yield this.selectActivePeers(),l.debug("ParticipantController::updateActive::updating_current_selected_peers",{peerIds:s}),i!=null||(i={video:this.updateParticipantsMapMinReplacement.bind(this),audio:this.updateParticipantsMap.bind(this)}),a=this.updateConsumers;break}default:throw new Error(`View mode ${t} not supported`)}let o,d;const h=this.updateGrid(s,i);n?(o=this.mapPeerIdsToProducers(s,["audio","video","screenshare"]),d=[]):(o=[...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"])]),!(o.length===0&&d.length===0)&&a(o,d)})}computeActivateParticipants(t,e){const r=t.map((i,s)=>({peerId:i,priority:s+1})),n=e==null?void 0:e.map((i,s)=>({peerId:i,priority:-(s+1)}));r.push(...n!=null?n:[]),r.length>0&&this.updateActiveParticipantsWithPriorities(r)}fromSocketService(t){const e=gv.formatSocketServiceMessage(t);return new Br(this.context,X(U({},e),{isHost:!1,videoEnabled:!1,audioMuted:!0,videoTrack:void 0,audioTrack:void 0}),this.self,this.roomSocketHandler)}updatePipSource(t,e){var r,n;e?(r=this.pip)==null||r.enableSource(t):(n=this.pip)==null||n.disableSource(t)}onMediaJoined(t,e){if(!this.mediaJoined||t===this.self.id)return;const r=this.participants.joined.get(t);if(!r){l.warn(`Recieved media.peerJoinedBroadcast for non-existent peer ${t}`);return}e.forEach(n=>{n.kind===Lt.AUDIO&&!n.screenShare?r.setAudioEnabled(!n.pause):n.kind===Lt.VIDEO&&!n.screenShare&&(r.setVideoEnabled(!n.pause),this.updatePipSource(r.id,!n.pause)),r.producers.push(X(U({},n),{producingTransportId:n.producingTransportId,kind:n.kind===Lt.AUDIO?"audio":"video",producingPeerId:t}))})}updateParticipantsMapMinReplacement(t,e){const r=Array.from(t.keys()),n=new Map(t),i=[],s=[],a=new Set(e),o=[];return r.forEach((d,h)=>{(!a.has(d)||!this.participants.joined.get(d))&&o.push(h)}),e.forEach(d=>{if(t.get(d))return;if(r.length<e.length){r.push(d),i.push(d);return}const h=o.shift();s.push(r[h]),r[h]=d,i.push(r[h])}),r.forEach((d,h)=>{a.has(d)||s.concat(r.splice(h,1))}),Array.from(t.keys()).forEach(d=>{t.delete(d,!a.has(d))}),r.forEach(d=>{if(!this.participants.joined.get(d)){l.warn("updateActiveParticipants::participant_not_in_joined_list",{dyteParticipant:{id:d}});return}t.add(this.participants.joined.get(d),!n.get(d))}),t.emit("participantsUpdate"),[i,s]}updateParticipantsMap(t,e){const r=Array.from(t.keys()),n=[],i=[];return r.forEach(s=>{e.includes(s)||(t.delete(s,!0),i.push(s))}),e.forEach(s=>{t.get(s)||(t.add(this.participants.joined.get(s)),n.push(s))}),t.emit("participantsUpdate"),[n,i]}updatePinnedParticipants(){this.participants.pinned.forEach(t=>{t.setIsPinned(!1),this.participants.pinned.delete(t.id)})}setupEventsGlobal(){this.roomSocketHandler.on(j.joinRoom,({peer:t})=>{if(!t.waitlisted){const e=Q.hasFeature(ie.DEBUG_SOCKET_JOIN);e&&l.info("Processing socket join",{peers:t.peerId}),this.onParticipantJoined(this.fromSocketService(t)),e&&l.info("Processed socket join",{peers:t.peerId})}}),this.roomSocketHandler.on(j.leaveRoom,t=>{this.selectedPeers.delete(t.peer.peerId),this.onParticipantLeave(t.peer.peerId)}),b.on(w.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())}),b.on(w.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})}),b.on(w.CONSUMER_PAUSED,({id:t})=>{this.processConsumerPaused(t)}),b.on(w.CONSUMER_RESUMED,({id:t})=>{this.processConsumerResumed(t)}),b.on(w.NEW_CONSUMER,({id:t})=>{this.processNewConsumer(t)}),b.on(w.CONSUMER_CLOSED,({id:t})=>{this.processConsumerClosed(t)}),b.on(w.ROOM_MESSAGE,t=>u(this,[t],function*({payload:e,type:r,timestamp:n}){this.participants.emit("broadcastedMessage",{type:r,payload:e,timestamp:n})})),b.on(w.MESSAGE,t=>u(this,[t],function*({payload:e,type:r,timestamp:n}){r!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:r,payload:e,timestamp:n})})),b.on(w.LOW_CONSUMER_SCORE,({peerId:t,score:e,kind:r})=>{const n=this.participants.joined.get(t);n&&(n.emit("poorConnection",{score:e,kind:r}),this.participants.emit("poorConnection",{participantId:t,score:e,kind:r}))}),b.on(w.CONSUMER_SCORE_UPDATE,({score:t,kind:e,appData:r,peerId:n,scoreStats:i})=>{var s;const a=e==="video"&&((s=r==null?void 0:r.screenShare)!=null?s:!1),o=this.participants.joined.get(n);o&&(o.emit("mediaScoreUpdate",{kind:e,isScreenshare:a,score:t,participantId:n,scoreStats:i}),this.participants.emit("mediaScoreUpdate",{kind:e,isScreenshare:a,score:t,participantId:n,scoreStats:i}))}),b.onAsync(w.KICK_PEER,t=>u(this,[t],function*({peerId:e}){const r=this.participants.joined.get(e);yield this.roomNodeClient.kick(e),yield this.roomSocketHandler.kick(e),r?r.emit("kicked"):this.participants.joined.emit("kicked",{id:e})})),b.on(w.UPDATE_ACTIVE,(...t)=>u(this,[...t],function*({page:e,createAllConsumers:r}={}){yield this.updateActive(e?"PAGINATED":"ACTIVE_GRID",{page:e,createAllConsumers:r})}))}onParticipantPinned(t){return u(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 u(this,null,function*(){var e,r,n;if(this.self.id!==t.id&&!((e=t.flags)!=null&&e.recorder)&&!((r=t.flags)!=null&&r.hidden_participant)&&!((n=t.flags)!=null&&n.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"&&b.emit(w.UPDATE_STAGE_REQUESTS,{request:{displayName:t.name,userId:t.userId,peerId:t.id},add:!0})),b.emit(w.PEER_JOINED_INTERNAL,t),this.self.config.viewType===gt.Webinar&&t.stageStatus!=="ON_STAGE"||this.roomNodeClient===void 0||this.participants.videoSubscribed.size>=this.roomNodeClient.maxPreferredStreams)return;const i=this.participants.currentPage;this.updateActive(i?"PAGINATED":"ACTIVE_GRID",{page:i})})}onParticipantLeave(t){return u(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),e&&e.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&b.emit(w.UPDATE_STAGE_REQUESTS,{request:{displayName:e.name,userId:e.userId,peerId:e.id},add:!1});const{currentPage:r}=this.participants,n=this.maxPreferredStreams*(r-1),i=this.participants.videoSubscribed.get(t);n===0?this.participants.setViewMode("ACTIVE_GRID"):this.participants.joined.size<=n?r===2?this.participants.setViewMode("ACTIVE_GRID"):this.participants.setPage(r-1):i&&this.updateActive(r?"PAGINATED":"ACTIVE_GRID",{page:r})})}processMedia(t){var e;const r=this.roomNodeClient.getConsumers(),{peerId:n,kind:i,appData:s,remotelyPaused:a,track:o,producerId:d,rtpReceiver:h}=(e=r.get(t))!=null?e:{};if(!n)return l.warn("processMedia::Peer ID is undefined",{consumer:{id:t,kind:i,peerId:n,appData:{supportsRemoteControl:s==null?void 0:s.supportsRemoteControl,screenShare:s==null?void 0:s.screenShare},remotelyPaused:a,producerId:d}}),{};const p=s;return i==="video"&&p.screenShare!==!0&&this.videoPeerConsumerMap.set(n,t),l.info("ParticipantController::processMedia",{consumer:{id:t,peerId:n,kind:i,appData:p,remotelyPaused:a,producerId:d}}),this.consumerPeerMap.set(t,{type:i,peerId:n,appData:p,remotelyPaused:a,producerId:d}),{peerId:n,kind:i,appData:p,remotelyPaused:a,track:o,producerId:d,rtpReceiver:h}}processConsumerClosed(t){const{peerId:e,type:r,appData:n,remotelyPaused:i,producerId:s}=this.consumerPeerMap.get(t)||{},a=this.participants.joined.get(e);if(l.info("ParticipantController::processConsumerClosed",{consumer:{id:t,peerId:e,appData:n,kind:r,remotelyPaused:i,producerId:s}}),this.consumerPeerMap.delete(t),r==="video"&&n.screenShare!==!0&&this.videoPeerConsumerMap.delete(e),!a)return;const o=[];n&&n.screenShare?(a.setScreenShareEnabled(!1),$.consumerSharedMediaState(t,{screen:!1}),a.screenShareTracks.video&&o.push(a.screenShareTracks.video.id),a.screenShareTracks.audio&&o.push(a.screenShareTracks.audio.id),a.screenShareTracks={audio:void 0,video:void 0}):r==="audio"?(a.setAudioEnabled(!1),a.audioTrack&&o.push(a.audioTrack.id),$.consumerSharedMediaState(t,{audio:!1}),a.audioTrack=void 0):r==="video"&&(a.setVideoEnabled(!1),this.updatePipSource(a.id,!1),a.videoTrack&&o.push(a.videoTrack.id),$.consumerSharedMediaState(t,{video:!1}),a.videoTrack=void 0),n.e2ee&&o.forEach(d=>{b.emit(w.E2EE_INACTIVE_CONSUMER,{peerId:e,trackId:d})})}processConsumerResumed(t){const{peerId:e,kind:r,appData:n,track:i,remotelyPaused:s,producerId:a,rtpReceiver:o}=this.processMedia(t);if(!e)return;l.info("ParticipantController::processConsumerResumed",{consumer:{id:t,peerId:e,kind:r,appData:n,remotelyPaused:s,producerId:a}});const d=this.participants.joined.get(e);if(d){if(n.e2ee&&b.emit(w.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:o,track:i}),n.screenShare){r==="video"?d.screenShareTracks.video=i:r==="audio"&&(d.screenShareTracks.audio=i),d.setScreenShareEnabled(!0),$.consumerSharedMediaState(t,{screen:!0});return}r==="video"?(d.videoTrack=i,d.setVideoEnabled(!0),this.updatePipSource(d.id,!0),$.consumerSharedMediaState(t,{video:!0})):r==="audio"&&(d.audioTrack=i,d.setAudioEnabled(d.audioEnabled),$.consumerSharedMediaState(t,{audio:d.audioEnabled}))}}processConsumerPaused(t){l.info(`ParticipantController::processConsumerPaused called for consumerId: ${t}`);const{peerId:e,kind:r,track:n,appData:i,remotelyPaused:s,producerId:a}=this.processMedia(t);if(!e)return;l.info("ParticipantController::processConsumerPaused",{consumer:{id:t,peerId:e,kind:r,appData:i,remotelyPaused:s,producerId:a}});const o=this.participants.joined.get(e);o&&(n&&i.e2ee&&b.emit(w.E2EE_INACTIVE_CONSUMER,{peerId:e,trackId:n.id}),r==="video"?(o.videoTrack=n,o.setVideoEnabled(!1),this.updatePipSource(o.id,!1),$.consumerSharedMediaState(t,{video:!1})):r==="audio"&&(o.audioTrack=n,o.setAudioEnabled(o.audioEnabled),$.consumerSharedMediaState(t,{audio:o.audioEnabled})))}processNewConsumer(t){const{peerId:e,kind:r,remotelyPaused:n,track:i,appData:s,producerId:a,rtpReceiver:o}=this.processMedia(t);if(!e)return;l.info("ParticipantController::processNewConsumer",{consumer:{id:t,peerId:e,kind:r,remotelyPaused:n,appData:s,producerId:a}});const d=this.participants.joined.get(e);if(d){if(s.screenShare){r==="video"?d.screenShareTracks.video=i:r==="audio"&&(d.screenShareTracks.audio=i),(!n||this.self.permissions.isRecorder||Q.hasFeature(ie.SCREEENSHARE_ERR_HACK))&&d.setScreenShareEnabled(!0),s.supportsRemoteControl&&(d.supportsRemoteControl=!0),this.participants.broadcastMessage("screenshareConsumerCreated",{producerId:a,peerId:e,screenShare:!0,consumerId:t,consumerPeerId:this.self.id}),l.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:t,peerId:e,kind:r,remotelyPaused:n,appData:s,producerId:a}});return}r==="video"?(d.videoTrack=i,n||(d.setVideoEnabled(!0),this.updatePipSource(d.id,!0)),$.consumerSharedMediaState(t,{video:!n})):r==="audio"&&(d.audioTrack=i,n||d.setAudioEnabled(!0),$.consumerSharedMediaState(t,{audio:!n})),!n&&s.e2ee&&b.emit(w.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:o,track:i})}}static formatSocketServiceMessage(t){var e,r,n,i,s,a;if(!t)return;const o=eu(t.stageType);return{id:t.peerId,userId:t.userId,name:t.displayName,displayName:t.displayName,stageType:o,customParticipantId:t.customParticipantId,presetId:t.presetId,picture:t.displayPictureUrl,waitlisted:t.waitlisted,stageStatus:o,metadata:{preset_name:(e=t.flags)==null?void 0:e.presetName},recorderType:(r=t.flags)==null?void 0:r.recorderType,flags:{hiddenParticipant:(n=t.flags)==null?void 0:n.hiddenParticipant,hidden_participant:(i=t.flags)==null?void 0:i.hiddenParticipant,recorder:((s=t.flags)==null?void 0:s.recorderType)!==void 0&&((a=t.flags)==null?void 0:a.recorderType)!=="NONE"}}}mapPeerIdsToProducers(t,e){const r=(n,i)=>n.filter(({kind:s,screenShare:a})=>i.includes(s)||a&&i.includes("screenshare"));return t.flatMap(n=>{const i=this.participants.joined.get(n);if(i)return r(i.producers,e)}).filter(n=>!!n)}updateGrid(t,e){let r=[],n=[],i=[],s=[];return e.video&&([r,i]=e.video(this.participants.videoSubscribed,t)),e.audio&&([n,s]=e.audio(this.participants.audioSubscribed,t)),{video:{add:r,remove:i},audio:{add:n,remove:s}}}onSelectedPeers(t,e){return u(this,null,function*(){this.participants.viewMode==="ACTIVE_GRID"&&this.computeActivateParticipants(t,e)})}updateActiveParticipantsWithPriorities(t,e=!1){if(!this.mediaJoined){l.warn("Skipped::ParticipantController::updateActiveParticipantsWithPriorities",{roomJoined:this.mediaJoined});return}t.forEach(n=>{this.selectedPeers.add(n.peerId,n.priority)});const r=this.selectedPeers.activeSpeakerPeers.at(0);r!==void 0&&r!==this.participants.lastActiveSpeaker&&(this.participants.lastActiveSpeaker=r,this.participants.emit("activeSpeaker",{peerId:r,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 zr=gv;hs([y.trace("ParticipantController.setupEvents")],zr.prototype,"setupEventsGlobal",1),hs([y.trace("ParticipantController.processMedia")],zr.prototype,"processMedia",1),hs([y.trace("ParticipantController.processConsumerClosed")],zr.prototype,"processConsumerClosed",1),hs([y.trace("ParticipantController.processConsumerResumed")],zr.prototype,"processConsumerResumed",1),hs([y.trace("ParticipantController.processConsumerPaused")],zr.prototype,"processConsumerPaused",1),hs([y.trace("ParticipantController.processNewConsumer")],zr.prototype,"processNewConsumer",1);var M1=Object.defineProperty,D1=Object.getOwnPropertyDescriptor,O1=(t,e,r,n)=>{for(var i=n>1?void 0:n?D1(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&M1(e,r,i),i};class vv extends zr{get roomNodeClient(){return this.context.getValue("roomNodeClient")}constructor(e,r,n){super(e,r,n),this.setupEvents()}setupEvents(){this.roomSocketHandler.on(j.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),b.on(w.SOCKET_PEERS,e=>u(this,null,function*(){e==null||e.forEach(r=>this.onParticipantJoined(this.fromSocketService(r)))})),this.roomSocketHandler.on(ce.peerJoinedBroadcast,({participant:e})=>this.onMediaJoined(e.peerId,e.producerStates)),this.roomSocketHandler.on(ce.selfJoinComplete,({participants:e,selectedPeers:r,roomState:n})=>{e.forEach(a=>this.onMediaJoined(a.peerId,a.producerStates));const{audioPeers:i,compulsoryPeers:s}=r!=null?r:{};n.pinnedPeerIds.length!==0&&this.onParticipantPinned(n.pinnedPeerIds[0]),this.computeActivateParticipants(i!=null?i:[],s),b.emit(w.UPDATE_ACTIVE,{createAllConsumers:!0})}),b.on(w.MAX_SPATIAL_LAYER_CHANGE,({peerId:e,maxSpatialLayer:r})=>{const n=this.videoPeerConsumerMap.get(e);n&&(this.maxSpatialLayerUpdates.set(n,r),this.updateConsumerSpatialLayers())}),b.on(w.NEW_PRODUCER,({peerId:e,producer:r})=>{const n=this.participants.joined.get(e);if(!n){l.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:r==null?void 0:r.producerId,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}},dyteParticipant:{id:e}});return}n.producers.push(r),l.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}}),(r==null?void 0:r.kind)==="audio"||r!=null&&r.screenShare||this.currentActiveGridParticipants.has(e)?this.roomNodeClient.createConsumers([r]).catch(i=>{l.error("ParticipantController::createConsumer failed",{error:i})}):l.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}})}),b.on(w.PRODUCER_CLOSED,({peerId:e,producerId:r})=>{const n=this.participants.joined.get(e);if(!n){l.warn("ParticipantController::NEW_PRODUCER::participant not found",{dyteParticipant:{id:e}});return}n.producers=n.producers.filter(i=>i.producerId!==r)}),b.on(w.PRODUCER_TOGGLE,({peerId:e,producerId:r,paused:n,kind:i})=>{const s=this.participants.joined.get(e);if(s){i==="audio"&&s.setAudioEnabled(!n);const a=s.producers.find(o=>o.producerId===r);a&&(a.pause=n)}}),this.roomSocketHandler.on(ce.globalPeerPinBroadcast,({participantId:e})=>{if(!this.mediaJoined)return;const r=e;this.onParticipantPinned(r);const n=this.participants.joined.get(r);this.roomNodeClient.activatePeers(n.producers).catch(i=>{l.error("unable to create consumers",{error:i})})}),this.roomSocketHandler.on(ce.selectedPeer,({audioPeers:e,compulsoryPeers:r})=>{this.mediaJoined&&this.onSelectedPeers(r.concat(e))}),this.roomSocketHandler.on(ce.selectedPeerDiff,({entries:e})=>{if(!this.mediaJoined||this.participants.viewMode!=="ACTIVE_GRID")return;const r=e.map(n=>({peerId:n.peerId,priority:n.priority}));this.updateActiveParticipantsWithPriorities(r,!0)})}}O1([y.trace("ParticipantController.setupEvents")],vv.prototype,"setupEvents",1);var N1=Object.defineProperty,L1=Object.getOwnPropertyDescriptor,x1=(t,e,r,n)=>{for(var i=n>1?void 0:n?L1(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&N1(e,r,i),i};class yv extends zr{get roomNodeClient(){return this.context.getValue("roomNodeClient")}constructor(e,r,n){super(e,r,n),this.setupEvents()}setupEvents(){this.roomSocketHandler.on(j.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),b.on(w.SOCKET_PEERS,e=>u(this,null,function*(){const r=Q.hasFeature(ie.DEBUG_SOCKET_JOIN);if(r){const n=e&&(e==null?void 0:e.length)<20?{peers:JSON.stringify(e.map(i=>i.peerId))}:void 0;l.info("Processing socket peers",n)}e==null||e.forEach(n=>{n.waitlisted||this.onParticipantJoined(this.fromSocketService(n))}),r&&l.info("Processed socket peers")})),this.roomSocketHandler.on(oe.peerJoinedBroadcast,({participant:e})=>{Q.hasFeature(ie.DEBUG_SOCKET_JOIN)&&l.info("mediaEvents.peerJoinedBroadcast",{peers:e.peerId}),this.onMediaJoined(e.peerId,e.producerStates)}),this.roomSocketHandler.on(oe.selfJoinComplete,({participants:e,selectedPeers:r,roomState:n})=>{if(Q.hasFeature(ie.DEBUG_SOCKET_JOIN)){const a=e&&(e==null?void 0:e.length)<20?{peers:JSON.stringify(e.map(o=>o.peerId))}:void 0;l.info("mediaEvents.selfJoinComplete",a)}e.forEach(a=>this.onMediaJoined(a.peerId,a.producerStates));const{audioPeers:i,compulsoryPeers:s}=r!=null?r:{};n.pinnedPeerIds.length!==0&&this.onParticipantPinned(n.pinnedPeerIds[0]),this.computeActivateParticipants(i!=null?i:[],s),b.emit(w.UPDATE_ACTIVE,{createAllConsumers:!0})}),b.on(w.MAX_SPATIAL_LAYER_CHANGE,({peerId:e,maxSpatialLayer:r})=>{const n=this.videoPeerConsumerMap.get(e);n&&(this.maxSpatialLayerUpdates.set(n,r),this.updateConsumerSpatialLayers())}),b.on(w.NEW_PRODUCER,({peerId:e,producer:r})=>{const n=this.participants.joined.get(e);if(!n){l.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:r==null?void 0:r.producerId,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}},dyteParticipant:{id:e}});return}if(n.producers.push(r),l.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}}),this.participants.viewMode==="MANUAL"){let i=!1;const s=r.kind==="audio",a=r.kind==="video",o=n.manualProducerConfig;(s&&(o.audio&&!r.screenShare||o.screenshareAudio&&r.screenShare)||a&&(o.video&&!r.screenShare||o.screenshareVideo&&r.screenShare))&&(i=!0),i?this.roomNodeClient.createConsumers([r]):l.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}});return}(r==null?void 0:r.kind)==="audio"&&this.participants.audioSubscribed.get(e)||(r==null?void 0:r.kind)==="video"&&this.participants.videoSubscribed.get(e)||r!=null&&r.screenShare?this.roomNodeClient.createConsumers([r]).catch(i=>{l.error("ParticipantController::createConsumer failed",{error:i})}):l.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}})}),b.on(w.PRODUCER_CLOSED,({peerId:e,producerId:r})=>{const n=this.participants.joined.get(e);if(!n){l.warn("ParticipantController::PRODUCER_CLOSED::participant not found",{dyteParticipant:{id:e}});return}n.producers=n.producers.filter(i=>i.producerId!==r)}),b.on(w.PRODUCER_TOGGLE,({peerId:e,producerId:r,paused:n,kind:i})=>{const s=this.participants.joined.get(e);if(s){i==="audio"&&s.setAudioEnabled(!n);const a=s.producers.find(o=>o.producerId===r);a&&(a.pause=n)}}),this.roomSocketHandler.on(oe.globalPeerPinBroadcast,e=>{let r;if(e&&(r=e.participantId),!this.mediaJoined)return;const n=r;this.onParticipantPinned(n);const i=this.participants.joined.get(n);i&&this.roomNodeClient.activatePeers(i.producers).catch(s=>{l.error("unable to create consumers",{error:s})})}),this.roomSocketHandler.on(oe.selectedPeer,({audioPeers:e,compulsoryPeers:r})=>{this.mediaJoined&&this.onSelectedPeers(r.concat(e))}),this.roomSocketHandler.on(oe.selectedPeerDiff,({entries:e})=>{if(!this.mediaJoined)return;const r=e.map(n=>({peerId:n.peerId,priority:n.priority}));this.updateActiveParticipantsWithPriorities(r,!0)})}}x1([y.trace("ParticipantController.setupEvents")],yv.prototype,"setupEvents",1);const Pe=dr(gl().permissions);var q,Ta,ka,Au,Vt,zt;const _a=class extends jt{constructor(t,e,r,n=!1){if(super(),T(this,Vt),T(this,q,void 0),T(this,Ta,void 0),T(this,ka,void 0),T(this,Au,i=>{var s,a,o;const d=i,{chat:h,connectedMeetings:p,plugins:m,polls:g,media:v}=d,I=po(d,["chat","connectedMeetings","plugins","polls","media"]);if(h&&(h.private&&cn(c(this,q).chat.private,h.private),h.public&&cn(c(this,q).chat.public,h.public),this.emit("chatUpdate")),p&&cn(c(this,q).connectedMeetings,p),v){const A=D=>{switch(D){case mn.NONE:return K.Allowed;case mn.ALLOWED:return K.Allowed;case mn.NOT_ALLOWED:return K.NotAllowed;case mn.CAN_REQUEST:return K.CanRequest;default:return}},P={audio:void 0,video:void 0,screenshare:void 0};(s=v.audio)!=null&&s.canProduce&&(P.audio={canProduce:A(v.audio.canProduce)}),(a=v.video)!=null&&a.canProduce&&(P.video={canProduce:A(v.video.canProduce)}),(o=v.screenshare)!=null&&o.canProduce&&(P.screenshare={canProduce:A(v.screenshare.canProduce)}),cn(c(this,q).media,P)}m&&(cn(c(this,q).plugins,m),this.emit("pluginsUpdate")),g&&(cn(c(this,q).polls,g),this.emit("pollsUpdate")),Object.keys(I).length!==0&&cn(c(this,q),I),this.emit("permissionsUpdate",i)}),!e)throw l.error("DytePermissionsPreset::load_preset_permissions_failed"),new _("Could not load preset permissions.","0904");S(this,ka,t),S(this,Ta,r),S(this,q,e),n&&this.setupEvents()}setupEvents(){b.on(w.UPDATE_PERMISSIONS,c(this,Au))}static fromResponse(t,e,r){return new _a(r,t,e,!0)}static default(t,e){return new _a(t,Pe,e)}static init(t,e,r){let n;return r?n=new _a(t,r,e,!0):n=new _a(t,Pe,e),n}get mediaRoomType(){const{sfu:t}=c(this,ka).getValue("roomNodeOptions");return t===cs.CF?"CF":"HIVE"}get stageEnabled(){var t;return((t=c(this,q))==null?void 0:t.stageEnabled)||c(this,Ta)===gt.Webinar||c(this,Ta)===gt.Livestream}get acceptStageRequests(){var t,e;return this.stageEnabled?((t=c(this,q))==null?void 0:t.acceptStageRequests)||((e=c(this,q))==null?void 0:e.canAcceptProductionRequests):!1}get stageAccess(){var t,e,r;return((t=c(this,q))==null?void 0:t.stageAccess)===K.NotAllowed?K.NotAllowed:((e=c(this,q))==null?void 0:e.stageAccess)===K.CanRequest?K.CanRequest:((r=c(this,q))==null?void 0:r.stageAccess)===K.Allowed||c(this,q).media.audio.canProduce===K.Allowed||c(this,q).media.video.canProduce===K.Allowed||c(this,q).media.screenshare.canProduce===K.Allowed?K.Allowed:c(this,q).media.audio.canProduce===K.CanRequest||c(this,q).media.video.canProduce===K.CanRequest||c(this,q).media.screenshare.canProduce===K.CanRequest?K.CanRequest:K.NotAllowed}get acceptWaitingRequests(){var t,e;return(e=(t=c(this,q))==null?void 0:t.acceptWaitingRequests)!=null?e:Pe.acceptWaitingRequests}get requestProduceVideo(){var t,e,r;return((r=(e=(t=c(this,q))==null?void 0:t.media)==null?void 0:e.video)==null?void 0:r.canProduce)===K.CanRequest}get requestProduceAudio(){var t,e,r;return((r=(e=(t=c(this,q))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.canProduce)===K.CanRequest}get requestProduceScreenshare(){var t,e,r;return((r=(e=(t=c(this,q))==null?void 0:t.media)==null?void 0:e.screenshare)==null?void 0:r.canProduce)===K.CanRequest}get canAllowParticipantAudio(){var t,e;return(e=(t=c(this,q))==null?void 0:t.disableParticipantAudio)!=null?e:Pe.disableParticipantAudio}get canAllowParticipantScreensharing(){var t,e;return(e=(t=c(this,q))==null?void 0:t.canAcceptProductionRequests)!=null?e:Pe.canAcceptProductionRequests}get canAllowParticipantVideo(){var t,e;return(e=(t=c(this,q))==null?void 0:t.disableParticipantVideo)!=null?e:Pe.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var t,e;return(e=(t=c(this,q))==null?void 0:t.kickParticipant)!=null?e:Pe.kickParticipant}get pinParticipant(){var t,e;return(e=(t=c(this,q))==null?void 0:t.pinParticipant)!=null?e:Pe.pinParticipant}get canRecord(){var t,e;return(e=(t=c(this,q))==null?void 0:t.canRecord)!=null?e:Pe.canRecord}get waitingRoomType(){var t,e;return(e=(t=c(this,q))==null?void 0:t.waitingRoomType)!=null?e:Pe.waitingRoomType}get waitingRoomBehaviour(){var t,e;return(e=(t=c(this,q))==null?void 0:t.waitingRoomType)!=null?e:Pe.waitingRoomType}get plugins(){var t,e;return(e=(t=c(this,q))==null?void 0:t.plugins)!=null?e:Pe.plugins}get polls(){var t,e;return(e=(t=c(this,q))==null?void 0:t.polls)!=null?e:Pe.polls}get produceVideo(){return this.canProduceVideo}get requestProduce(){return c(this,q).media.audio.canProduce===K.CanRequest||c(this,q).media.video.canProduce===K.CanRequest||c(this,q).media.screenshare.canProduce===K.CanRequest}get canProduceVideo(){var t;const e=(t=c(this,q).media.video.canProduce)!=null?t:Pe.media.video.canProduce;return this.stageEnabled&&(c(this,Vt,zt)==="ACCEPTED_TO_JOIN_STAGE"||c(this,Vt,zt)==="ON_STAGE")&&e===K.CanRequest?K.Allowed:this.stageEnabled&&(c(this,Vt,zt)==="OFF_STAGE"||c(this,Vt,zt)==="REQUESTED_TO_JOIN_STAGE")&&e===K.Allowed?K.NotAllowed:e}get produceScreenshare(){return this.canProduceScreenshare}get canProduceScreenshare(){var t;const e=(t=c(this,q).media.screenshare.canProduce)!=null?t:Pe.media.screenshare.canProduce;return this.stageEnabled&&(c(this,Vt,zt)==="ACCEPTED_TO_JOIN_STAGE"||c(this,Vt,zt)==="ON_STAGE")&&e===K.CanRequest?K.Allowed:this.stageEnabled&&(c(this,Vt,zt)==="OFF_STAGE"||c(this,Vt,zt)==="REQUESTED_TO_JOIN_STAGE")&&e===K.Allowed?K.NotAllowed:e}get produceAudio(){return this.canProduceAudio}get canProduceAudio(){var t;const e=(t=c(this,q).media.audio.canProduce)!=null?t:Pe.media.audio.canProduce;return this.stageEnabled&&(c(this,Vt,zt)==="ACCEPTED_TO_JOIN_STAGE"||c(this,Vt,zt)==="ON_STAGE")&&e===K.CanRequest?K.Allowed:this.stageEnabled&&(c(this,Vt,zt)==="OFF_STAGE"||c(this,Vt,zt)==="REQUESTED_TO_JOIN_STAGE")&&e===K.Allowed?K.NotAllowed:e}get chatPublic(){var t,e,r;return(r=(e=(t=c(this,q))==null?void 0:t.chat)==null?void 0:e.public)!=null?r:Pe.chat.public}get chatPrivate(){var t,e,r;return(r=(e=(t=c(this,q))==null?void 0:t.chat)==null?void 0:e.private)!=null?r:Pe.chat.private}get chatChannel(){var t,e,r;return(r=(e=(t=c(this,q))==null?void 0:t.chat)==null?void 0:e.channel)!=null?r:Pe.chat.channel}get chatMessage(){var t,e,r;return(r=(e=(t=c(this,q))==null?void 0:t.chat)==null?void 0:e.message)!=null?r:Pe.chat.message}get connectedMeetings(){var t,e;return(e=(t=c(this,q))==null?void 0:t.connectedMeetings)!=null?e:Pe==null?void 0:Pe.connectedMeetings}get hiddenParticipant(){var t,e;return(e=(t=c(this,q))==null?void 0:t.hiddenParticipant)!=null?e:Pe.hiddenParticipant}get showParticipantList(){var t;return(t=c(this,q).showParticipantList)!=null?t:Pe.showParticipantList}get canChangeParticipantRole(){var t,e;return(e=(t=c(this,q))==null?void 0:t.canChangeParticipantPermissions)!=null?e:Pe.canChangeParticipantPermissions}get canChangeParticipantPermissions(){var t,e;return(e=(t=c(this,q))==null?void 0:t.canChangeParticipantPermissions)!=null?e:Pe.canChangeParticipantPermissions}get canChangeTheme(){return!1}get canPresent(){return c(this,q).media.audio.canProduce===K.Allowed||c(this,q).media.video.canProduce===K.Allowed||c(this,q).media.screenshare.canProduce===K.Allowed}get acceptPresentRequests(){return this.acceptStageRequests}get canEditDisplayName(){var t;return(t=c(this,q).canEditDisplayName)!=null?t:!1}get maxScreenShareCount(){return 1}get isRecorder(){return c(this,q).isRecorder}get canSpotlight(){return c(this,q).canSpotlight}get canLivestream(){return c(this,q).canLivestream}get transcriptionEnabled(){return c(this,q).transcriptionEnabled}};let F1=_a;q=new WeakMap,Ta=new WeakMap,ka=new WeakMap,Au=new WeakMap,Vt=new WeakSet,zt=function(){return c(this,ka).getValue("stageStatus")};var Sv;class V1 extends jt{constructor(){super(...arguments),f(this,"localMediaHandler"),T(this,Sv,void 0)}updatePermission(){return u(this,null,function*(){var e,r;const n=(h,p)=>{this.mediaPermissions[h]=p;const m={message:this.mediaPermissions[h],kind:h};p==="DENIED"?b.emit(w.MEDIA_PERMISSION_ERROR,m):b.emit(w.MEDIA_PERMISSION_UPDATE,m)};if(Te.getName()==="firefox")return;const i="microphone",s="camera",a=yield(e=navigator==null?void 0:navigator.permissions)==null?void 0:e.query({name:i}),o=yield(r=navigator==null?void 0:navigator.permissions)==null?void 0:r.query({name:s}),d=(h,p)=>{switch(p){case"granted":n(h,"ACCEPTED");break;case"denied":n(h,"DENIED");break;case"prompt":n(h,"NOT_REQUESTED");break}this.localMediaHandler.repopulateAvailableDevices()};a&&(a.onchange=()=>d("audio",a.state)),o&&(o.onchange=()=>d("video",o.state))})}populateMediaPermissionsInCallstats(e){return u(this,arguments,function*({message:r,kind:n}){switch(n){case"audio":{$.mediaPermission("AUDIO",r),$.mediaPermission("SPEAKER",r);break}case"video":{$.mediaPermission("VIDEO",r);break}case"screenshare":{$.mediaPermission("SCREENSHARE",r);break}}})}init(){return u(this,arguments,function*(e={},r=!1,n=null){var i,s,a,o,d,h;if(Te.init(),!this.localMediaHandler)try{let p=!0;if(n!=null&&n.getValue("defaults").mediaHandler)p=!1,this.localMediaHandler=n.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:m}=navigator;this.localMediaHandler=yield m.init()}else this.localMediaHandler=new Ft(n,e.constraints,(i=n==null?void 0:n.getValue("defaults"))==null?void 0:i.isNonPreferredDevice,(s=n==null?void 0:n.getValue("defaults"))==null?void 0:s.autoSwitchAudioDevice);if(b.on(w.MEDIA_PERMISSION_UPDATE,m=>u(this,null,function*(){if(this.populateMediaPermissionsInCallstats({message:m.message,kind:m.kind}),m.message==="NOT_REQUESTED")switch(m==null?void 0:m.kind){case"audio":this.rawAudioTrack&&(l.info("Disabling audio due to media permission update"),this.disableAudio());break;case"video":this.rawVideoTrack&&(l.info("Disabling video due to media permission update"),this.disableVideo());break;default:break}this.emit("mediaPermissionUpdate",m)})),b.on(w.MEDIA_PERMISSION_ERROR,m=>u(this,null,function*(){const{kind:g,message:v,constraints:I}=m;this.populateMediaPermissionsInCallstats({message:v,kind:g}),g==="audio"?(l.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):g==="video"&&(l.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),l.error("SelfController::mediaPermissionError",{error:{message:v},constraints:I,mediaPermissionsErrors:{kind:g,message:v}}),this.emit("mediaPermissionError",m),this.emit("mediaPermissionUpdate",{message:v,kind:g})})),p){l.info(`Setting up DyteSelfMedia streams using media handler. audio:${(a=e==null?void 0:e.audio)!=null?a:!0} video:${(o=e==null?void 0:e.video)!=null?o:!0}`);const m=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});r||(yield m)}}catch(p){l.error("DyteSelf::init::Failed To Setup Streams",{error:{name:p.name,message:p.message}})}})}get audioTrack(){return this.localMediaHandler.audioTrack}get rawAudioTrack(){return this.localMediaHandler.rawAudioTrack}get mediaPermissions(){return this.localMediaHandler.permissions}addAudioMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.addAudioMiddleware(e)})}removeAudioMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.removeAudioMiddleware(e)})}removeAllAudioMiddlewares(){return u(this,null,function*(){return this.localMediaHandler.removeAllAudioMiddlewares()})}get videoTrack(){return this.localMediaHandler.videoTrack}get rawVideoTrack(){return this.localMediaHandler.rawVideoTrack}addVideoMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.addVideoMiddleware(e)})}setVideoMiddlewareGlobalConfig(){return u(this,arguments,function*(e={disablePerFrameCanvasRendering:!1}){return this.localMediaHandler.setVideoMiddlewareGlobalConfig(e)})}removeVideoMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.removeVideoMiddleware(e)})}removeAllVideoMiddlewares(){return u(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 u(this,null,function*(){yield this.localMediaHandler.enableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})}enableVideo(){return u(this,null,function*(){yield this.localMediaHandler.enableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})}disableAudio(){return u(this,null,function*(){this.localMediaHandler.disableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})}enableScreenShare(){return u(this,null,function*(){yield this.localMediaHandler.enableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})}disableScreenShare(){return u(this,null,function*(){yield this.localMediaHandler.disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})}disableVideo(){return u(this,null,function*(){yield this.localMediaHandler.disableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})}getCurrentDevices(){return this.localMediaHandler.getCurrentDevices()}getAudioDevices(){return u(this,null,function*(){return yield this.localMediaHandler.getAudioDevices()})}getVideoDevices(){return u(this,null,function*(){return yield this.localMediaHandler.getVideoDevices()})}getSpeakerDevices(){return u(this,null,function*(){return yield this.localMediaHandler.getSpeakerDevices()})}getDeviceById(e,r){let n;return r==="audio"?n="audioinput":r==="video"?n="videoinput":r==="speaker"&&(n="audiooutput"),this.localMediaHandler.getDeviceById(e,n)}setDevice(e){return u(this,null,function*(){switch(e.kind){case"audioinput":try{yield this.localMediaHandler.setAudioDevice(e)}catch(r){}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(r){}finally{this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})})}}Sv=new WeakMap;const ba={},In={executeWithLock({methodName:t,lockName:e,timeout:r}){return(n,i,s)=>{const a=s.value;return s.value=function(...o){if(ba[e]){const p=new Error(`Unsupported concurrent calls on Dyte method: ${t}.`);throw p.name="UnsupportedConcurrentMethodExecution",l.error("DyteLocker::UnsupportedConcurrentMethodExecution",{error:{stack:p.stack},dyteLocker:{methodName:t,lockName:e}}),p}ba[e]=!0;const d=setTimeout(()=>delete ba[e],r),h=a.apply(this,o);return Promise.resolve(h).then(()=>{delete ba[e],clearTimeout(d)}).catch(()=>{delete ba[e],clearTimeout(d)}),h},s}}};var U1=Object.defineProperty,B1=Object.getOwnPropertyDescriptor,Rt=(t,e,r,n)=>{for(var i=n>1?void 0:n?B1(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&U1(e,r,i),i},wa,Ut,Ia,Kr,Cn,yi,ot,pt,Qe,tt,Ca,Pa,zc,Mu,Ev;let ct=(Ev=class extends V1{constructor(t,e,r,n,i){var s;super(),T(this,Cn),T(this,ot),T(this,Qe),T(this,zc),f(this,"name"),f(this,"picture"),f(this,"customParticipantId"),f(this,"waitlistStatus"),T(this,wa,void 0),T(this,Ut,void 0),T(this,Ia,void 0),f(this,"role"),f(this,"userId"),f(this,"organizationId"),f(this,"supportsRemoteControl",!1),f(this,"device"),T(this,Kr,void 0),f(this,"hidden",!1),f(this,"presetName"),f(this,"roomState","init"),T(this,Ca,new Set),T(this,Pa,new Set),S(this,Kr,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=(s=e.customParticipantId)!=null?s:e.clientSpecificId,this.waitlistStatus="none",S(this,Ut,r),S(this,wa,n),this.hidden=!1,S(this,Ia,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=Te.isElectron(),this.device=Te.getDeviceInfo(),this.presetName=i,n.viewType!==gt.Chat&&this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),Je(this,zc,Mu).call(this)}get stageStatus(){return c(this,Kr).getValue("stageStatus")}get id(){return c(this,Kr).getValue("peerId")}static __init__(t,e,r,n,i,s=!1){return u(this,null,function*(){var a,o,d,h,p;let m=(o=(a=t.getValue("defaults"))==null?void 0:a.audio)!=null?o:!0,g=(h=(d=t.getValue("defaults"))==null?void 0:d.video)!=null?h:!0;r.canProduceAudio!=="ALLOWED"&&(m=!1),r.canProduceVideo!=="ALLOWED"&&(g=!1);const v=new ct(t,e,r,n,i);if(n.viewType===gt.Chat)return v;const I=ED(n.mediaConstraints);return cn(I,(p=t.getValue("defaults"))==null?void 0:p.mediaConfiguration),yield v.init({audio:m,video:g,constraints:I},s,t),v.setupEvents(),v})}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"),c(this,Ut).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",Je(this,zc,Mu)),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",()=>u(this,null,function*(){if(l.info("DyteSelf::setupEvents::AUDIO_TRACK_CHANGE",U({},ci(this))),c(this,Qe,tt)&&this.audioEnabled&&this.stageStatus==="ON_STAGE")try{yield c(this,ot,pt).shareMic(this.audioTrack)}catch(t){l.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",()=>u(this,null,function*(){if(l.info("DyteSelf::setupEvents::VIDEO_TRACK_CHANGE",U({},ci(this))),c(this,Qe,tt)&&this.rawVideoTrack===void 0)l.info("DyteSelf::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&c(this,Qe,tt)&&this.stageStatus==="ON_STAGE")try{const t=yield c(this,ot,pt).shareWebcam(this.videoTrack);t&&t.id!==this.videoTrack.id&&Q.hasFeature(ie.EXP_RESHARE)&&(yield c(this,ot,pt).shareWebcam(this.videoTrack))}catch(t){l.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=>u(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",()=>u(this,null,function*(){if(!c(this,Qe,tt)){l.error("DyteSelf.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{yield c(this,ot,pt).shareScreen(this.screenShareTracks)}catch(t){l.error("DyteSelf::setupEvents::Error while sharing screen",{error:t}),this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare())}l.info("DyteSelf::setupEvents::SCREENSHARE_TRACK_CHANGE",U({},ci(this))),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})),this.localMediaHandler.on("SCREENSHARE_ENDED",()=>u(this,null,function*(){l.log("Disabling screenshare due to SCREENSHARE_ENDED"),yield this.disableScreenShare(),l.info("DyteSelf::setupEvents::SCREENSHARE_ENDED",U({},ci(this)))})),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{$.mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",()=>u(this,null,function*(){c(this,Qe,tt)&&(yield c(this,ot,pt).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),$.videoOff()})),c(this,Ut).on("permissionsUpdate",t=>{var e,r,n;(e=t==null?void 0:t.media)!=null&&e.audio&&c(this,Ut).canProduceAudio!==K.Allowed&&(this.disableAudio(),l.info(`Disabled audio due to dynamic preset change: canProduceAudio: ${this.permissions.canProduceAudio}`)),(r=t==null?void 0:t.media)!=null&&r.video&&c(this,Ut).canProduceVideo!==K.Allowed&&(this.disableVideo(),l.info(`Disabled video due to dynamic preset change: canProduceVideo: ${this.permissions.canProduceVideo}`)),(n=t==null?void 0:t.media)!=null&&n.screenshare&&c(this,Ut).canProduceScreenshare!==K.Allowed&&(this.disableScreenShare(),l.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return c(this,Ut)}get config(){return c(this,wa)}get roomJoined(){var t;return c(this,wa).viewType===gt.Livestream&&this.stageStatus!=="ON_STAGE"?((t=c(this,Kr).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:c(this,Qe,tt)}setName(t){if(!t)throw new _("Name cannot be empty.","1103");this.name=t}setupTracks(){return u(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 u(this,null,function*(){return this.localMediaHandler.destruct()})}removeDocumentEventListeners(){return u(this,null,function*(){return this.localMediaHandler.removeDocumentEventListeners()})}enableAudio(){return u(this,null,function*(){if(this.permissions.canProduceAudio!==K.NotAllowed&&!(c(this,Ut).canProduceAudio===K.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if($.audioOn(),yield this.localMediaHandler.enableAudio(),c(this,Qe,tt)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{yield c(this,ot,pt).shareMic(this.audioTrack)}catch(t){l.error("DyteSelf::enableAudio::Error while sharing mic",{error:t}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return;c(this,ot,pt).unmuteSelf()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}})}enableVideo(){return u(this,null,function*(){if(c(this,Ut).canProduceVideo!==K.NotAllowed&&!(c(this,Ut).canProduceVideo===K.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if($.videoOn(),yield this.localMediaHandler.enableVideo(),c(this,Qe,tt)&&this.stageStatus==="ON_STAGE")try{yield c(this,ot,pt).shareWebcam(this.videoTrack)}catch(t){l.error("DyteSelf::enableVideo::Error while sharing video",{error:t}),this.videoEnabled&&(yield this.localMediaHandler.disableVideo())}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),l.info("DyteSelf.enableVideo",U({},ci(this)))}})}updateVideoConstraints(t){return u(this,null,function*(){if(!this.localMediaHandler.updateVideoConstraints)throw new _("Unsupported","1102");yield this.localMediaHandler.updateVideoConstraints(t)})}enableScreenShare(){return u(this,null,function*(){if(!c(this,Qe,tt))throw new _("Can`t enable screenshare without joining room","1105");if(c(this,Ut).canProduceScreenshare!==K.NotAllowed&&!(c(this,Ut).canProduceScreenshare===K.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 c(this,ot,pt).shareScreen(this.screenShareTracks)}catch(t){l.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 u(this,null,function*(){if(!this.localMediaHandler.updateScreenshareConstraints)throw new _("Unsupported","1102");yield this.localMediaHandler.updateScreenshareConstraints(t)})}disableAudio(){return u(this,null,function*(){this.audioEnabled&&(this.localMediaHandler.disableAudio(),c(this,Qe,tt)&&c(this,ot,pt).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),$.audioOff())})}disableVideo(){return u(this,null,function*(){this.videoEnabled&&(yield this.localMediaHandler.disableVideo(),c(this,Qe,tt)&&(yield c(this,ot,pt).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),$.videoOff())})}disableScreenShare(){return u(this,null,function*(){this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare(),c(this,Qe,tt)&&(yield c(this,ot,pt).disableScreenShare()),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))})}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var r;S(this,Ia,t);const n=t?"pinned":"unpinned";(r=c(this,Cn,yi))==null||r.updateSource(this.id,{pinned:t}),e&&this.emit(n,this)}get isPinned(){return c(this,Ia)}pin(){return u(this,null,function*(){if(!c(this,Qe,tt))throw new _("Can`t pin participants without joining room","1105");return this.show(),c(this,ot,pt).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!c(this,Qe,tt))throw new _("Can`t unpin participants without joining room","1105");return c(this,ot,pt).pinPeer(null)})}hide(){return u(this,null,function*(){if(!c(this,Qe,tt))throw new _("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})})}show(){if(!c(this,Qe,tt))throw new _("Can`t toggle participant tile without joining room","1105");this.hidden=!1,this.emit("toggleTile",{hidden:this.hidden})}setDevice(t){return u(this,null,function*(){var e,r,n;if(!t)throw new _("No device selected","1104");const i=this.getCurrentDevices();if(t.deviceId&&(((e=i==null?void 0:i.audio)==null?void 0:e.deviceId)===t.deviceId||((r=i==null?void 0:i.video)==null?void 0:r.deviceId)===t.deviceId||((n=i==null?void 0:i.speaker)==null?void 0:n.deviceId)===t.deviceId)&&(l.warn("DyteSelf.setDevice.setting_to_in_use_device",{devices:[t]}),Q.hasFeature(ie.SKIP_SETTING_IN_USE_DEVICE)))throw new _("Cannot set device currently in use","1106");switch(t.kind){case"audioinput":try{yield this.localMediaHandler.setAudioDevice(t)}catch(s){c(this,Qe,tt)&&(yield c(this,ot,pt).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(s){c(this,Qe,tt)&&(yield c(this,ot,pt).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}})}cleanUpTracks(){var t,e,r,n;(t=this.audioTrack)==null||t.stop(),(e=this.rawAudioTrack)==null||e.stop(),(r=this.videoTrack)==null||r.stop(),(n=this.rawVideoTrack)==null||n.stop()}registerVideoElement(t,e=!1){var r,n;e?c(this,Ca).add(t):c(this,Pa).add(t),this.updateVideo(t),e||(n=c(this,Cn,yi))==null||n.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(r=this.raised)!=null?r:!1)}deregisterVideoElement(t,e=!1){if(t===void 0){c(this,Cn,yi).removeSource(this.id);return}t.srcObject=void 0,e?c(this,Ca).delete(t):(c(this,Pa).delete(t),c(this,Cn,yi).removeSource(this.id))}updateVideo(t,e=!1){var r,n,i;if(this.videoEnabled){if(this.videoTrack==null)return;const s=(r=t.srcObject)==null?void 0:r.getTracks()[0];if((s==null?void 0:s.id)===this.videoTrack.id)return;const a=new MediaStream;a.addTrack(this.videoTrack),t.srcObject=a,e||(n=c(this,Cn,yi))==null||n.enableSource(this.id)}else t.srcObject=void 0,e||(i=c(this,Cn,yi))==null||i.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},wa=new WeakMap,Ut=new WeakMap,Ia=new WeakMap,Kr=new WeakMap,Cn=new WeakSet,yi=function(){return c(this,Kr).getValue("pip")},ot=new WeakSet,pt=function(){return c(this,Kr).getValue("roomNodeClient")},Qe=new WeakSet,tt=function(){var t;return((t=c(this,Kr).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Ca=new WeakMap,Pa=new WeakMap,zc=new WeakSet,Mu=function(){Array.from(c(this,Pa)).forEach(t=>this.updateVideo(t,!1)),Array.from(c(this,Ca)).forEach(t=>this.updateVideo(t,!0))},Ev);Rt([y.trace("DyteSelf.cleanupEvents")],ct.prototype,"cleanupEvents",1),Rt([y.trace("DyteSelf.setupEvents")],ct.prototype,"setupEvents",1),Rt([y.trace("DyteSelf.setupTracks")],ct.prototype,"setupTracks",1),Rt([y.trace("DyteSelf.destructMediaHandler")],ct.prototype,"destructMediaHandler",1),Rt([y.trace("DyteSelf.removeDocumentEventListeners")],ct.prototype,"removeDocumentEventListeners",1),Rt([In.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),y.trace("DyteSelf.enableAudio")],ct.prototype,"enableAudio",1),Rt([In.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),y.trace("DyteSelf.enableVideo")],ct.prototype,"enableVideo",1),Rt([y.trace("DyteSelf.updateVideoConstraints")],ct.prototype,"updateVideoConstraints",1),Rt([y.trace("DyteSelf.enableScreenShare"),In.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3})],ct.prototype,"enableScreenShare",1),Rt([y.trace("DyteSelf.updateScreenshareConstraints")],ct.prototype,"updateScreenshareConstraints",1),Rt([In.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),y.trace("DyteSelf.disableAudio")],ct.prototype,"disableAudio",1),Rt([In.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),y.trace("DyteSelf.disableVideo")],ct.prototype,"disableVideo",1),Rt([In.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3}),y.trace("DyteSelf.disableScreenShare")],ct.prototype,"disableScreenShare",1),Rt([y.trace("DyteSelf.setDevice")],ct.prototype,"setDevice",1),ct=Rt([vt("1100")],ct);class j1 extends sv{constructor(e){super(e),f(this,"sessionDescription"),this.sessionDescription=e.sessionDescription}}class H1 extends lv{}class W1 extends dv{retryFailedConsumerCreationTasks(e){return u(this,null,function*(){return jc(e.map(r=>u(this,null,function*(){return wr(n=>u(this,null,function*(){return n>0&&l.warn(`retrying failed consumer creation task: ${JSON.stringify(r)}`),this.consumerCreationTask(U({},r))}))})))})}consumerCreationTask(e){return u(this,arguments,function*({consumerId:r,producerId:n,producingPeerId:i,producingTransportId:s,streamId:a,trackId:o,paused:d,screenShare:h,appData:p,kind:m,sessionDescription:g}){const v=`${a}:${m}`,I={consumerId:r,producerId:n,producingPeerId:i,producingTransportId:s,streamId:a,trackId:o,sessionDescription:g,appData:p,kind:m,paused:d,screenShare:h,name:"consumer creation task error",message:"consumer creation failed"};return new Promise((A,P)=>u(this,null,function*(){const D=setTimeout(()=>{this.consumerTrackEvents.delete(v),I.isTimedout=!0,P(I)},5e3),N=(G,W)=>{try{if(G.readyState==="ended")clearTimeout(D),P(I);else{const de=G;de.enabled=!0,this.handler.midTransceiverMap.set(W.mid,W);const ae=new j1({id:r,localId:W.mid,track:de,paused:d,producerId:n,producingPeerId:i,handler:this.handler,appData:X(U({},p),{screenShare:h,peerId:i}),reuseTrack:!0,rtpReceiver:W.receiver,producingTransportId:s,sessionDescription:g});this.consumers.set(r,ae),ae.once("close",()=>{this.consumers.delete(ae.id),this.handler.midTransceiverMap.delete(W.mid)}),l.info("consumer created for ",{consumer:{id:r,kind:m,appData:{screenShare:h},peerId:i,producerId:n}}),this.observer.emit("newconsumer",ae),clearTimeout(D),A(ae)}}catch(de){l.warn("error while creating consumer:",de),clearTimeout(D),P(I)}},J=this.consumerTrackPool.get(r);if((J==null?void 0:J.length)===2){N(J[0],J[1]);return}const C=this.unknownTracksMap.get(v);C?(this.unknownTracksMap.delete(v),N(C.track,C.transceiver)):this.consumerTrackEvents.set(v,N),g&&(yield this.safeEmitAsPromise("negotiate",{description:g}))}))})}connect(){return u(this,null,function*(){try{const{offerSdp:e,callback:r}=yield this.handler.connect(),{answer:n}=yield this.safeEmitAsPromise("connect",{offer:e});if(yield r(n),!(yield this.isConnected))throw new Error("ice connection failed")}catch(e){throw l.error("transport failed to connect:",e),e}})}_ontrack(e){const{track:r,transceiver:n}=e;l.info(`track event received [trackId: ${r.id}]`);const i=`${n.mid}:${r.kind}`;r.addEventListener("ended",()=>{l.info(`rtc consumer track ended [trackId: ${r.id}]`),this.consumerTrackPool.delete(r.id),this.unknownTracksMap.delete(i)}),this.consumerTrackPool.set(r.id,[r,n]);const s=this.consumerTrackEvents.get(i);s?(s(r,n),this.consumerTrackEvents.delete(i)):(l.warn(`track event handler not found ${i}`),this.unknownTracksMap.set(i,e))}consume(e){return u(this,null,function*(){if(l.debug(`consume() producers: ${JSON.stringify(e)}`),this.closed)throw new et("closed");if(this.direction!=="recv")throw new mi("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.isConnected))return Promise.reject(new Error("Transport not connected"));const r=[],n=new Map;return e.forEach(i=>{var s;const a=(s=n.get(i.producingPeerId))!=null?s:[];n.set(i.producingPeerId,a.concat([i]))}),n.forEach((i,s)=>u(this,null,function*(){const{consumersMap:a}=yield this.safeEmitAsPromise("consume_peer",{producingPeerId:s});a.forEach((o,d)=>{const{consumerId:h,trackId:p,screenShare:m,paused:g,streamId:v,kind:I,appData:A,producingTransportId:P,sessionDescription:D}=o;r.push(this.consumerCreationTask({consumerId:h,trackId:p,streamId:v,kind:I,producerId:d,producingPeerId:s,producingTransportId:P,paused:g,screenShare:m,appData:A,sessionDescription:D}))})})),jc(r)})}produce(){return u(this,arguments,function*({track:e,encodings:r,codecOptions:n,stopTracks:i=!0,disableTrackOnPause:s=!0,zeroRtpOnPause:a=!1,appData:o={}}={}){if(l.debug(`produce() [track:${e.id}]`),e){if(this.direction!=="send")throw new mi("not a sending Transport");if(e.readyState==="ended")throw new et("track ended");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("produce")===0)throw new TypeError('no "produce" listener set into this transport');if(o&&typeof o!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!(yield this.isConnected))return Promise.reject(new Error("Transport not connected"));const{producerId:d,localId:h,rtpSender:p}=yield this.awaitQueue.push(()=>u(this,null,function*(){const{offerSdp:g,callback:v,sender:I,mid:A}=yield this.handler.send({track:e,encodings:r,codecOption:n,screenShare:o==null?void 0:o.screenShare}),{answer:P,producerId:D}=yield this.safeEmitAsPromise("produce",{offer:g,kind:e.kind,paused:s?!e.enabled:!1,appData:X(U({},o||{}),{mid:A})}),N=yield v(P);return{producerId:D,localId:N,rtpSender:I}}),"producer"),m=new H1({id:d,localId:h,track:e,stopTracks:i,disableTrackOnPause:s,zeroRtpOnPause:a,appData:o,handler:this.handler,rtpSender:p});return this.producers.set(d,m),m.observer.on("close",()=>{this.producers.delete(m.id)}),this.emit("newproducer",m),this.observer.emit("newproducer",m),m})}}class $1 extends uv{createTransport({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,appData:a,config:o}){const d=Un(),h=new W1({id:d,direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,appData:a,handlerFactory:this.handlerFactory,config:o});return this._observer.emit("newtransport",h),h}}var At;class J1{constructor(e){T(this,At,void 0),S(this,At,e)}joinRoom(e,r,n=!1,i=null){return u(this,null,function*(){const s={roomUuid:e,displayName:r,prejoined:n};return i&&(s.location=i),(yield c(this,At).sendMessagePromiseWithTimeout({event:ce.joinRoom,protobuf:gf.toBinary(s),timeout:5e3})).payload})}connectTransport(e){return u(this,null,function*(){const r=(yield c(this,At).sendMessagePromise(ce.createWebRTCTransport,lf.toBinary(e))).payload,{transportId:n,description:i}=_l.fromBinary(r),s={sdp:i==null?void 0:i.sdp,type:i.type};return{transportId:n,answer:s}})}produce(e){return u(this,null,function*(){var r,n;const i=(yield c(this,At).sendMessagePromise(ce.produce,Sf.toBinary(e))).payload,s=Mf.fromBinary(i);return{answer:{sdp:(r=s==null?void 0:s.description)==null?void 0:r.sdp,type:(n=s==null?void 0:s.description)==null?void 0:n.type},producerId:s.producerId}})}consume(e){return u(this,null,function*(){const r=(yield c(this,At).sendMessagePromise(ce.consume,bl.toBinary(e))).payload,{consumerIdsMap:{map:n},description:i}=Af.fromBinary(r);return{consumerStateMap:n,sessionDescription:i}})}closeProducer(e){return u(this,null,function*(){const r=(yield c(this,At).sendMessagePromise(ce.closeProducer,Tf.toBinary(e))).payload,{description:n}=Df.fromBinary(r);return n})}closeConsumer(e){return u(this,null,function*(){return(yield c(this,At).sendMessagePromise(ce.closeConsumer,kf.toBinary(e))).payload})}hostControlForPeer(e,r){return u(this,null,function*(){const n={audio:r==="audio",screeShare:!1,video:r==="video",participantId:e},i=(yield c(this,At).sendMessagePromise(ce.hostControlPeer,wf.toBinary(n))).payload;if(!i)return!1;const{status:s}=Lf.fromBinary(i);return s==="success"})}hostControlForAll(e){return u(this,null,function*(){const r={audio:e==="audio",screenShare:!1,video:e==="video"},n=(yield c(this,At).sendMessagePromise(ce.hostControlAllPeers,If.toBinary(r))).payload;if(!n)return!1;const{status:i}=xf.fromBinary(n);return i==="success"})}kickAll(){return u(this,null,function*(){const e={},r=(yield c(this,At).sendMessagePromise(ce.kickAll,wl.toBinary(e))).payload;if(!r)return!1;const{status:n}=Nf.fromBinary(r);return n==="success"})}kickPeer(e){return u(this,null,function*(){const r=(yield c(this,At).sendMessagePromise(ce.kickPeer,_f.toBinary(e))).payload;if(!r)return!1;const{status:n}=Of.fromBinary(r);return n==="success"})}changeDisplayName(e){return u(this,null,function*(){const r=(yield c(this,At).sendMessagePromise(ce.changeDisplayName,bf.toBinary(e))).payload;if(!r)return!1;const{status:n}=Ff.fromBinary(r);return n==="success"})}notifySelfJoinComplete(){return u(this,null,function*(){const e={},r=(yield c(this,At).sendMessagePromise(ce.selfJoinComplete,vf.toBinary(e))).payload;return qo.fromBinary(r)})}}At=new WeakMap;const G1=Error("task execution aborted");class q1{constructor(e,r){f(this,"id"),f(this,"executor"),f(this,"cancel"),this.id=e,this.executor=r}execute(){return u(this,null,function*(){return new Promise((e,r)=>{this.cancel=()=>r(G1),this.executor.then(n=>e(n))})})}}let Tv=0;const Kc=new Map;class Du{static execute(e){const r=Tv;Tv+=1;const n=new q1(r,e);return Kc.set(r,n),{id:r,value:n.execute().finally(()=>Kc.delete(r))}}static stop(e){const r=Kc.get(e);r&&(r.cancel(),Kc.delete(e))}}const z1=2e3;var ps,Ra,Yr;class K1 extends ev{constructor(e,r){super(),T(this,ps),f(this,"_device"),f(this,"_sendTransport"),f(this,"_recvTransport"),f(this,"_consumers"),f(this,"_producers"),f(this,"_producerStatus"),f(this,"_producerIdToConsumerIdMap"),f(this,"_socket"),f(this,"_socketHandler"),f(this,"_totalTransportReconnectionCount"),f(this,"_transportReconnectFailureCount"),f(this,"_consumerCreationFailureCount"),f(this,"_producerNotReadyFailureCount"),f(this,"_consumerNotBoundFailureCount"),f(this,"_transportDisconnectedTimer"),f(this,"_iceTransportPolicy","all"),f(this,"_transportConnectionFailCount",0),f(this,"lastConnectionTime",0),f(this,"transportConnectionStatus"),f(this,"transportDisconnected"),T(this,Yr,void 0),S(this,Yr,e),this._device=new $1({}),this._socket=r,c(this,ps,Ra).mediaState={recv:{state:er.NEW,reconnected:!1},send:{state:er.NEW,reconnected:!1}},this.transportDisconnected={consuming:!1,producing:!1},this._socketHandler=new J1(r),this.reset()}get socket(){return this._socket}get producers(){return this._producers}get consumers(){return this._consumers}get producerIdToConsumerIdMap(){return this._producerIdToConsumerIdMap}get cfSocketHandler(){return this._socketHandler}get sendTransport(){return this._sendTransport}get recvTransport(){return this._recvTransport}reset(){this._producers=new Map,this._consumers=new Map,this._producerStatus=new Map,this._producerIdToConsumerIdMap=new Map,this.transportConnectionStatus=new Map,this._transportReconnectFailureCount=0,this._consumerCreationFailureCount=0,this._totalTransportReconnectionCount=0,this._producerNotReadyFailureCount=0,this._consumerNotBoundFailureCount=0,this._transportDisconnectedTimer={consuming:void 0,producing:void 0}}setupTransports(e,r){return u(this,null,function*(){const n=yield qe().getICEServers().catch(s=>(l.warn(`failed to get iceservers from server: ${s.message}`),[])),i=e.map(s=>{var a,o,d,h,p,m,g,v;const I=this.transportConnectionStatus.get(s);if(I&&!r)return I;switch(I&&r&&Du.stop(I.id),s){case"send":{const A=Du.execute(this.createSendTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(a=c(this,Yr).getValue("modules").e2ee)==null?void 0:a.enabled},config:{enableHighBitrate:(h=(d=(o=c(this,Yr).getValue("defaults").mediaConfiguration)==null?void 0:o.audio)==null?void 0:d.enableHighBitrate)!=null?h:!1,enableStereo:(g=(m=(p=c(this,Yr).getValue("defaults").mediaConfiguration)==null?void 0:p.audio)==null?void 0:m.enableStereo)!=null?g:!1},iceTransportPolicy:this._iceTransportPolicy}));return this.transportConnectionStatus.set(s,A),A.value}case"recv":{const A=Du.execute(this.createRecvTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(v=c(this,Yr).getValue("modules").e2ee)==null?void 0:v.enabled},iceTransportPolicy:this._iceTransportPolicy}));return this.transportConnectionStatus.set(s,A),A.value}default:return l.warn(`What are you thinking when passing this transportType: ${s}?`,{transport:{type:s}}),Promise.reject(Error("TYPE_OF_TRANSPORT_UNKNOWN"))}});return Promise.all(i).finally(()=>{e.forEach(s=>{this.transportConnectionStatus.delete(s)})})})}stopAllTransports(){var e,r,n,i;l.info(" closing all the transports"),(e=this._sendTransport)==null||e.close(),(r=this._sendTransport)==null||r.removeAllListeners(),(n=this._recvTransport)==null||n.close(),(i=this._recvTransport)==null||i.removeAllListeners(),this._sendTransport=void 0,this._recvTransport=void 0,this.reset()}createSendTransport(e){return u(this,null,function*(){var r,n,i,s;if(this._sendTransport&&this._sendTransport.connected){l.info("sendTransport::already_exists_in_connected_state",{transport:{id:(r=this._sendTransport)==null?void 0:r.id,serverId:(n=this._sendTransport)==null?void 0:n.serverId,type:"send"}});return}l.info("sendTransport::initializing_transport",{transport:{id:(i=this._sendTransport)==null?void 0:i.id,serverId:(s=this._sendTransport)==null?void 0:s.serverId,type:"send"}});const a=this._device.createSendTransport(e);this._transportDisconnectedTimer.producing=void 0,l.info("sendTransport::initialized_transport",{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"send"}}),this.handleTransport(a,!1),l.info("sendTransport::connecting_transport",{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"send"}});try{yield wr((o,d)=>u(this,null,function*(){this.socket.isConnected||d(new Error("socket is not connected")),a.connectionState==="closed"&&d(new Error("transport is closed")),o>0&&l.debug(`retrying transport connect, count: ${o}`,{transport:{id:a.id,serverId:a.serverId,type:"send"}});try{yield a.connect()}catch(h){throw l.error(`failed to connect send transport: ${a.id}`,{error:h,transport:{id:a.id,serverId:a.serverId,type:"send"}}),h.message==="ice connection failed"&&d(h),h}}),{delayTime:100,strategy:"exponential",maxRetryCount:Q.hasFeature(ie.ENABLE_CF_INFINITE_RETRIES)?1/0:3}),l.info("sendTransport::connected_transport",{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"send"}}),this._transportReconnectFailureCount=Math.max(0,this._transportReconnectFailureCount-1),this._producerNotReadyFailureCount=0,this._sendTransport=a,$.configureSendTransport(a)}catch(o){throw l.error(`failed to connect send transport after retry:${a.id}`,{error:o,transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"send"}}),a.close(),a.removeAllListeners(),this._transportReconnectFailureCount+=1,this.handleFailure(),o}})}createRecvTransport(e){return u(this,null,function*(){var r,n,i,s,a;if(this._recvTransport&&this._recvTransport.connected){l.info("recvTransport::already_exists_in_connected_state",{transport:{id:(r=this._recvTransport)==null?void 0:r.id,serverId:(n=this._recvTransport)==null?void 0:n.serverId,type:"recv"}});return}l.info("recvTransport::initializing_transport",{transport:{id:(i=this._recvTransport)==null?void 0:i.id,serverId:(s=this._recvTransport)==null?void 0:s.serverId,type:"recv"}});const o=this._device.createRecvTransport(X(U({},e),{additionalSettings:X(U({},(a=e.additionalSettings)!=null?a:{}),{rtcAudioJitterBufferMaxPackets:25,rtcAudioJitterBufferFastAccelerate:!0,rtcAudioJitterBufferMinDelayMs:20})}));this._transportDisconnectedTimer.consuming=void 0,l.info("recvTransport::initialized_transport",{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"recv"}}),this.handleTransport(o,!0),l.info("recvTransport::connecting_transport",{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"recv"}});try{yield wr((d,h)=>u(this,null,function*(){this.socket.isConnected||h(new Error("socket is not connected")),o.connectionState==="closed"&&h(new Error("transport is closed")),d>0&&l.debug(`retrying transport connect, count: ${d}`,{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"recv"}});try{yield o.connect()}catch(p){throw l.error(`fail to connect recv transport: ${o.id}`,{error:p,transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"recv"}}),p.message==="ice connection failed"&&h(p),p}}),{delayTime:100,strategy:"exponential",maxRetryCount:Q.hasFeature(ie.ENABLE_CF_INFINITE_RETRIES)?1/0:3}),l.info("recvTransport::connected_transport",{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"recv"}}),this._transportReconnectFailureCount=Math.max(0,this._transportReconnectFailureCount-1),this._consumerCreationFailureCount=0,this._consumerNotBoundFailureCount=0,this.producerIdToConsumerIdMap.clear(),this._recvTransport=o,$.configureRecvTransport(o)}catch(d){throw l.error(`failed to connect recv transport after retry:${o.id}`,{error:d,transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"recv"}}),o.close(),o.removeAllListeners(),this._transportReconnectFailureCount+=1,this.handleFailure(),d}})}handleTransport(e,r){if(e.on("connect",(n,i,s)=>u(this,[n,i,s],function*({offer:a},o,d){try{const h={consuming:r,description:{sdp:a.sdp,type:a.type,target:r?Ht.SUBSCRIBER:Ht.PUBLISHER}},{transportId:p,answer:m}=yield this._socketHandler.connectTransport(h);e.setServerId(p),o({answer:m})}catch(h){l.error(`${r?"consumer":"producer"} transport connection error:`,{error:h,transport:{id:e==null?void 0:e.id,serverId:e==null?void 0:e.serverId,type:r?"recv":"send"}}),d(h)}})),e.on("connectionstatechange",n=>u(this,null,function*(){this.updateTransportState({state:n,direction:r?"consuming":"producing"}),l.info(`${r?"consumer":"producer"} transport connectionState:`,{transport:{id:e==null?void 0:e.id,serverId:e==null?void 0:e.serverId,type:r?"recv":"send",status:n}});const i=()=>{this._transportDisconnectedTimer[r?"consuming":"producing"]!==void 0&&(clearTimeout(this._transportDisconnectedTimer[r?"consuming":"producing"]),this._transportDisconnectedTimer[r?"consuming":"producing"]=void 0)};switch(n){case"connected":i(),this.lastConnectionTime=performance.now();break;case"disconnected":this._transportDisconnectedTimer[r?"consuming":"producing"]=setTimeout(()=>{this.triggerTransportReconnection(e,r)},z1);break;case"failed":if(e.closed)return;i(),this.triggerTransportReconnection(e,r);break}})),e.on("icecandidate",n=>u(this,null,function*(){l.debug("sending icecandidate:",{iceCandidate:n})})),e.on("datachannel:events",(n,i)=>u(this,null,function*(){var s,a;l.debug("got data channel message on event:",{rtcChannel:{label:n,message:i}});try{switch(i.type){case"negotiation":{this.negotiateOverDC(i,Wc(i),n,e);break}case"handshake":{const o={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,Wc(i),o);break}case"consumer_toggle":{this.handleConsumerToggle(i.payload);break}case"hub-disconnect":{l.debug(`media hub disconnected, full_reconnect: ${(s=i.payload)==null?void 0:s.full_reconnect}`),((a=i.payload)==null?void 0:a.full_reconnect)===!0&&this.emit("rejoin");break}case"error":{this.handleErrorOverDC(i.payload,e.id);break}default:l.warn(`unknown event received from cf node, event: ${i.type}`);break}}catch(o){l.error(`Unable to handle the incoming datachannel message on channel ${n}`)}})),e.on("dc_error",()=>{e.direction==="recv"&&(l.warn("events datachannel did not open in 5s"),this.handleFailure())}),e.on("negotiate",(n,i,s)=>u(this,[n,i,s],function*({description:a},o,d){try{const h={sdp:a==null?void 0:a.sdp,type:a==null?void 0:a.type},p=yield this.negotiate(e,h);o({answer:p})}catch(h){l.error("negotiate error:",{transport:{id:e.id,serverId:e.serverId,type:e.direction},error:h}),d(h)}})),!r){e.on("produce",(n,i,s)=>u(this,[n,i,s],function*({offer:a,kind:o,paused:d,appData:h},p,m){var g;const v=Md(a.sdp).media.filter(A=>o==="video"?A.type==="video":A.type==="audio").at(-1).msid,I={description:{sdp:a.sdp,type:a.type,target:Ht.PUBLISHER},paused:d,kind:o,msid:v,appData:JSON.stringify(h),screenShare:(g=h.screenShare)!=null?g:!1};try{const{answer:A,producerId:P}=yield this._socketHandler.produce(I);p({answer:A,producerId:P})}catch(A){l.error("create producer error:",{error:A}),m(A)}}));return}e.on("consume_peer",(n,i,s)=>u(this,[n,i,s],function*({producingPeerId:a},o,d){l.info("consumePeer:",a);const h={producingPeerId:a};try{const p=yield this._socketHandler.consume(h);l.debug(`consumePeer response for ${a}:`,{consumerStateMap:p.consumerStateMap});const m=new Map;Object.entries(p.consumerStateMap).forEach(([g,v])=>{var I,A,P;let D={};try{D=JSON.parse(v.producerState.appData)}catch(N){}m.set(g,{consumerId:v.consumerId,trackId:(I=v.producerTrack)==null?void 0:I.trackId,streamId:v.producerTrack.streamId,kind:v.producerState.kind===Lt.VIDEO?"video":"audio",appData:D,screenShare:(A=v.producerState)==null?void 0:A.screenShare,paused:(P=v.producerState)==null?void 0:P.pause,sessionDescription:p.sessionDescription,producingPeerId:a})}),o({consumersMap:m})}catch(p){l.error("consumePeer error:",{error:p}),d(p)}})),e.on("consume",(n,i,s)=>u(this,[n,i,s],function*({producerId:a,producingPeerId:o},d,h){var p,m,g,v,I,A,P,D,N;const J={producingPeerId:o,producerId:a};try{const C=yield this._socketHandler.consume(J),G=C.consumerStateMap[a];let W={};try{W=JSON.parse((p=G.producerState)==null?void 0:p.appData)}catch(de){}l.info("consumer create response:",{consumer:{remotelyPaused:(m=G.producerState)==null?void 0:m.pause,producerId:(g=G.producerState)==null?void 0:g.producerId,kind:(I=(v=G.producerState)==null?void 0:v.kind)==null?void 0:I.toString(),appData:X(U({},W),{screenShare:(A=G.producerState)==null?void 0:A.screenShare}),id:G.consumerId,sessionDescription:C.sessionDescription},consumerState:G}),d({consumerId:G.consumerId,screenShare:(P=G.producerState)==null?void 0:P.screenShare,trackId:(D=G.producerTrack)==null?void 0:D.trackId,streamId:G.producerTrack.streamId,kind:G.producerState.kind===Lt.VIDEO?"video":"audio",paused:(N=G.producerState)==null?void 0:N.pause,appData:W,sessionDescription:C.sessionDescription})}catch(C){l.error("error during consuming on server:",C),h(C)}}))}createProducer(e,r,n){return u(this,null,function*(){var i;if(this._sendTransport===void 0||this._sendTransport.closed)return null;l.info("createProducer::initializing_producer",{producer:{id:"TO_BE_CREATED",kind:e,status:"initializing",appData:r==null?void 0:r.appData}});const s=this._producerStatus.get(e);if((s==null?void 0:s.trackId)===r.track.id&&(s==null?void 0:s.status)===jr.INITIALIZING)return l.info("createProducer::producer getting initializing",{producer:{id:"GETTING_CREATED",status:"initializing",kind:e,appData:r==null?void 0:r.appData}}),null;this._producerStatus.set(e,{trackId:r.track.id,status:jr.INITIALIZING});try{const a=yield this._sendTransport.produce(r);return(i=r.appData)!=null&&i.e2ee&&b.emit(w.E2EE_ACTIVE_PRODUCER,a),l.info("createProducer::initialized_producer",{producer:{id:a==null?void 0:a.id,kind:e,status:"producing",appData:r==null?void 0:r.appData}}),a.on("close",(o,d)=>u(this,[o,d],function*({offer:h,reason:p},m){l.info("producer::closing",{debuggingHint:p,producer:{id:a==null?void 0:a.id,kind:e,status:"closing",appData:r==null?void 0:r.appData}});const g={producerId:a.id,description:{sdp:h.sdp,type:h.type,target:Ht.PUBLISHER}};try{const v=yield this._socketHandler.closeProducer(g),I={sdp:v==null?void 0:v.sdp,type:v==null?void 0:v.type};l.info("producer::closed",{producer:{id:a==null?void 0:a.id,kind:e,status:"closed",appData:r==null?void 0:r.appData}}),m({answer:I})}catch(v){l.error("producer close error",v)}this._producerStatus.delete(e),this._producers.delete(e),n(),this.reconfigureWebcamLayers()})),a.on("trackended",()=>{l.info("producer::trackended",{producer:{id:a==null?void 0:a.id,kind:e,status:"UNKNOWN",appData:a==null?void 0:a.appData}}),[ne.MIC,ne.WEBCAM].includes(e)||n()}),this._producers.set(e,a),this._producerStatus.set(e,{trackId:r.track.id,status:jr.INITIALIZED}),this.reconfigureWebcamLayers(),a.track}catch(a){throw this._producerStatus.set(e,{status:jr.NOT_INITIALIZED,trackId:r.track.id}),l.error("createProducer::transport_initialization_failed",{producer:{id:"FAILED_TO_CREATE",kind:e,status:"failed",appData:r==null?void 0:r.appData,error:a}}),a}})}reconfigureWebcamLayers(){return u(this,null,function*(){if(!Q.hasFeature(ie.DISABLE_WEBCAM_LAYERS_ON_SCREENSHARE))return;const e=this.producers.get(ne.WEBCAM);e&&(yield this._switchProducerSpatialLayer(e,this.producers.get(ne.SCREENSHARE_VIDEO)?0:3))})}_switchProducerSpatialLayer(e,r){return u(this,null,function*(){try{l.debug("switching layer of webcam producer to:",{media:{video:{layer:r}},producer:{id:e.id,kind:e.kind,appData:e.appData}}),yield e.setMaxSpatialLayer(r)}catch(n){l.error("failed to switch spatial layer",{error:n})}})}_initConsumer(e){e&&(e.observer.on("close",r=>u(this,null,function*(){l.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),this._consumers.delete(e.id),b.emit(w.CONSUMER_CLOSED,{id:e.id})})),this._consumers.set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),b.emit(w.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId}))}createConsumers(e){return u(this,null,function*(){if(!(this._recvTransport===void 0||this._recvTransport.closed||!this._recvTransport.connected)){if(e.every(r=>this.getProducer(r.producerId))){l.warn("why are you creating a consumer for local producer?");return}yield wr(r=>u(this,null,function*(){r>0&&l.debug(`retrying consume call, retryCount: ${r}`),(yield this._recvTransport.consume(e).catch(n=>{throw l.error("failed to consume:",{error:n}),n})).forEach(n=>{n.status==="rejected"?(l.error("consumer creation task is failing",n.reason),this._consumerCreationFailureCount+=1,setTimeout(this.handleFailure.bind(this),0)):this._initConsumer(n.value)})})).catch(r=>{l.error("create consumer failed after retries",{error:r}),this._consumerCreationFailureCount+=1,this.handleFailure()})}})}pauseProducer(e){return u(this,null,function*(){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.pause(),r.appData.e2ee&&b.emit(w.E2EE_INACTIVE_PRODUCER,r),l.info(`Paused the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})})}resumeProducer(e){return u(this,null,function*(){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.resume(),l.info(`Resumed the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})})}replaceTrack(e,r){return u(this,null,function*(){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}yield n.replaceTrack({track:r}),l.info(`Replaced track for the producer of type: ${n.kind}`,{producer:{id:n.id,kind:n.kind,appData:n.appData,trackId:r.id}})})}removeProducer(e,r){return u(this,null,function*(){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}r&&n.track.stop(),yield this.sendTransport.awaitQueue.push(n.close.bind(n),"producer").then(()=>{c(this,Yr).getValue("modules").e2ee.enabled&&b.emit(w.E2EE_INACTIVE_PRODUCER,n)}).catch(i=>{l.error("failed to close producer on server",i)})})}pauseConsumer(e){return u(this,null,function*(){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}this.toggleConsumerOverDC(e,!0),l.info(`Paused the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})})}pauseConsumerOverSocket(e){return u(this,null,function*(){try{const r={consumerId:e.id,pause:!0};yield this.socket.sendMessagePromise(ce.toggleConsumer,Go.toBinary(r)),e.pause(),b.emit(w.CONSUMER_PAUSED,{id:e.id}),l.info(`Paused the consumer of type: ${e.kind} over socket`,{consumer:{id:e.id,kind:e.kind,appData:e.appData}})}catch(r){l.error("error on pausing consumer",{error:r,consumer:{id:e.id,kind:e.kind,appData:e.appData}})}})}toggleConsumerOverDC(e,r){return u(this,null,function*(){const n={type:"consumer_toggle",payload:{consumerId:e,mute:r}},i=this._recvTransport.getDatachannel("events");if(!i){l.warn("recvTransport:: events datachannel not found");return}yield i.request(n),l.info(`HiveSFUHandler::consumer toggled, consumerId: ${e}, muted: ${r}`)})}resumeConsumer(e){return u(this,null,function*(){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}if(!r.paused){l.warn(`consumer with id:${e} is not paused so not resuming`);return}try{const n={consumerId:e,pause:!1};yield this.socket.sendMessagePromise(ce.toggleConsumer,Go.toBinary(n)),r.resume(),b.emit(w.CONSUMER_RESUMED,{id:r.id}),l.info(`Resumed the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})}catch(n){l.error("error on resuming consumer",n)}})}closeConsumer(e,r){return u(this,null,function*(){return this.closeConsumers([e],r)})}closeConsumers(e,r=!1){return u(this,null,function*(){l.info(`Closing consumers: ${JSON.stringify(e)} with force: ${r}`);let n=!0;const i=e.filter(o=>this._consumers.get(o)?!0:(l.warn(`consumer with id: ${o} not found`),!1));if(!i.length)return;const s={consumerIds:i},a=()=>u(this,null,function*(){var o;return(o=this._recvTransport)==null?void 0:o.awaitQueue.push(()=>u(this,null,function*(){yield this._socketHandler.closeConsumer(s)}),"close_consumer").catch(d=>{l.warn("error on closing consumer:",{error:d}),n=r})});r?a():yield a(),n&&i.forEach(o=>{const d=this.consumers.get(o);this.producerIdToConsumerIdMap.delete(d.producerId),d.close(r?"force closed":void 0)})})}cleanupConsumers(e){return u(this,null,function*(){l.debug("cleaning up all consumers");const r=[];this._consumers.forEach(n=>{e?n.peerId===e&&r.push(n.id):r.push(n.id)}),this.closeConsumers(r,!0)})}stopAllProducers(){return u(this,null,function*(){l.info("stopping all available producers"),this._producers.forEach((e,r)=>{l.debug(`closing producer type: ${r}`,{producer:{id:e==null?void 0:e.id,kind:e.kind,appData:e.appData}}),e.close()})})}getProducer(e){return Array.from(this.producers.values()).filter(r=>r.id===e).at(0)}hasProducer(e){return this.getProducer(e)!==void 0}negotiate(e,r){return u(this,null,function*(){l.debug(`setting remote offer : ${JSON.stringify(r)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}});const n=yield e.setRemoteOffer(r),i={transportId:e.serverId,description:{sdp:n.sdp,type:n.type,target:Ht.SUBSCRIBER}};return l.debug(`sending renegotiate request: ${JSON.stringify(i)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),yield this.socket.sendMessagePromise(ce.renegotiateSessionDescription,uf.toBinary(i)),l.info("renegotiation done",{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),n})}negotiateOverDC(e,r,n,i){return u(this,null,function*(){const{sdp:s}=e.payload,a={sdp:s,type:"offer"};try{l.debug(`got offer over dc: ${s} for transport: ${i.id}`);const o=yield i.setRemoteOffer(a),d={type:"answer",payload:{type:o.type,sdp:o.sdp}};l.debug(`datachannel answer: ${JSON.stringify(d)}`),i.sendResponseOverDC(n,r,d)}catch(o){l.error("datachannel:events::Error:",o),o.code!=="DC_NOT_FOUND"&&i.sendErrorOverDC(n,r,o)}})}handleConsumerToggle(e){const{mute:r,trackId:n}=e;l.info(`consumer toggled for trackId: ${n} muted: ${r}`);const i=this.consumers.get(n);if(!i){l.warn(`consumer with trackId: ${n} not found`);return}i.paused!==r&&(l.debug("consumer state is not same",{consumer:{id:i.id,remotelyPaused:i.paused}}),r?(i.pause(),b.emit(w.CONSUMER_PAUSED,{id:i.id})):(i.resume(),b.emit(w.CONSUMER_RESUMED,{id:i.id})))}handleErrorOverDC(e,r){return u(this,null,function*(){l.error(`got error over dc: ${JSON.stringify(e)} for transport: ${r}`);const{type:n,error:i,id:s}=e;if(n==="consumer"){if(i==="bind-fail"){if(this._consumerNotBoundFailureCount>=2){this.handleFailure();return}this._consumerNotBoundFailureCount+=1;const a=this.consumers.get(s);if(!a)return;try{yield this.closeConsumer(a.id),yield this.createConsumers([{kind:a.kind,pause:a.paused,producerId:a.producerId,producingTransportId:a.producingTransportId,screenShare:a.appData.screenShare,producingPeerId:a.peerId}])}catch(o){l.error("failed to recreate consumer on downtrack bound failure,",{consumer:{id:a.id,producerId:a.producerId,kind:a.kind,appData:a.appData}})}}}else if(n==="producer")if(i==="ready-fail"){if(this._producerNotReadyFailureCount>=2){this.handleFailure();return}this._producerNotReadyFailureCount+=1;const[a]=Array.from(this.producers.entries()).find(o=>o[1].id===s);if(!a)return;yield this.removeProducer(a).catch(o=>{l.error("failed to remove ready-fail producer:",{error:o,producer:{id:s,kind:a,appData:null}})})}else i==="general-failure"&&(this.updateTransportState({state:er.RECONNECTING,direction:"producing"}),this.emit("reconnect_transport",this._sendTransport))})}handleFailure(){return u(this,null,function*(){if(this._transportReconnectFailureCount>0||this._totalTransportReconnectionCount>3){l.warn("transport failure detected"),Q.hasFeature(ie.ENABLE_CF_EXPERIMENTAL_FAIL_RECOVERY)&&(l.debug("rejoining room"),this.emit("rejoin"));return}(this._consumerCreationFailureCount>0||this._consumerNotBoundFailureCount>=2)&&(l.warn("consumer creation failure detected or consumer not bound failure increased"),Q.hasFeature(ie.ENABLE_CF_EXPERIMENTAL_FAIL_RECOVERY)&&(l.debug("reconnecting recv transport"),this._totalTransportReconnectionCount+=1,this.updateTransportState({state:er.RECONNECTING,direction:"consuming"}),this.emit("reconnect_transport",this._recvTransport))),this._producerNotReadyFailureCount>=2&&(l.warn("producer receiver not getting added needs to reconnect send transport"),this._totalTransportReconnectionCount+=1,this.updateTransportState({state:er.RECONNECTING,direction:"producing"}),this.emit("reconnect_transport",this._sendTransport))})}triggerTransportReconnection(e,r){l.info("triggerTransportReconnection:: reconnecting transport",{transport:{type:e.direction,id:e.id,serverId:e.serverId}});const n=Q.hasFeature(ie.ENABLE_CF_TRANSPORT_RECONNECTION_ON_ICE_FAILED),i=Q.hasFeature(ie.CF_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED);n&&(i&&this._socket.isConnected&&(performance.now()-this.lastConnectionTime>2e4&&(this._transportConnectionFailCount=0),this._transportConnectionFailCount>2&&(l.warn("Multiple disconnections, forcing relay"),this._iceTransportPolicy="relay"),this._transportConnectionFailCount+=1),this.updateTransportState({state:er.RECONNECTING,direction:r?"consuming":"producing"}),this.emit("reconnect_transport",e))}switchConsumersToLayer(e,r){return u(this,null,function*(){const n=this._recvTransport.getDatachannel("events");if(!n){l.warn("events datachannel not found");return}const i={type:"switch_consumer_layer",payload:{consumerIds:e,layer:r}};yield n.request(i),l.info(`CFSFUHandler::consumer id: ${e} layer switched to ${r}`)})}updateTransportState(e){const{state:r,direction:n}=e;r==="disconnected"&&(this.transportDisconnected[n]=!0),c(this,ps,Ra).mediaState[n]={state:r,reconnected:r==="connected"?this.transportDisconnected[n]:c(this,ps,Ra).mediaState[n].reconnected},r==="connected"&&(this.transportDisconnected[n]=!1),b.emit(w.TRANSPORT_STATE_UPDATE,U({transport:n},c(this,ps,Ra).mediaState[n]))}}ps=new WeakSet,Ra=function(){return c(this,Yr).getValue("connectionHandler")},Yr=new WeakMap;var Y1=Object.defineProperty,Q1=Object.getOwnPropertyDescriptor,pe=(t,e,r,n)=>{for(var i=n>1?void 0:n?Q1(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&Y1(e,r,i),i},Mt,ve,Qr,ms,Si,Ei,Yc,Qc,Xc,Pn,Aa,Xr,Rn,kv;const _v=(kv=class extends Zg{constructor(t,e){var r,n;super(),T(this,Xr),T(this,Mt,void 0),T(this,ve,void 0),T(this,Qr,void 0),T(this,ms,void 0),T(this,Si,void 0),T(this,Ei,void 0),T(this,Yc,void 0),T(this,Qc,void 0),T(this,Xc,void 0),T(this,Pn,void 0),T(this,Aa,void 0),f(this,"legacyMode"),f(this,"roomNodeUrl"),f(this,"peerDisplayName"),f(this,"activatedProducingPeerIds"),f(this,"e2ee"),f(this,"partialJoinRoomPromise"),this.context=t;const{roomName:i,authToken:s,legacyMode:a,socketClient:o,meetingTitle:d}=e;this.mediaJoined=!1,this.roomName=i,this.authToken=s,this.legacyMode=a,this.meetingTitle=d,S(this,Mt,o),S(this,Qr,!1),S(this,ve,new K1(t,o)),this.maxPreferredStreams=6,this.activatedProducingPeerIds=new Set,S(this,Pn,new Set),S(this,ms,!1),S(this,Si,0),S(this,Ei,new as),this.e2ee=(n=(r=t.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?n:!1,$.legacySwitch(a),this.handleSocketEvents(),this.handleSFUEvents(),this.handleCallstatsEvents(),S(this,Yc,Mr(()=>u(this,null,function*(){if(!c(this,Xr,Rn).mediaJoinAttempted)return;const{roomJoined:h}=yield this.joinRoom(this.peerDisplayName,this.roomUUID,{},!0,!0);h&&(b.emit(w.RESET_PRODUCER_STATE),b.emit(w.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3})),S(this,Qc,Mr(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports(["send"]),l.info("send transport reconected!"),b.emit(w.RESET_PRODUCER_STATE)}),1e3)),S(this,Xc,Mr(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports(["recv"]),l.info("recv transport reconnected!"),this.activatedProducingPeerIds=new Set,b.emit(w.UPDATE_ACTIVE,{createAllConsumers:!0})}),1e3))}get mediaState(){return c(this,Xr,Rn).mediaState}get mediaJoined(){return c(this,Xr,Rn).mediaJoined}set mediaJoined(t){c(this,Xr,Rn).mediaJoined=t}static init(t,e){return u(this,null,function*(){const{legacyMode:r=!0,meetingId:n,authToken:i,meetingTitle:s,socket:a}=e;return new _v(t,{legacyMode:r,authToken:i,socketClient:a,roomName:n,meetingTitle:s})})}get sfuHandler(){return c(this,ve)}get rejoinRoom(){return c(this,Yc)}reset(t=!0){var e,r,n,i;(r=(e=c(this,ve))==null?void 0:e.cleanupConsumers)==null||r.call(e),(i=(n=c(this,ve))==null?void 0:n.stopAllProducers)==null||i.call(n),c(this,Pn).clear(),this.activatedProducingPeerIds.clear(),t&&(c(this,Ei).stop(),this.sfuHandler.stopAllTransports(),this.sfuHandler.reset(),S(this,Ei,new as))}reconnectTransport(t){return u(this,null,function*(){l.info(`CFNodeClient::Room joining state: ${c(this,Qr)}`),!(!t||c(this,Qr))&&(t.direction==="send"?yield c(this,Qc).call(this,t):yield c(this,Xc).call(this,t))})}setupTransports(t=!1){return u(this,null,function*(){yield c(this,ve).setupTransports(["recv","send"],t)})}stopAllProducers(){return u(this,null,function*(){yield c(this,ve).stopAllProducers()})}joinRoom(t,e){return u(this,arguments,function*(r,n,i={},s=!1,a=!1){c(this,Xr,Rn).mediaJoinAttempted=!0,S(this,Qr,!0),this.reset(s);const o=qe().ipInfo;if(o!=null&&o.loc&&!c(this,Aa)){const h=o.loc.split(",");S(this,Aa,{latitude:parseFloat(h[0]),longitude:parseFloat(h[1])})}let d;try{return d=yield c(this,Ei).push(()=>this._joinRoom(r,n,i,a,c(this,Aa)),"joinRoom"),d}catch(h){d={roomJoined:!1}}return d.roomJoined||b.emit(w.ROOM_NODE_FAILED),d})}_partialJoinRoom(t,e,r=!1,n=void 0){return u(this,null,function*(){const i=qe().ipInfo;let s=n;if(i!=null&&i.loc&&!n){const a=i.loc.split(",");s={latitude:parseFloat(a[0]),longitude:parseFloat(a[1])}}yield wr((a,o)=>(c(this,Mt).isConnected||o(new Error("socket is not connected")),a>0&&l.warn(`retrying sending join room request, count: ${a}`),this.sfuHandler.cfSocketHandler.joinRoom(e,t,r,s).catch(d=>{throw l.error("failed to send join room request, error:",{error:d}),d})),{delayTime:1e3,strategy:"exponential",maxRetryCount:Q.hasFeature(ie.ENABLE_CF_INFINITE_RETRIES)?1/0:3}),yield this.setupTransports(!0)})}partialJoinRoom(t,e,r=!1,n=void 0){return u(this,null,function*(){this.partialJoinRoomPromise=c(this,Ei).push(()=>this._partialJoinRoom(t,e,r,n))})}_joinRoom(t,e){return u(this,arguments,function*(r,n,i={},s=!1,a=null){this.peerDisplayName=r;try{return this.partialJoinRoomPromise?yield this.partialJoinRoomPromise:yield this._partialJoinRoom(r,n,s,a),navigator.product!=="ReactNative"&&setTimeout(()=>u(this,null,function*(){const o={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:n,roomViewType:"groupCall",deviceInfo:X(U({},Te.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};$.roomJoined(o)})),{roomJoined:yield this.completeJoinRoom()}}catch(o){return l.error("error on sending join room request",{error:o}),{roomJoined:!1}}finally{this.partialJoinRoomPromise=void 0}})}completeJoinRoom(){return u(this,null,function*(){try{const{maxPreferredStreams:t,roomState:e}=yield this.sfuHandler.cfSocketHandler.notifySelfJoinComplete();return this.roomUUID=e.roomUuid,this.maxPreferredStreams=t!=null?t:6,S(this,Qr,!1),S(this,ms,!0),this.mediaJoined=!0,b.emit(w.UPDATE_ACTIVE,{createAllConsumers:!0}),!0}catch(t){return l.error("error on completing join room:",{error:t}),!1}})}leaveRoom(){return u(this,null,function*(){c(this,ve).stopAllTransports(),S(this,ms,!1),c(this,Xr,Rn).mediaJoinAttempted=!1;const t={closeRoom:!1};c(this,Mt).sendMessagePromise(ce.leaveRoom,yf.toBinary(t)).then(e=>{var r;(r=Rf.fromBinary(e.payload))!=null&&r.closed||l.warn("weird state on peer closed and should not happen")}).catch(e=>{l.error("error on sending leave room request",{error:e})}),$.callEnded(),y.destruct()})}getConsumers(){return c(this,ve).consumers}activatePeers(t){return u(this,null,function*(){return this.createConsumers(t)})}deactivatePeers(t,e="default"){return u(this,null,function*(){const r=new Set;t.forEach(i=>{i.screenShare&&i.kind==="video"&&r.add(i.producingPeerId)});const n=e==="default"?t.filter(i=>!r.has(i.producingPeerId)).filter(i=>i.kind!=="audio"):t;yield Promise.all(n.map(i=>{const s=this.sfuHandler.producerIdToConsumerIdMap.get(i.producerId);if(!s){l.warn(`consumer not found in deactivate producers: ${i.producerId}`);return}return this.sfuHandler.closeConsumer(s)}))})}createConsumers(t){return u(this,null,function*(){return this.sfuHandler.createConsumers(t)})}pauseConsumers(t){return u(this,null,function*(){t.forEach(e=>{this.sfuHandler.pauseConsumer(e)})})}resumeConsumers(t){return u(this,null,function*(){t.forEach(e=>{this.sfuHandler.resumeConsumer(e)})})}closeConsumers(t){return u(this,null,function*(){yield Promise.all(t.map(e=>{const r=this.sfuHandler.producerIdToConsumerIdMap.get(e.producerId);if(!r){l.warn(`consumer not found in deactivate producers: ${e.producerId}`);return}return this.sfuHandler.closeConsumer(r)}))})}consumePeer(t,e,r){return u(this,null,function*(){if(l.info(`current activated Peer ids: ${JSON.stringify(Array.from(this.activatedProducingPeerIds.values()))}, forced?:${r}`),!this.activatedProducingPeerIds.has(t)||r)try{yield c(this,ve).createConsumers(e),this.activatedProducingPeerIds.add(t)}catch(n){l.error("consumePeer failed in CFNodeClient.ts",{error:n})}else l.info(`not creating consumer for this peerId: ${t}`)})}shareWebcam(t){return u(this,null,function*(){if(t===void 0)return null;if(c(this,ve).producers.has(ne.WEBCAM)){const i=c(this,ve).producers.get(ne.WEBCAM);if(!i.closed&&!navigator.isReactNative)return yield i.replaceTrack({track:t}),yield this.resumeWebcam(),t;yield c(this,ve).removeProducer(ne.WEBCAM)}const e={track:t,codecOptions:{name:"VP8"},appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1};let r=t.getConstraints().width;r in Ug||(r=640),e.encodings=yD[r],Q.hasFeature(ie.ENABLE_CF_SIMULCAST)&&(e.encodings=Ug[r]);const n=()=>{l.info("Disabling video due to the producer closure"),this.disableWebcam()};return c(this,ve).createProducer(ne.WEBCAM,e,n)})}shareScreen(t){return u(this,null,function*(){const{video:e,audio:r}=t;if(e===void 0)return;const n={track:e,codecOptions:{name:"VP8"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1};let i=()=>{l.info("Disabling screenShare due to the producer closure"),this.disableScreenShare()};if(yield c(this,ve).createProducer(ne.SCREENSHARE_VIDEO,n,i),r){const s={track:r,codecOptions:{name:"opus"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1,zeroRtpOnPause:!0};i=()=>{},yield c(this,ve).createProducer(ne.SCREENSHARE_AUDIO,s,i)}$.screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new et("track undefined");if(c(this,ve).producers.has(ne.MIC)){const n=c(this,ve).producers.get(ne.MIC);if(!n.closed&&!navigator.isReactNative){yield n.replaceTrack({track:t}),yield this.resumeMic();return}yield c(this,ve).removeProducer(ne.MIC,!1)}const e={track:t,encodings:[{priority:"high"}],codecOptions:{name:"opus"},appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!0},r=()=>{l.info("Disabling audio due to the producer closure"),this.disableMic()};yield c(this,ve).createProducer(ne.MIC,e,r)}catch(e){throw new _(e)}})}pauseMic(){const t=c(this,ve).producers.get(ne.MIC);if(!t){l.error("pauseMic::could_not_find_mic_producer");return}if(t.paused){l.info("pauseMic::mic_producer_already_paused");return}t.pause();const e={producerId:t.id,pause:!0};c(this,Mt).sendMessage(ce.toggleProducer,pn.toBinary(e))}pauseWebcam(){return u(this,null,function*(){const t=c(this,ve).producers.get(ne.WEBCAM);if(!t){l.error("pauseWebcam::could_not_find_webcam_producer");return}t.pause();const e={producerId:t.id,pause:!0};c(this,Mt).sendMessage(ce.toggleProducer,pn.toBinary(e))})}resumeMic(){return u(this,null,function*(){const t=c(this,ve).producers.get(ne.MIC);if(!t){l.error("resumeMic::could_not_find_mic_producer");return}if(!t.pause){l.info("resumeMic::mic_producer_already_resumed");return}t.resume(),t.appData.e2ee&&b.emit(w.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,Mt).sendMessage(ce.toggleProducer,pn.toBinary(e))})}resumeWebcam(){return u(this,null,function*(){const t=c(this,ve).producers.get(ne.WEBCAM);if(!t){l.error("resumeWebcam::could_not_find_webcam_producer");return}t.resume(),t.appData.e2ee&&b.emit(w.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,Mt).sendMessage(ce.toggleProducer,pn.toBinary(e))})}disableWebcam(){return u(this,null,function*(){yield c(this,ve).removeProducer(ne.WEBCAM)})}disableMic(){return u(this,null,function*(){yield c(this,ve).removeProducer(ne.MIC)})}disableScreenShare(){return u(this,null,function*(){l.info("screen_sharing_stopped"),$.screenShareStop(),yield c(this,ve).removeProducer(ne.SCREENSHARE_VIDEO),yield c(this,ve).removeProducer(ne.SCREENSHARE_AUDIO),c(this,Pn).clear()})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}unmuteSelf(){return u(this,null,function*(){})}resetVideoProducers(t,e){return u(this,null,function*(){t&&(yield c(this,ve).removeProducer(ne.WEBCAM,!1),this.shareWebcam(t)),e&&(yield c(this,ve).removeProducer(ne.SCREENSHARE_VIDEO,!1),this.shareScreen({video:e}))})}changeDisplayName(t,e){return u(this,null,function*(){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!(yield this.sfuHandler.cfSocketHandler.changeDisplayName(r)))throw new Error("failed to change display name!")})}kick(t){return u(this,null,function*(){const e={participantId:t};if(!(yield this.sfuHandler.cfSocketHandler.kickPeer(e)))throw new Error("failed to kickout the participant!")})}kickAll(){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.kickAll()))throw new Error("failed to kickout all participant!")})}muteAll(t){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.hostControlForPeer(t,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(t){return u(this,null,function*(){const e={participantId:t!=null?t:""};try{yield c(this,Mt).sendMessagePromise(ce.globalPinPeer,Ef.toBinary(e))}catch(r){l.error("Error in pinning peer:",{error:r})}})}validateScreenShare(t){return this.peerId===t.peerId&&this.sfuHandler.hasProducer(t.producerId)&&c(this,Pn).add(t.consumerPeerId),c(this,Pn).size}switchConsumersToLayer(t,e){return u(this,null,function*(){this.sfuHandler.switchConsumersToLayer(t,e)})}handleSocketEvents(){return u(this,null,function*(){c(this,Mt).on(ce.peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:r}=Bf.fromBinary(t);if(e===this.peerId)return;l.info(`producer created broadcast: ${e}, producer state: ${r}`),b.emit(w.NEW_PRODUCER,{peerId:e,producer:X(U({},r),{kind:r.kind===Lt.AUDIO?"audio":"video"})})}catch(e){l.error("error in peer-producer-create-broadcast",{error:e})}}),c(this,Mt).on(ce.peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{kind:r,pause:n,producerId:i}}=Cl.fromBinary(t),s=r===Lt.AUDIO?"audio":"video";l.info(`producer toggle broadcast: ${e}, producerId: ${i}, kind:${s}, paused:${n}`),b.emit(w.PRODUCER_TOGGLE,{peerId:e,producerId:i,paused:n,kind:s}),Array.from(this.getConsumers().values()).filter(a=>a.producerId===i).forEach(a=>{a.paused!==n&&(l.debug(`consumer state mismatched for ${a.id}. updating consumer pause state ${a.paused} to ${n}`),n?(a.pause(),b.emit(w.CONSUMER_PAUSED,{id:a.id})):(a.resume(),b.emit(w.CONSUMER_RESUMED,{id:a.id})))})}catch(e){l.error("error in producer toggle broadcast handler",{error:e})}}),c(this,Mt).on(ce.peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=zo.fromBinary(t);if(e===this.peerId)return;l.info(`peer left broadcast:${e}`),c(this,Pn).delete(e),this.sfuHandler.cleanupConsumers(e)}catch(e){l.error("error in peer left broadcast",{error:e})}}),c(this,Mt).on(ce.peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=jf.fromBinary(t);if(e===this.peerId)return;l.info(`producer closed broadcast:${e}`),b.emit(w.PRODUCER_CLOSED,{peerId:e,producerId:r});const n=this.sfuHandler.producerIdToConsumerIdMap.get(r);if(!n){l.warn(`no consumer found for producer:${r}`);return}l.info(`closing consumer ${n}, producer id: ${r}`),this.sfuHandler.closeConsumer(n).then(()=>{l.info(`closed consumer: ${n}`),this.sfuHandler.producerIdToConsumerIdMap.delete(r),b.emit(w.CONSUMER_CLOSED,{id:n})}).catch(i=>{l.error("error closing consumer",{error:i})})}catch(e){l.error("error on producer close broadcast",{error:e})}}),c(this,Mt).on(ce.mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!c(this,Qr)&&!c(this,ms)||(l.warn("media hub termination broadcast received, rejoining room"),b.emit(w.ROOM_NODE_DISCONNECTED),this.rejoinRoom())})})}handleSFUEvents(){c(this,ve).on("reconnect_transport",t=>u(this,null,function*(){try{yield this.reconnectTransport(t),l.info(`transport reconnected [id:${t.id}]`)}catch(e){l.error("error on reconnection transports",{error:e})}})),c(this,ve).on("rejoin",t=>{var e;if(((e=c(this,Xr,Rn).socketState)==null?void 0:e.state)!=="connected"){l.warn("Ignoring rejoin attempt because socket is not connected");return}if(c(this,Si)>3&&!t){l.warn("cannot rejoin more already rejoined 3 times");return}if(c(this,Qr)&&!t){l.warn("room joining in progress, cannot start rejoining");return}S(this,Si,c(this,Si)+1),l.warn(`rejoining the room because transports are failing. [rejoinCount: ${c(this,Si)}]`),this.mediaJoined=!1,b.emit(w.ROOM_NODE_DISCONNECTED),this.rejoinRoom()})}handleCallstatsEvents(){$.onConsumerScore(t=>{t.forEach((e,r)=>{const n=this.sfuHandler.consumers.get(r);n&&b.emit(w.CONSUMER_SCORE_UPDATE,{id:r,kind:n.kind,peerId:n.peerId,score:e.score,scoreStats:e})})}),$.onProducerScore(t=>{t.forEach((e,r)=>{const n=Array.from(this.sfuHandler.producers.values()).find(i=>i.id===r);n&&b.emit(w.PRODUCER_SCORE_UPDATE,{id:r,kind:n.kind,appData:n.appData,score:e.score,scoreStats:e})})})}},Mt=new WeakMap,ve=new WeakMap,Qr=new WeakMap,ms=new WeakMap,Si=new WeakMap,Ei=new WeakMap,Yc=new WeakMap,Qc=new WeakMap,Xc=new WeakMap,Pn=new WeakMap,Aa=new WeakMap,Xr=new WeakSet,Rn=function(){return this.context.getValue("connectionHandler")},kv);let ue=_v;pe([y.trace("CFNodeClient.reset")],ue.prototype,"reset",1),pe([y.trace("CFNodeClient.reconnect")],ue.prototype,"reconnectTransport",1),pe([y.trace("CFNodeClient.setupTransport")],ue.prototype,"setupTransports",1),pe([y.trace("CFNodeClient.stopAllProducers")],ue.prototype,"stopAllProducers",1),pe([y.trace("CFNodeClient.joinRoom")],ue.prototype,"joinRoom",1),pe([y.trace("CFNodeClient.completeJoinRoom")],ue.prototype,"completeJoinRoom",1),pe([y.trace("CFNodeClient.leaveRoom")],ue.prototype,"leaveRoom",1),pe([y.trace("CFNodeClient.activatePeers")],ue.prototype,"activatePeers",1),pe([y.trace("CFNodeClient.deactivatePeers")],ue.prototype,"deactivatePeers",1),pe([y.trace("CFNodeClient.createConsumers")],ue.prototype,"createConsumers",1),pe([y.trace("CFNodeClient.pauseConsumers")],ue.prototype,"pauseConsumers",1),pe([y.trace("CFNodeClient.resumeConsumers")],ue.prototype,"resumeConsumers",1),pe([y.trace("CFNodeClient.closeConsumers")],ue.prototype,"closeConsumers",1),pe([y.trace("CFNodeClient.consumePeer")],ue.prototype,"consumePeer",1),pe([y.trace("CFNodeClient.shareWebcam")],ue.prototype,"shareWebcam",1),pe([y.trace("CFNodeClient.shareScreen")],ue.prototype,"shareScreen",1),pe([y.trace("CFNodeClient.shareMic")],ue.prototype,"shareMic",1),pe([y.trace("CFNodeClient.pauseMic")],ue.prototype,"pauseMic",1),pe([y.trace("CFNodeClient.pauseWebcam")],ue.prototype,"pauseWebcam",1),pe([y.trace("CFNodeClient.resumeMic")],ue.prototype,"resumeMic",1),pe([y.trace("CFNodeClient.resumeWebcam")],ue.prototype,"resumeWebcam",1),pe([y.trace("CFNodeClient.disableWebcam")],ue.prototype,"disableWebcam",1),pe([y.trace("CFClient.disableMic")],ue.prototype,"disableMic",1),pe([y.trace("CFClient.disableScreenShare")],ue.prototype,"disableScreenShare",1),pe([y.trace("CFNodeClient.muteSelf")],ue.prototype,"muteSelf",1),pe([y.trace("CFNodeClient.resetVideoProducers")],ue.prototype,"resetVideoProducers",1),pe([y.trace("CFNodeClient.changeDisplayName")],ue.prototype,"changeDisplayName",1),pe([y.trace("CFNodeClient.kickPeer")],ue.prototype,"kick",1),pe([y.trace("CFNodeClient.kickAllPeers")],ue.prototype,"kickAll",1),pe([y.trace("CFNodeClient.muteAll")],ue.prototype,"muteAll",1),pe([y.trace("CFNodeClient.muteAllVideo")],ue.prototype,"muteAllVideo",1),pe([y.trace("CFNodeClient.disableAudio")],ue.prototype,"disableAudio",1),pe([y.trace("CFNodeClient.disableVideo")],ue.prototype,"disableVideo",1),pe([y.trace("CFNodeClient.pinPeer")],ue.prototype,"pinPeer",1),pe([y.trace("CFNodeClient.validateScreenShare")],ue.prototype,"validateScreenShare",1),pe([y.trace("CFNodeClient.init")],ue,"init",1);function X1(t,e){return u(this,null,function*(){const r=t.getValue("roomNodeClient");if(r){if(r instanceof le)return r;throw new Error("Room Node Client already setup")}const n=yield le.init(t,e);return t.setValue("roomNodeClient",n),n})}function Z1(t,e){return u(this,null,function*(){const r=t.getValue("roomNodeClient");if(r){if(r instanceof ue)return r;throw new Error("Room Node Client already setup")}const n=yield ue.init(t,e);return t.setValue("roomNodeClient",n),n})}function bv(t,e){return u(this,arguments,function*(r,n,i=cs.HIVE){return i===cs.CF?Z1(r,n):X1(r,n)})}function wv(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch(r){l.error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var eO=Object.defineProperty,tO=Object.getOwnPropertyDescriptor,rO=(t,e,r,n)=>{for(var i=n>1?void 0:n?tO(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&eO(e,r,i),i};let fs;var Zc,Iv;const Cv=(Iv=class{constructor(t,e){f(this,"socket"),T(this,Zc,void 0),S(this,Zc,e),this.socket=t,this.handleSocketEvents()}static create(t,e){return fs||(fs=new Cv(t,e)),fs}static cleanup(){var t;try{(t=fs==null?void 0:fs.socket)==null||t.disconnect()}catch(e){l.error("roomSocketHandler::cleanup")}fs=void 0}joinRoom(t,e){return u(this,null,function*(){var r;this.socket.joinAttempted=!0;const n={capabilities:[],peer:{displayName:(r=t.name)!=null?r:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},i=this.socket.sendMessagePromise(j.joinRoom,AC.toBinary(n));try{const{peer:s}=Fi.fromBinary((yield i).payload);c(this,Zc).getValue("connectionHandler").socketJoined=!0,b.emit(w.SOCKET_SERVICE_ROOM_JOINED,{peer:s});const a=this.getRoomState(),o=this.getRoomPeersNonPaginated(),[{room:d},{peers:h}]=yield Promise.all([a,o]);return b.emit(w.ROOM_STATE,d),b.emit(w.SOCKET_PEERS,h),{peer:s}}catch(s){throw l.error("RoomSocketHandler.joinRoom.failed",{error:s}),new _("Error: RoomSocketHandler.joinRoom failed.","0002",s)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return mP.fromBinary((yield this.socket.sendMessagePromise(j.getAllAddedParticipants)).payload).participants.map(t=>{var e=t,{id:r}=e,n=po(e,["id"]);return X(U({},n),{userId:r})})}catch(t){return[]}})}getRoomPeers(t,e,r){return u(this,null,function*(){let n;try{const i={seachQuery:t,limit:e,offset:r},s=yield this.socket.sendMessagePromise(j.getRoomPeersInfo,EC.toBinary(i));n=Ml.fromBinary(s.payload)}catch(i){l.error("getRoomPeers::binary_decode_error",{error:i})}return n})}getRoomPeersNonPaginated(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(j.getRoomPeersInfo);t=Ml.fromBinary(e.payload)}catch(e){l.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getStagePeers(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(j.getRoomPeersInfo);t=Ml.fromBinary(e.payload)}catch(e){l.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getPeerInfo(t){return u(this,null,function*(){let e;try{const r=yield this.socket.sendMessagePromise(j.getPeerInfo,qf.toBinary({peerId:t}));e=Fi.fromBinary(r.payload)}catch(r){l.error("getPeerInfo::binary_decode_error",{error:r})}return e})}getRoomState(){return u(this,null,function*(){let t=Gf.create();try{const e=yield this.socket.sendMessagePromise(j.getRoomInfo);t=Gf.fromBinary(e.payload)}catch(e){l.error("getRoomState::binary_decode_error",{error:e})}return t})}getRoomStageState(){return u(this,null,function*(){let t=Xf.create();try{const e=yield this.socket.sendMessagePromise(j.getRoomStageState);t=Xf.fromBinary(e.payload)}catch(e){l.error("getRoomStageState::binary_decode_error",{error:e})}return t})}broadcastMessage(t,e){return u(this,null,function*(){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(j.broadcastMessage,Vs.toBinary(r))})}broadcastToMeetings(t,e,r){return u(this,null,function*(){const n={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(j.broadcastToEntity,Vs.toBinary(n))})}broadcastToPeers(t,e,r){return u(this,null,function*(){const n={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(j.broadcastToEntity,Vs.toBinary(n))})}leaveRoom(){return u(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(j.leaveRoom,DC.toBinary({}))})}kick(t){return u(this,null,function*(){const e={peerIds:[t]};this.socket.sendMessage(j.kick,yP.toBinary(e))})}kickAll(t=!1){return u(this,null,function*(){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(j.kickAll,wl.toBinary(e))})}getWaitingRoomRequests(){this.socket.sendMessage(j.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(j.acceptWaitingRoomRequests,TP.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(j.denyWaitingRoomRequests,_P.toBinary(e))}updatePermissions(t,e){return u(this,null,function*(){const r={updatePeersPresets:[]};return t.forEach(n=>{r.updatePeersPresets.push({userIds:n,patch:e})}),this.socket.sendMessagePromise(ec.updateUserPreset,XP.toBinary(r))})}handleSocketEvents(){this.socket.on(j.broadcastMessage,({payload:t})=>{try{const e=Vs.fromBinary(t);b.emit(w.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){l.error("failed to decode broadcast message:",e)}}),this.socket.on(j.broadcastToEntity,({payload:t})=>{try{const e=Vs.fromBinary(t);b.emit(w.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){l.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,n;switch(t){case j.joinRoom:case j.leaveRoom:case j.kick:case j.kickAll:{r=Fi.fromBinary.bind(Fi),n=Fi.create();break}case j.getWaitingRoomRequests:{r=(i,s)=>i?Qf.fromBinary(i,s):{requests:[]},n=Qf.create();break}case j.recordingPaused:case j.recordingStarted:case j.recordingStopped:{r=lg.fromBinary.bind(lg);break}case ec.updateUserPreset:{r=eg.fromBinary.bind(eg);break}case ce.peerJoinedBroadcast:case oe.peerJoinedBroadcast:{r=Vf.fromBinary.bind(Vf);break}case ce.selfJoinComplete:case oe.selfJoinComplete:{r=qo.fromBinary.bind(qo);break}case ce.globalPeerPinBroadcast:case oe.globalPeerPinBroadcast:{r=Hf.fromBinary.bind(Hf);break}case ce.selectedPeer:case oe.selectedPeer:{r=Il.fromBinary.bind(Il);break}case ce.selectedPeerDiff:case oe.selectedPeerDiff:{r=Pf.fromBinary.bind(Pf);break}case ce.leaveRoom:case oe.leaveRoom:{r=zo.fromBinary.bind(zo);break}}this.socket.on(t,({payload:i})=>{let s=n;if(!r)return e(void 0);try{s=r(i)}catch(a){l.error("roomSocketHandler::on::binary_decode_error",{error:a})}return e(s)})}getUserPermissions(t){return u(this,null,function*(){const e={userIds:[t]};try{const r=yield this.socket.sendMessagePromise(ec.getUserPresets,JP.toBinary(e)),n=KP.fromBinary(r.payload).peerPresets[0],i=new TextDecoder().decode(n.preset),s=JSON.parse(i).permissions;return{chat:s.chat,polls:s.polls,plugins:s.plugins}}catch(r){throw l.error("Error in getting user preset",{error:r}),r}})}},Zc=new WeakMap,Iv);let ed=Cv;rO([y.trace("RoomSocketHandler.joinRoom")],ed.prototype,"joinRoom",1);var nO=Object.defineProperty,iO=Object.getOwnPropertyDescriptor,Ti=(t,e,r,n)=>{for(var i=n>1?void 0:n?iO(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&nO(e,r,i),i},ki,Ir,St,Kt,tr,Pv;const Rv=(Pv=class{constructor(t,e,r,n){T(this,Kt),f(this,"self"),f(this,"authToken"),T(this,ki,void 0),f(this,"viewType"),T(this,Ir,void 0),T(this,St,void 0);const{socket:i}=r,s=t.getValue("authToken");this.self=e,S(this,St,t),this.viewType=n,this.authToken=s,S(this,ki,i),S(this,Ir,r),e.config.viewType!==gt.Chat&&this.setupEvents()}get peerId(){return c(this,St).getValue("peerId")}get mediaJoined(){return c(this,St).getValue("connectionHandler").mediaJoined}static init(t,e,r,n,i){return u(this,null,function*(){const s=qe(),a=t.getValue("peerId"),o=!!t.getValue("cachedUserDetails"),d=yield ct.__init__(t,r,n,i,i.name,o);if(navigator.product!=="ReactNative"){const h=!Q.hasFeature(ie.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const p=yield d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(p)}),$.devices("AUDIO",p==null?void 0:p.filter(m=>m.kind==="audioinput")),$.devices("VIDEO",p==null?void 0:p.filter(m=>m.kind==="videoinput")),$.devices("SPEAKER",p==null?void 0:p.filter(m=>m.kind==="audiooutput")),l.info("Callstats:: initializing");try{yield $.initialize({peerId:a,engineName:Te.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield s.getICEServers(),apiBase:t.getValue("apiBase"),flags:Q.getAllFlags(),logger:l,apiHostnames:nf(t),skipConnectivityChecks:h}),l.info("Callstats:: initialized")}catch(m){l.error("Callstats:: initialization failed",{error:m})}}),0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new Rv(t,d,e,i.viewType)})}shareMediaTracks(){return u(this,null,function*(){var t;const{audioTrack:e,videoTrack:r,permissions:n,audioEnabled:i,videoEnabled:s,screenShareEnabled:a,screenShareTracks:o}=this.self;if(n.canProduceAudio&&i)try{yield c(this,Kt,tr).shareMic(e)}catch(d){this.self.disableAudio()}if(n.canProduceVideo&&s)try{const d=yield c(this,Kt,tr).shareWebcam(r);d&&d.id!==r.id&&Q.hasFeature(ie.EXP_RESHARE)&&(yield c(this,Kt,tr).shareWebcam(d))}catch(d){this.self.disableVideo()}if(n.canProduceScreenshare&&a)try{yield(t=c(this,Kt,tr))==null?void 0:t.shareScreen({video:o.video,audio:o.audio})}catch(d){this.self.disableScreenShare()}})}kickHandler(t){return u(this,null,function*(){let e="kicked";(t==null?void 0:t.kickType)==="kickAll"&&(e="ended"),this.leaveRoom(e)})}waitlistedHandler(){l.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(l.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){l.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(l.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){l.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}resetSelf(t){return u(this,null,function*(){$.callEnded(),c(this,Kt,tr).reset(),t&&(yield this.joinRoom(t))})}setupEvents(){b.on(w.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),b.on(w.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),b.on(w.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),b.on(w.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),b.on(w.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{t===!1&&(this.self.roomState="init"),this.resetSelf(t)}),b.on(w.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;t&&Q.hasFeature(ie.REFRESH_ID_ON_DISCONNECTION)&&(e=Un()),c(this,ki).updateURL(e),y.resetPeerId(e),qe().setHeader("dyte-tracing-id",e),qn.remapContext(e,c(this,St)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),b.on(w.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),c(this,Ir).on(j.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),c(this,Ir).on(ec.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&b.emit(w.UPDATE_PERMISSIONS,e.patch)})}),c(this,Ir).on(j.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),c(this,Ir).on(j.kick,()=>{this.kickHandler({kickType:"kick"})}),c(this,Ir).on(j.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),b.onAsync(w.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),b.on(w.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:r,scoreStats:n})=>{var i;const s=(i=r==null?void 0:r.screenShare)!=null?i:!1;this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:s,score:t,participantId:this.self.id,scoreStats:n})}),b.on(w.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),$.audioOff())})),b.on(w.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),$.videoOff())})),b.onAsync(w.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),b.on(w.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return u(this,null,function*(){try{const{peer:e}=yield c(this,Ir).joinRoom(this.self,this.self.config.viewType);c(this,Ir).socket.flush();const r=eu(e.stageType);if(c(this,St).setValue("stageStatus",r,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),c(this,St).notify("stageStatus")}catch(e){throw l.error("Error in joinRoom",{error:e}),e}})}leaveRoom(t="left"){return u(this,null,function*(){var e,r;if(t==="rejected"){try{(e=c(this,ki))==null||e.disconnect()}catch(n){l.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),c(this,St).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),c(this,St).notify("stageStatus");try{(r=c(this,ki))==null||r.disconnect()}catch(n){l.error("SelfController::leaveRoom::socketDisconnect")}wv(c(this,St)),ed.cleanup(),this.self.roomState=t,this.self.emit("roomLeft",{state:t})})}partialMediaRoom(){var t;(t=c(this,Kt,tr))==null||t.partialJoinRoom(this.self.name,c(this,St).getValue("meetingId"),void 0)}joinMediaRoom(t=!1){return u(this,null,function*(){var e,r;const{peerId:n,viewType:i,meetingId:s,authToken:a,stageStatus:o,roomNodeOptions:d}=c(this,St).getAllValues(),{sfu:h,roomNodeUrl:p,meetingTitle:m}=d;try{if(i===gt.Livestream){if(o!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}yield bv(c(this,St),{socket:c(this,ki),peerId:n,meetingId:s,authToken:a,roomNodeUrl:p,meetingTitle:m},h)}const{roomJoined:g}=(r=yield(e=c(this,Kt,tr))==null?void 0:e.joinRoom(this.self.name,s,{audio:this.self.audioEnabled,video:this.self.videoEnabled,screen:this.self.screenShareEnabled},t,t))!=null?r:{};if(!g)return;o==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(g){throw l.error("Error:SelfController.mediaRoomJoin",g),new _("Error: could not join media room","0002")}})}leaveMediaRoom(t){return u(this,null,function*(){const e=c(this,St).getValue("viewType");t!=="connected-meeting"&&(yield this.cleanupSelf()),!(t==="stageLeft"&&e===gt.Webinar)&&c(this,Kt,tr)&&(c(this,Kt,tr).mediaJoined&&t!=="disconnected"&&(yield c(this,Kt,tr).leaveRoom()),!(t==="stageLeft"&&e===gt.Livestream)&&(c(this,Kt,tr).mediaJoined=!1))})}cleanupSelf(){return u(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()})}},ki=new WeakMap,Ir=new WeakMap,St=new WeakMap,Kt=new WeakSet,tr=function(){return c(this,St).getValue("roomNodeClient")},Pv);let An=Rv;Ti([y.trace("SelfController.resetSelf")],An.prototype,"resetSelf",1),Ti([y.trace("SelfController.setupEvents")],An.prototype,"setupEvents",1),Ti([y.trace("SelfController.joinRoom")],An.prototype,"joinRoom",1),Ti([y.trace("SelfController.leaveRoom")],An.prototype,"leaveRoom",1),Ti([y.trace("SelfController.joinMediaRoom")],An.prototype,"joinMediaRoom",1),Ti([y.trace("SelfController.leaveMediaRoom")],An.prototype,"leaveMediaRoom",1),Ti([y.trace("SelfController.init")],An,"init",1);var td;class sO{constructor(e){T(this,td,void 0),S(this,td,e)}on(e,r){let n;e===j.roomPeerCount?n=$f.fromBinary.bind($f):n=ag.fromBinary.bind(ag),c(this,td).on(e,({payload:i})=>{const s=n(i);return r(s)})}}td=new WeakMap;var rd;class aO{constructor(e){T(this,rd,void 0),S(this,rd,e)}on(e,r){let n,i;switch(e){case j.transcript:{n=Pl.fromBinary.bind(Pl),i=Pl.create();break}default:{l.debug("AISocketHandler switch case hit default, event not accounted for.");break}}c(this,rd).on(e,({payload:s})=>{let a=i;try{a=n(s)}catch(o){l.error("chatSocketHandler::on::binary_decode_error",{error:o})}return r(a)})}}rd=new WeakMap;var oO=Object.defineProperty,cO=Object.getOwnPropertyDescriptor,Ou=(t,e,r,n)=>{for(var i=n>1?void 0:n?cO(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&oO(e,r,i),i},Mn;class nd{constructor(e){T(this,Mn,void 0),S(this,Mn,e)}getPolls(){return c(this,Mn).sendMessagePromise(Nr.getPolls)}createPoll(e,r,n=!1,i=!1){const s={anonymous:n,hideVotes:i,question:e,options:r};return c(this,Mn).sendMessage(Nr.createPoll,$A.toBinary(s))}votePoll(e,r){const n={index:r,pollId:e};return c(this,Mn).sendMessage(Nr.votePoll,GA.toBinary(n))}on(e,r){let n,i;switch(e){case Nr.updatePoll:case Nr.createPoll:case Nr.votePoll:{n=jl.fromBinary.bind(jl),i=jl.create();break}}c(this,Mn).on(e,({payload:s})=>{let a=i;try{a=n(s)}catch(o){l.error("pollSocketHandler::on::binary_decode_error",{error:o})}return r(a)})}removeListeners(e){c(this,Mn).removeListeners(e)}}Mn=new WeakMap,Ou([y.trace("PollSocketHandler.getPolls")],nd.prototype,"getPolls",1),Ou([y.trace("PollSocketHandler.createPoll")],nd.prototype,"createPoll",1),Ou([y.trace("PollSocketHandler.votePoll")],nd.prototype,"votePoll",1);var Yt;class dO{constructor(e){T(this,Yt,void 0),S(this,Yt,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield c(this,Yt).sendMessagePromise(j.getStageRequests);return e?Bl.fromBinary(e):{stageRequests:[]}})}requestAccess(){c(this,Yt).sendMessage(j.requestStageAccess)}cancelRequestAccess(){c(this,Yt).sendMessage(j.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const r={userIds:e};c(this,Yt).sendMessage(j.grantStageAccess,NA.toBinary(r))})}denyAccess(e){return u(this,null,function*(){const r={userIds:e};c(this,Yt).sendMessage(j.denyStageAccess,xA.toBinary(r))})}joinStage(){return c(this,Yt).sendMessagePromise(j.joinStage,void 0,void 0,j.peerStageStatusUpdate)}leaveStage(e){const r={userIds:[e]};return c(this,Yt).sendMessagePromise(j.leaveStage,cg.toBinary(r),void 0,j.peerStageStatusUpdate)}kick(e){const r={userIds:e};return c(this,Yt).sendMessagePromise(j.leaveStage,cg.toBinary(r))}on(e,r){let n;switch(e){case j.grantStageAccess:case j.denyStageAccess:{n=void 0;break}case j.getStagePeers:{n=og.fromBinary.bind(og);break}case j.getStageRequests:case j.requestStageAccess:case j.cancelStageRequest:{n=Bl.fromBinary.bind(Bl);break}case j.peerStageStatusUpdate:{n=Wf.fromBinary.bind(Wf);break}}c(this,Yt).on(e,({payload:i,id:s})=>{if(!i||!n)return r(void 0,s);const a=n(i);return r(a,s)})}getPeerInfo(e){return u(this,null,function*(){const r=yield c(this,Yt).sendMessagePromise(j.getPeerInfo,qf.toBinary({peerId:e}));return Fi.fromBinary(r.payload)})}}Yt=new WeakMap;var dt;class lO{constructor(e){T(this,dt,void 0),S(this,dt,e)}addPlugin(e,r){c(this,dt).sendMessage(z.addPlugin,QR.toBinary({pluginId:e,staggered:r}))}removePlugin(e){c(this,dt).sendMessage(z.removePlugin,ZR.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield c(this,dt).sendMessagePromise(z.getPlugins);return e?kA.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,r,n){const i={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};c(this,dt).sendMessage(z.customPluginEventToRoom,dA.toBinary(i),n)}customPluginEventToPeers(e,r,n,i){const s={pluginId:e,peerIds:r,pluginData:new TextEncoder().encode(JSON.stringify(n))};c(this,dt).sendMessage(z.customPluginEventToPeers,uA.toBinary(s),i)}enablePluginForRoom(e,r){c(this,dt).sendMessage(z.enablePluginForRoom,tA.toBinary({pluginId:e}),r)}enablePluginForPeers(e,r,n){c(this,dt).sendMessage(z.enablePluginForPeers,sA.toBinary({pluginId:e,peerIds:r}),n)}disablePluginForRoom(e,r){c(this,dt).sendMessage(z.disablePluginForRoom,nA.toBinary({pluginId:e}),r)}disablePluginForPeers(e,r,n){c(this,dt).sendMessage(z.disablePluginForPeers,oA.toBinary({pluginId:e,peerIds:r}),n)}storeInsertKeys(e,r,n,i){const s={pluginId:e,storeName:r,insertKeys:n.map(a=>({storeKey:a.key,payload:new TextEncoder().encode(JSON.stringify(a.payload))}))};c(this,dt).sendMessage(z.storeInsertKeys,rg.toBinary(s),i)}storeGetKeys(e,r,n,i){const s={pluginId:e,storeName:r,getKeys:n.map(a=>({storeKey:a.key}))};c(this,dt).sendMessage(z.storeGetKeys,fA.toBinary(s),i)}storeDeleteKeys(e,r,n,i){const s={pluginId:e,storeName:r,deleteKeys:n.map(a=>({storeKey:a.key}))};c(this,dt).sendMessage(z.storeDeleteKeys,vA.toBinary(s),i)}storeDelete(e,r,n){c(this,dt).sendMessage(z.storeDelete,SA.toBinary({pluginId:e,storeName:r}),n)}getPluginDataOld(e,r){l.info("getPluginDataOld",{plugin:{id:e,storeName:r}})}storePluginDataOld(e,r,n){const i={pluginId:e,storeName:r,insertKeys:[{storeKey:n.key,payload:new TextEncoder().encode(JSON.stringify(n))}]};c(this,dt).sendMessage(z.storeInsertKeys,rg.toBinary(i))}on(e,r){let n;switch(e){case z.addPlugin:case z.enablePluginForPeers:case z.enablePluginForRoom:{n=Ul.fromBinary.bind(Ul);break}case z.removePlugin:case z.disablePluginForPeers:case z.disablePluginForRoom:{n=ng.fromBinary.bind(ng);break}case z.customPluginEventToPeers:case z.customPluginEventToRoom:{n=sg.fromBinary.bind(sg);break}case z.storeInsertKeys:case z.storeGetKeys:case z.storeDeleteKeys:case z.storeDelete:{n=ig.fromBinary.bind(ig);break}}c(this,dt).on(e,({payload:i,id:s})=>{const a=n(i);return r(a,s)})}}dt=new WeakMap;var uO=Object.defineProperty,hO=(t,e,r)=>e in t?uO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,pO=(t,e,r)=>(hO(t,typeof e!="symbol"?e+"":e,r),r),Nu=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},F=(t,e,r)=>(Nu(t,e,"read from private field"),r?r.call(t):e.get(t)),Me=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},Se=(t,e,r,n)=>(Nu(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),Oe=(t,e,r)=>(Nu(t,e,"access private method"),r),Dn,_i,bi,Be,wi,Ne,ze,On,lt,Zr,Nn,fr,gs,en,Lu,Av,Ma,id,xu,Mv,Fu,Dv,sd,Vu,Uu,Ov,Da,ad,Oa,od,cd,Bu,vs,Na,La,dd,ju={exports:{}},ys=typeof Reflect=="object"?Reflect:null,Nv=ys&&typeof ys.apply=="function"?ys.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},ld;ys&&typeof ys.ownKeys=="function"?ld=ys.ownKeys:Object.getOwnPropertySymbols?ld=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:ld=function(t){return Object.getOwnPropertyNames(t)};function mO(t){console&&console.warn&&console.warn(t)}var Lv=Number.isNaN||function(t){return t!==t};function ke(){ke.init.call(this)}ju.exports=ke,ju.exports.once=yO,ke.EventEmitter=ke,ke.prototype._events=void 0,ke.prototype._eventsCount=0,ke.prototype._maxListeners=void 0;var xv=10;function ud(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(ke,"defaultMaxListeners",{enumerable:!0,get:function(){return xv},set:function(t){if(typeof t!="number"||t<0||Lv(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");xv=t}}),ke.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},ke.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Lv(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 Fv(t){return t._maxListeners===void 0?ke.defaultMaxListeners:t._maxListeners}ke.prototype.getMaxListeners=function(){return Fv(this)},ke.prototype.emit=function(t){for(var e=[],r=1;r<arguments.length;r++)e.push(arguments[r]);var n=t==="error",i=this._events;if(i!==void 0)n=n&&i.error===void 0;else if(!n)return!1;if(n){var s;if(e.length>0&&(s=e[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var o=i[t];if(o===void 0)return!1;if(typeof o=="function")Nv(o,this,e);else for(var d=o.length,h=Hv(o,d),r=0;r<d;++r)Nv(h[r],this,e);return!0};function Vv(t,e,r,n){var i,s,a;if(ud(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),a=s[e]),a===void 0)a=s[e]=r,++t._eventsCount;else if(typeof a=="function"?a=s[e]=n?[r,a]:[a,r]:n?a.unshift(r):a.push(r),i=Fv(t),i>0&&a.length>i&&!a.warned){a.warned=!0;var o=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");o.name="MaxListenersExceededWarning",o.emitter=t,o.type=e,o.count=a.length,mO(o)}return t}ke.prototype.addListener=function(t,e){return Vv(this,t,e,!1)},ke.prototype.on=ke.prototype.addListener,ke.prototype.prependListener=function(t,e){return Vv(this,t,e,!0)};function fO(){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 Uv(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=fO.bind(n);return i.listener=r,n.wrapFn=i,i}ke.prototype.once=function(t,e){return ud(e),this.on(t,Uv(this,t,e)),this},ke.prototype.prependOnceListener=function(t,e){return ud(e),this.prependListener(t,Uv(this,t,e)),this},ke.prototype.removeListener=function(t,e){var r,n,i,s,a;if(ud(e),n=this._events,n===void 0)return this;if(r=n[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete n[t],n.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(i=-1,s=r.length-1;s>=0;s--)if(r[s]===e||r[s].listener===e){a=r[s].listener,i=s;break}if(i<0)return this;i===0?r.shift():gO(r,i),r.length===1&&(n[t]=r[0]),n.removeListener!==void 0&&this.emit("removeListener",t,a||e)}return this},ke.prototype.off=ke.prototype.removeListener,ke.prototype.removeAllListeners=function(t){var e,r,n;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[t]),this;if(arguments.length===0){var i=Object.keys(r),s;for(n=0;n<i.length;++n)s=i[n],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=r[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(n=e.length-1;n>=0;n--)this.removeListener(t,e[n]);return this};function Bv(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?vO(i):Hv(i,i.length)}ke.prototype.listeners=function(t){return Bv(this,t,!0)},ke.prototype.rawListeners=function(t){return Bv(this,t,!1)},ke.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):jv.call(t,e)},ke.prototype.listenerCount=jv;function jv(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}ke.prototype.eventNames=function(){return this._eventsCount>0?ld(this._events):[]};function Hv(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function gO(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function vO(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function yO(t,e){return new Promise(function(r,n){function i(a){t.removeListener(e,s),n(a)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}Wv(t,e,s,{once:!0}),e!=="error"&&SO(t,i,{once:!0})})}function SO(t,e,r){typeof t.on=="function"&&Wv(t,"error",e,r)}function Wv(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var EO=ju.exports;class TO extends E{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 $v=new TO;class Jv{static encode(e){return $v.toBinary(e)}static decode(e){return $v.fromBinary(new Uint8Array(e))}}function kO(t,e){return Math.floor(Math.random()*(e-t+1)+t)}class _O{constructor(e={}){pO(this,"opts"),Me(this,Dn,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},Se(this,Dn,0)}wait(){return u(this,null,function*(){Se(this,Dn,F(this,Dn)+1);const e=kO(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*rS(2,F(this,Dn))));yield new Promise(r=>{setTimeout(r,e)})})}getAttempts(){return F(this,Dn)}reset(){Se(this,Dn,0)}}Dn=new WeakMap;const Ln={debug:0,info:1,warn:2,error:3};class bO{constructor(e){Me(this,_i,void 0),Me(this,bi,void 0),Se(this,_i,console),Se(this,bi,e)}debug(...e){Ln[F(this,bi)]>Ln.debug||F(this,_i).debug("[Sockrates]:",...e)}info(...e){Ln[F(this,bi)]>Ln.info||F(this,_i).info("[Sockrates]:",...e)}warn(...e){Ln[F(this,bi)]>Ln.warn||F(this,_i).warn("[Sockrates]:",...e)}error(...e){Ln[F(this,bi)]>Ln.error||F(this,_i).error("[Sockrates]:",...e)}}_i=new WeakMap,bi=new WeakMap;var Gv=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(Gv||{});const wO="2",IO="3";class CO{constructor(e,r){Me(this,Lu),Me(this,Ma),Me(this,xu),Me(this,Fu),Me(this,sd),Me(this,Uu),Me(this,Da),Me(this,Oa),Me(this,cd),Me(this,vs),Me(this,La),Me(this,Be,void 0),Me(this,wi,void 0),Me(this,Ne,void 0),Me(this,ze,void 0),Me(this,On,void 0),Me(this,lt,void 0),Me(this,Zr,void 0),Me(this,Nn,void 0),Me(this,fr,void 0),Me(this,gs,void 0),Me(this,en,void 0);var n,i,s,a,o,d,h,p,m,g;Se(this,wi,e),Se(this,On,[]),Se(this,lt,new EO),Se(this,Zr,!0),Se(this,fr,!1),Se(this,Ne,r!=null?r:{}),(n=F(this,Ne)).autoReconnect!=null||(n.autoReconnect=!0),(i=F(this,Ne)).retryConnectionInterval!=null||(i.retryConnectionInterval=1e3),(s=F(this,Ne)).pingTimeout!=null||(s.pingTimeout=3e4),(a=F(this,Ne)).connectionTimeout!=null||(a.connectionTimeout=5e3),(o=F(this,Ne)).debug!=null||(o.debug=!0),(d=F(this,Ne)).maxReconnectionAttempts!=null||(d.maxReconnectionAttempts=10),(h=F(this,Ne)).disconnectOnPingTimeout!=null||(h.disconnectOnPingTimeout=!0),(p=F(this,Ne)).queueOnDisconnect!=null||(p.queueOnDisconnect=!1),(m=F(this,Ne)).flushOnReconnect!=null||(m.flushOnReconnect=!1),Se(this,Nn,{code:void 0,reason:void 0}),Se(this,ze,(g=F(this,Ne).logger)!=null?g:new bO(F(this,Ne).debug?"debug":"info")),Se(this,en,new _O)}get readyState(){var e;return(e=F(this,Be))==null?void 0:e.readyState}get url(){return F(this,wi)}updateURL(e){Se(this,wi,e),Oe(this,Uu,Ov).call(this)}get config(){return F(this,Ne)}get sendQueue(){return F(this,On)}flush(){if(!F(this,Ne).queueOnDisconnect)return!1;const e=[];return F(this,On).forEach(r=>{this.send(r.event,r.id,r.payload,r.metadata)||e.push(r)}),Se(this,On,e),F(this,On)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){F(this,ze).debug("Websocket was already connecting or connected.");return}if(F(this,Zr)!==!1)return new Promise((r,n)=>{Oe(this,vs,Na).call(this),Oe(this,La,dd).call(this);try{Se(this,Be,new WebSocket(Oe(this,Lu,Av).call(this,F(this,wi)))),F(this,Be).binaryType="arraybuffer",F(this,ze).debug("Connecting to",F(this,wi));const i=setTimeout(()=>{F(this,ze).debug("Connection timeout. Closing socket"),Se(this,Zr,!0),Oe(this,La,dd).call(this),F(this,Be).close(3001,"Connection Timeout"),F(this,Ne).autoReconnect&&!F(this,fr)&&(F(this,lt).emit("reconnecting"),Oe(this,Da,ad).call(this)),n(new Error("Connection timed out!"))},F(this,Ne).connectionTimeout);F(this,Be).onopen=()=>{F(this,ze).debug(`Ready State: ${Gv[F(this,Be).readyState]}`),i&&clearTimeout(i),Oe(this,cd,Bu).call(this),Se(this,Nn,{code:void 0,reason:void 0}),F(this,lt).emit("connected"),F(this,Ne).flushOnReconnect&&this.flush(),r()},F(this,Be).onclose=s=>{try{i&&clearTimeout(i);const{code:a,reason:o}=s;n(o),F(this,ze).debug("Socket closed. Close event:",s),F(this,ze).debug("Connection closed code:",a),F(this,ze).debug("Connection closed reason:",o),F(this,fr)||Oe(this,sd,Vu).call(this,a,o)}catch(a){Oe(this,Ma,id).call(this,a)}},F(this,Be).onerror=s=>{Oe(this,Ma,id).call(this,s)},F(this,Be).onmessage=s=>Oe(this,xu,Mv).call(this,s)}catch(i){Oe(this,Ma,id).call(this,i,n)}})})}send(e,r,n,i){const s={event:e,id:r,payload:n,metadata:i};if(F(this,Ne).queueOnDisconnect&&(!F(this,Be)||F(this,Be).readyState!==1))return F(this,ze).debug("Queuing message since socket is not connected!",s),F(this,On).push(s),!1;const a=Jv.encode(s);return Oe(this,Oa,od).call(this,a)}emit(e,r,n,i){return this.send(e,r,n,i)}sendRaw(e){return Oe(this,Oa,od).call(this,e)}receive(e,r){return F(this,lt).on(e.toString(),r)}on(e,r){if(typeof e=="string"&&(e==="connected"||e==="disconnected"||e==="errored"||e==="reconnected"||e==="reconnecting"||e==="reconnectAttempt"||e==="reconnectFailure"||e==="failed")){F(this,lt).on(e,r);return}this.receive(e,r)}removeAllListeners(){F(this,lt).removeAllListeners()}removeReceiver(e,r){this.removeListener(e,r)}removeListener(e,r){F(this,lt).removeListener(e.toString(),r)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){F(this,lt).listeners(e.toString()).map(r=>this.removeListener(e,r))}disconnect(){Se(this,Zr,!1),Oe(this,vs,Na).call(this),this.removeAllListeners(),Se(this,Nn,{code:1e3,reason:"Sockrates disconnect method called"}),F(this,Be).close(1e3,"Sockrates disconnect method called.")}}Be=new WeakMap,wi=new WeakMap,Ne=new WeakMap,ze=new WeakMap,On=new WeakMap,lt=new WeakMap,Zr=new WeakMap,Nn=new WeakMap,fr=new WeakMap,gs=new WeakMap,en=new WeakMap,Lu=new WeakSet,Av=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)://.")},Ma=new WeakSet,id=function(t,e){F(this,ze).error("Error:",{error:t}),F(this,lt).emit("errored",{error:t}),e==null||e(t)},xu=new WeakSet,Mv=function(t){if(Oe(this,cd,Bu).call(this),t.data===wO){F(this,ze).debug("Received ping from server"),Oe(this,Oa,od).call(this,IO);return}const e=Jv.decode(t.data),{id:r,payload:n}=e;F(this,ze).debug("Received message",{event:e.event,messageID:r}),F(this,lt).emit(e.event.toString(),{id:r,payload:n})},Fu=new WeakSet,Dv=function(){return F(this,Be).readyState===1},sd=new WeakSet,Vu=function(t,e){Se(this,Nn,{reason:e,code:t}),F(this,lt).emit("disconnected",{code:t,reason:e})},Uu=new WeakSet,Ov=function(){const{reason:t,code:e}=F(this,Nn);e&&e!==1e3&&F(this,Zr)&&F(this,Ne).autoReconnect&&!F(this,fr)&&(F(this,ze).debug(`Triggering reconnection due to ${t}.`),F(this,lt).emit("reconnecting"),Oe(this,Da,ad).call(this))},Da=new WeakSet,ad=function(t=!0){return u(this,null,function*(){if(t&&F(this,fr)){F(this,ze).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(F(this,fr)||F(this,en).reset(),F(this,Ne).maxReconnectionAttempts!==null&&F(this,en).getAttempts()>=F(this,Ne).maxReconnectionAttempts){F(this,lt).emit("failed"),Se(this,fr,!1);return}Se(this,fr,!0),Oe(this,La,dd).call(this),Oe(this,vs,Na).call(this);try{if(yield F(this,en).wait(),F(this,Zr)===!1)return;if(F(this,ze).debug(`Reconnection attempt ${F(this,en).getAttempts()}`),F(this,lt).emit("reconnectAttempt",{attempt:F(this,en).getAttempts()}),yield this.connect(),!Oe(this,Fu,Dv).call(this))throw Error("Reconnect Failed");Se(this,fr,!1),Se(this,Nn,{code:void 0,reason:void 0}),F(this,lt).emit("reconnected")}catch(e){F(this,ze).debug("Failed to reconnect."),F(this,lt).emit("reconnectFailure",{attempt:F(this,en).getAttempts()}),Oe(this,Da,ad).call(this,!1)}})},Oa=new WeakSet,od=function(t){try{return F(this,Be).send(t),!0}catch(e){return F(this,ze).error(e.message),!1}},cd=new WeakSet,Bu=function(){this.config.disconnectOnPingTimeout&&(F(this,ze).debug("Resetting ping timeout"),Oe(this,vs,Na).call(this),Se(this,gs,setTimeout(()=>{var t;F(this,ze).debug("Disconnecting the socket due to ping timeout"),Se(this,Zr,!0);const e=3002,r="Ping timeout";(t=F(this,Be))==null||t.close(e,r),Oe(this,sd,Vu).call(this,e,r)},F(this,Ne).pingTimeout)))},vs=new WeakSet,Na=function(){F(this,gs)&&(clearTimeout(F(this,gs)),Se(this,gs,void 0))},La=new WeakSet,dd=function(){F(this,Be)&&(F(this,Be).onopen=void 0,F(this,Be).onerror=void 0,F(this,Be).onmessage=void 0,F(this,Be).onclose=void 0)};var PO=Object.defineProperty,RO=Object.getOwnPropertyDescriptor,hd=(t,e,r,n)=>{for(var i=n>1?void 0:n?RO(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&PO(e,r,i),i};const qv=65535,AO=3e3;var Ii,je,He,Ke,gr,xn,pd,Hu,md,Wu,zv;const Kv=(zv=class{constructor(t,{peerId:e,meetingId:r,authToken:n,capabilities:i}){T(this,He),T(this,pd),T(this,md),T(this,Ii,void 0),T(this,je,void 0),f(this,"roomName"),f(this,"authToken"),f(this,"capabilities"),T(this,gr,void 0),T(this,xn,void 0);var s;if(!e||!r||!n)throw new _("peerId, meetingId, or authToken can not be empty","0404");S(this,gr,void 0),S(this,xn,t),this.capabilities=i,this.roomName=r,this.authToken=n,S(this,Ii,Je(this,pd,Hu).call(this,e)),S(this,je,new CO(c(this,Ii),{autoReconnect:!0,disconnectOnPingTimeout:(s=i.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:l})),this.handleSocketConnectionEvents()}get joinAttempted(){return c(this,He,Ke).socketJoinAttempted}set joinAttempted(t){c(this,He,Ke).socketJoinAttempted=t}get peerId(){return c(this,xn).getValue("peerId")}updateURL(t){t!==this.peerId&&(S(this,Ii,Je(this,pd,Hu).call(this,t)),l.debug("SocketService:: Connection URL updated.")),c(this,je).updateURL(c(this,Ii))}static getSocketEdgeDomain(t){return Li({servicePrefix:"socket-edge",baseURI:t})}get url(){return c(this,Ii)}connect(){return u(this,null,function*(){c(this,He,Ke).socketJoinAttempted=!0,yield c(this,je).connect(),c(this,He,Ke).socketJoinAttempted=!0,c(this,He,Ke).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){return u(this,null,function*(){c(this,He,Ke).socketJoinAttempted=!1,c(this,je).disconnect(),c(this,He,Ke).socketJoinAttempted=!0,c(this,He,Ke).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}})}get isConnected(){try{return c(this,je).readyState===1}catch(t){return!1}}sendMessage(t,e,r){const n={};return y.injectContext(n),c(this,je).send(t,r!=null?r:Je(this,md,Wu).call(this),e,new TextEncoder().encode(JSON.stringify(n)))}sendMessagePromise(t,e,r,n){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:i,protobuf:e,messageId:r,resp:n})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:r,messageId:n,resp:i}){const s=i!=null?i:t;return new Promise((a,o)=>{const d=(v,I)=>{c(this,je).removeListener(s,v),c(this,je).removeListener(qv,I),c(this,je).removeListener(oe.errorResponse,I),c(this,je).removeListener(ce.errorResponse,I)},h=n!=null?n:Je(this,md,Wu).call(this),p={};y.injectContext(p);const m=({id:v,payload:I})=>{if(h===v){let A;try{const P=kI.fromBinary(I);A=new Error(P.errorMessage)}catch(P){A=new Error("failed to parse error message",{cause:P});try{const D=pC.fromBinary(I);A=new Error(D.message)}catch(D){A=new Error("failed to parse error message",{cause:D})}}o(A),d(g,m)}},g=({id:v,payload:I})=>{h===v&&(a({id:v,payload:I}),d(g,m))};c(this,je).on(s,g),c(this,je).on(qv,m),c(this,je).on(oe.errorResponse,m),c(this,je).on(ce.errorResponse,m),setTimeout(()=>{d(g,m),o(new Error(`request timeout for callback eventId:${t}`))},e),c(this,je).send(t,h,r,new TextEncoder().encode(JSON.stringify(p)))})}on(t,e){c(this,je).on(t,e)}onStateEvent(t,e){c(this,je).on(t,e)}removeListener(t,e){c(this,je).removeListener(t,e)}removeListeners(t){c(this,je).removeListeners(t)}flush(){return c(this,je).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){l.info("SocketService::Connected to socket-edge"),c(this,gr)&&(clearTimeout(c(this,gr)),S(this,gr,void 0)),c(this,He,Ke).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:t,reason:e})=>{var r;l.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e},country:y.location.country});const{recv:n,send:i}=(r=c(this,He,Ke).mediaState)!=null?r:{};n!=null&&n.state&&(n==null?void 0:n.state)!==er.CONNECTED||i!=null&&i.state&&(i==null?void 0:i.state)!==er.CONNECTED?b.emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:c(this,He,Ke).joinAttempted}):S(this,gr,setTimeout(()=>{b.emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:c(this,He,Ke).joinAttempted}),S(this,gr,void 0)},AO)),c(this,He,Ke).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){l.info("SocketService::Reconnecting to socket-edge",{country:y.location.country}),c(this,He,Ke).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){l.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),c(this,He,Ke).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{l.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),c(this,He,Ke).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){l.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:c(this,He,Ke).joinAttempted}}),c(this,gr)&&(clearTimeout(c(this,gr)),S(this,gr,void 0)),b.emit(w.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:c(this,He,Ke).joinAttempted}),c(this,He,Ke).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){l.info("SocketService::Failed to connect to socket-edge",{country:y.location.country}),b.emit(w.SOCKET_SERVICE_FAILED),c(this,He,Ke).updateSocketConnectionState("failed")}))}},Ii=new WeakMap,je=new WeakMap,He=new WeakSet,Ke=function(){return c(this,xn).getValue("connectionHandler")},gr=new WeakMap,xn=new WeakMap,pd=new WeakSet,Hu=function(t){let e=Kv.getSocketEdgeDomain(c(this,xn).getValue("baseURI"));typeof Ho(c(this,xn),"socket_server_base")=="string"&&(e=Ho(c(this,xn),"socket_server_base"));const r=`wss://${e}`,n=new URL(`${r}/ws`),i=this.peerId,s=X(U({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},i!==t&&{oldPeerID:i}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(a=>Ko[a]).join(" "),joinWithDetails:!0});return Object.entries(s).forEach(([a,o])=>{n.searchParams.append(a,o.toString())}),n.href},md=new WeakSet,Wu=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},zv);let xa=Kv;hd([y.trace("SocketService.connect")],xa.prototype,"connect",1),hd([y.trace("SocketService.disconnect")],xa.prototype,"disconnect",1),hd([y.trace("SocketService.sendMessagePromise")],xa.prototype,"sendMessagePromise",1),hd([y.trace("SocketService.sendMessagePromiseWithTimeout")],xa.prototype,"sendMessagePromiseWithTimeout",1);const Ci=class{static handleConnectedRoomsDumpRaw({payload:t}){var e;const r=BC.fromBinary(t),n=r.meetings.map(i=>{var s;return{id:i.id,title:i.title,participants:(s=i.participants)!=null?s:[]}});return{parentMeeting:{id:r.parentMeeting.id,title:r.parentMeeting.title,participants:(e=r.parentMeeting.participants)!=null?e:[]},meetings:n}}static handleTransferPeerRaw({payload:t}){const e=hP.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}static handleMovedPeerRaw({payload:t}){const e=Yf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}static handleConnectedRoomsUpdatedRaw({payload:t}){return Kf.fromBinary(t).payloads.map(e=>({id:e.id,title:e.title}))}static handleConnectedRoomsDeletedRaw({payload:t}){return rP.fromBinary(t).payloads}static getConnectedRoomsDump(){return u(this,null,function*(){const t=yield Ci.socketService.sendMessagePromise(j.getConnectedRoomsDump);return Ci.handleConnectedRoomsDumpRaw(t)})}static createConnectedRooms(t){return u(this,null,function*(){const{payload:e}=yield Ci.socketService.sendMessagePromise(j.createConnectedRooms,$C.toBinary({payloads:t}));return Kf.fromBinary(e).payloads.map(r=>({id:r.id,title:r.title}))})}static updateConnectedRooms(t){return u(this,null,function*(){})}static disableConnectedRooms(t){return u(this,null,function*(){const e=t.map(n=>({id:n})),r=yield Ci.socketService.sendMessagePromise(j.deleteConnectedRooms,eP.toBinary({payloads:e}));return Ci.handleConnectedRoomsDeletedRaw(r)})}static movePeersBetweenRooms(t){return u(this,null,function*(){try{const e=yield Ci.socketService.sendMessagePromise(j.movePeers,cP.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 Fe=Ci;f(Fe,"socketService"),f(Fe,"currentMeetingId");var MO=Object.defineProperty,DO=Object.getOwnPropertyDescriptor,fd=(t,e,r,n)=>{for(var i=n>1?void 0:n?DO(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&MO(e,r,i),i};const Pi=class{constructor(t,e){f(this,"apiBase"),f(this,"selfController"),f(this,"pollController"),f(this,"chatController"),f(this,"metaController"),f(this,"storesManager"),f(this,"stageController"),f(this,"pluginController"),f(this,"internalsController"),f(this,"recordingController"),f(this,"livestreamController"),f(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 u(this,null,function*(){var e;const{peerId:r,apiBase:n,authToken:i,meetingId:s,organizationId:a,cachedUserDetails:o}=t.getAllValues();if(b.reset(),ed.cleanup(),wv(t),Te.isSupported()===!1)throw new _("Browser not supported","0010",!0);const d=bM(t,{authToken:i,baseURL:n,cachedUserDetails:o});d.setRoomName(s),d.setRoomUUID(s),d.setOrganizationId(a),d.setHeader("dyte-tracing-id",r),t.setValue("apiClient",d);const h=new aD;t.setValue("connectionHandler",h);const p=Pi.createSocketService(t),m=p.connect(),g=d.getPlugins(),[{sfu:v,userResponse:I,meetingTitle:A,roomNodeUrl:P}]=yield Promise.all([Pi.getRoomMetadata(),Pi.setupFlagsmith(t)]);y.location.country=(e=d.ipInfo)==null?void 0:e.country,t.setValue("roomNodeOptions",{sfu:v,meetingTitle:A,roomNodeUrl:P});const{theme:D,controllers:N}=yield Pi.setupControllers(p,t,I,g);KM(D)&&Pi.createRoomNodeClient(t,p),bw();try{yield m,N.selfController.partialMediaRoom()}catch(J){throw l.error("[Socket Service] Failed to connect to socket server:",{error:J}),new _("Failed to connect to websocket","0012")}return new Pi(n,N)})}static getRoomMetadata(){return u(this,null,function*(){const t=qe(),[{roomNodeUrl:e,meetingTitle:r,sfu:n=cs.HIVE},i]=yield Promise.all([t.getRoomNodeData(),t.getUserDetails()]);return{sfu:n,roomNodeUrl:e,meetingTitle:r,userResponse:i}})}static setupFlagsmith(t){return u(this,null,function*(){const{peerId:e,baseURI:r,overrides:n,meetingId:i,organizationId:s}=t.getAllValues(),a=kw(i),o=X(U({entity:Tl.PEER,clientId:s,isAnonUser:!s,sdkVersion:t.getValue("sdkVersion"),meetingHash:a,roomName:i},Te.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const d=n!=null&&n.whitelabelled_flags_endpoint?Li({servicePrefix:"flags",baseURI:r}):"edge.api.flagsmith.com";yield Q.identify(`${Tl.PEER}_${e}`,JSON.parse(JSON.stringify(o)),!1,5e3,d),l.info("flagsmith::allFlags",{flags:JSON.stringify(Q.getAllFlags())},!0)}catch(d){l.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,r,n){return u(this,null,function*(){var i,s,a;const o=e.getValue("modules"),{preset:d,participant:h}=r,p=e.getValue("defaults"),{sfu:m,meetingTitle:g}=e.getValue("roomNodeOptions"),v=WD.init(d,!o.theme),{viewType:I,mediaConstraints:{audio:A}}=v;e.setValue("viewType",I),e.setValue("defaults",U({mediaConfiguration:{audio:{enableHighBitrate:(i=A.enableHighBitrate)!=null?i:!1,enableStereo:(s=A.enableStereo)!=null?s:!1}}},p));const P=F1.init(e,I,d.permissions);e.setValue("maxPreferredStreams",Te.isMobile()?v.maxVideoStreams.mobile:v.maxVideoStreams.desktop);let D,N,J,C,G,W,de,ae;const Le=new aO(t);Fe.socketService=t;const Dt=new nd(t),O=new Xt(t),k=new dO(t),R=ed.create(t,e),H=new lO(t),De=new sO(t),rt=new Xn(t),B=yield An.init(e,R,h,P,v),M=yield Pg.init(e,B.self,R,Le,g);if(o.participant&&(m===cs.CF&&(ae=new vv(e,B.self,R)),ae=new yv(e,B.self,R)),(a=o.e2ee)!=null&&a.enabled&&o.e2ee.manager.init(l,b),o.chat&&(N=yield xr.init(e,O,rt,B.self,ae.participants)),o.internals&&(G=yield iu.init()),o.livestream&&v.viewType===gt.Livestream&&Q.hasFeature(ie.LIVESTREAM)&&(de=new zg(B.self,De)),v.viewType!==gt.Chat){if(o.poll&&(D=yield Tg.init(e,B.self,Dt)),o.recording&&(W=new xg(e,B.self,R)),o.stage&&(J=new Rg(e,k,R,B.self,ae.participants)),o.plugin){if(!ae)throw new _("The plugin module cannot be initialized without the `participant` module","0102");const tn=yield n;C=yield Xs.init(e,tn,H,O,N==null?void 0:N.chat,B.self,ae.participants)}if(o.pip){const tn=yield Cw._init(e,B.self);e.setValue("pip",tn)}}const nt={storesManager:new QD(e,H),pollController:D,selfController:B,metaController:M,chatController:N,stageController:J,pluginController:C,recordingController:W,internalsController:G,livestreamController:de,participantController:ae};return{theme:v,permissions:P,controllers:nt}})}static createRoomNodeClient(t,e){return u(this,null,function*(){const{peerId:r,meetingId:n,authToken:i,roomNodeOptions:s}=t.getAllValues(),{sfu:a,roomNodeUrl:o,meetingTitle:d}=s;return bv(t,{socket:e,peerId:r,meetingId:n,authToken:i,roomNodeUrl:o,meetingTitle:d},a)})}static createSocketService(t){const{peerId:e,meetingId:r,authToken:n}=t.getAllValues(),i=["PING"];return new xa(t,{peerId:e,meetingId:r,authToken:n,capabilities:i})}};let Fa=Pi;fd([y.trace("Controller.init")],Fa,"init",1),fd([y.trace("setupFlagsmith")],Fa,"setupFlagsmith",1),fd([y.trace("Controller.createSocketServiceAndRoomNodeClient")],Fa,"createRoomNodeClient",1),fd([y.trace("Controller.createSocketService")],Fa,"createSocketService",1);var OO=Object.defineProperty,NO=Object.getOwnPropertyDescriptor,LO=(t,e,r,n)=>{for(var i=n>1?void 0:n?NO(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&OO(e,r,i),i},gd,$u;class Yv extends jt{constructor(e,r){super(),T(this,gd,void 0),f(this,"meetings",[]),f(this,"parentMeeting",null),T(this,$u,void 0),S(this,$u,e),S(this,gd,r.self)}get supportsConnectedMeetings(){return c(this,gd).id!==""}get isActive(){return this.meetings.length!==0}get currentMeetingId(){return Fe.currentMeetingId}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
21
+ Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`)}getConnectedMeetings(){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),yield Fe.getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield Fe.createConnectedRooms(e)).map(r=>({id:r.id,title:r.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield Fe.updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title})))})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction();const r=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.participants.map(i=>i.id)):Promise.resolve());return yield Promise.all(r),yield Fe.disableConnectedRooms(e)})}moveParticipants(e,r,n){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=yield Fe.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:n.map(s=>({id:s}))});return i.success&&this.moveSuccessHandler(e,r,n),i})}moveParticipantsWithCustomPreset(e,r,n){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=yield Fe.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:n});return i.success&&this.moveSuccessHandler(e,r,n.map(s=>s.id)),i})}moveSuccessHandler(e,r,n){const i=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(s=>s.participants)].forEach(s=>i.set(s.id,s)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(n.map(s=>i.get(s)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(s=>!n.includes(s.id))),this.meetings=this.meetings.map(s=>{if(r===s.id){const a=s.participants.concat(n.map(o=>i.get(o)));return X(U({},s),{participants:a})}if(e===s.id){const a=s.participants.filter(o=>!n.includes(o.id));return X(U({},s),{participants:a})}return s})}}gd=new WeakMap,$u=new WeakMap,LO([xt({maxInvocations:60,period:60})],Yv.prototype,"getConnectedMeetings",1);var xO=Object.defineProperty,FO=Object.getOwnPropertyDescriptor,Ju=(t,e,r,n)=>{for(var i=n>1?void 0:n?FO(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&xO(e,r,i),i},Va,vr,Gu,qu;const Fn=(Gu=class{constructor(t,e,r){f(this,"connectedMeetings"),T(this,Va,void 0),T(this,vr,void 0),T(this,qu,void 0),S(this,qu,t),S(this,Va,r),this.connectedMeetings=new Yv(t,e),this.setCurrentMeeting(e)}static init(t,e,r){return Fn.instance||(Fn.instance=new Fn(t,e,r)),Fn.instance.connectedMeetings.supportsConnectedMeetings&&(Fn.instance.setupEvents(),e.self.once("roomJoined",()=>Fn.instance.getConnectedMeetings())),Fn.instance}setCurrentMeeting(t){S(this,vr,t),Fe.currentMeetingId=t.meta.meetingId}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){Fe.socketService&&(Fe.socketService.on(j.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),Fe.socketService.on(j.transferPeer,this.handleTransferPeer.bind(this)),Fe.socketService.on(j.movedPeer,this.handleMovedPeer.bind(this)),Fe.socketService.on(j.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),Fe.socketService.on(j.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this)))}handleTransferPeer(t){const e=Fe.handleTransferPeerRaw(t);return this.switchMeeting(e)}switchMeeting(t){return u(this,arguments,function*({authToken:e,meetingId:r}){var n,i,s,a;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
22
+ Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`);l.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",r);const o={video:c(this,vr).self.videoEnabled,audio:c(this,vr).self.audioEnabled};try{c(this,vr).self.cleanupEvents(),yield c(this,vr).leave("connected-meeting")}catch(h){l.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(i=(n=c(this,vr))==null?void 0:n.meta)==null?void 0:i.meetingId}`,{error:h})}Fe.socketService=void 0,l.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${r}`);const d=yield ey.init(X(U({},c(this,Va)),{cachedUserDetails:null,defaults:X(U(U({},c(this,Va).defaults),o),{mediaHandler:c(this,vr).self}),authToken:e}));l.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(s=d==null?void 0:d.meta)==null?void 0:s.meetingId}`);try{const{hidden:h}=c(this,vr).self;d.self.setName(c(this,vr).self.name),yield d.join(),h&&d.self.hide()}catch(h){l.error("ConnectedMeetingsController.joinRoom",{error:h})}return l.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=Fe.handleConnectedRoomsDumpRaw(t);this.connectedMeetings.meetings=e.meetings.map(r=>({id:r.id,title:r.title,participants:r.participants||[]})),this.connectedMeetings.parentMeeting={id:e.parentMeeting.id,title:e.parentMeeting.title,participants:e.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(t){return Fe.handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=Fe.handleConnectedRoomsUpdatedRaw(t),r=new Map;this.connectedMeetings.meetings.forEach(n=>{r.set(n.id,n)}),e.forEach(n=>{r.has(n.id)?r.get(n.id).title=n.title:r.set(n.id,X(U({},n),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(r.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=Fe.handleConnectedRoomsDeletedRaw(t).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},Va=new WeakMap,vr=new WeakMap,qu=new WeakMap,f(Gu,"instance"),Gu);let vd=Fn;Ju([y.trace("ConnectedMeetingsController.getConnectedMeetings")],vd.prototype,"getConnectedMeetings",1),Ju([y.trace("ConnectedMeetingsController.setupEvents")],vd.prototype,"setupEvents",1),Ju([y.trace("ConnectedMeetingsController.switchMeeting")],vd.prototype,"switchMeeting",1);class VO{constructor(){f(this,"battery"),f(this,"init",()=>u(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){l.error("Error getting battery",e)}})),f(this,"updateChargeInfo",()=>{var e;l.log(`Battery charging? ${(e=this.battery)!=null&&e.charging?"Yes":"No"}`)}),f(this,"updateLevelInfo",()=>{if(!this.battery){l.log("Battery level: Not known");return}l.log(`Battery level: ${this.battery.level*100}%`)}),f(this,"cleanup",()=>{var e,r;"getBattery"in navigator&&((e=this.battery)==null||e.removeEventListener("chargingchange",this.updateChargeInfo),(r=this.battery)==null||r.removeEventListener("levelchange",this.updateLevelInfo))})}}const Qv=new VO;function UO(t,e){try{const{meetingId:r,orgId:n,participantId:i}=JSON.parse(atob(t.split(".")[1]));if(!r)throw Error(`Received V1 auth token ${t}`);let s="dyte.io";e&&(s=e);const a=`https://api.${s}`;return{meetingId:r,orgId:n,participantId:i,baseURI:s,apiBase:a}}catch(r){throw l.error("constants::decodeAuthToken",{error:r,debuggingHint:`Unable to decode auth token: ${t}`},!0),new _("Invalid auth token","0004")}}var BO=Object.defineProperty,jO=Object.getOwnPropertyDescriptor,yd=(t,e,r,n)=>{for(var i=n>1?void 0:n?jO(e,r):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(n?a(e,r,i):a(i))||i);return n&&i&&BO(e,r,i),i},mt,Sd,Ed,zu,Xv,Zv;let Vn=(Zv=class{constructor(t,e){T(this,zu),T(this,mt,void 0),T(this,Sd,void 0),T(this,Ed,void 0),S(this,Ed,t),S(this,mt,e)}static init(t){return u(this,null,function*(){var e,r,n,i,s;Sw(),Te.init();const a=Un();Qv.init();const{authToken:o,baseURI:d}=t,h=UO(o,d),{meetingId:p}=h,m=po(h,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const g=Vn.setupContext(a,t,p,m);y.meetingMetadata.roomName=p,y.meetingMetadata.userId=m.participantId,y.meetingMetadata.organizationId=m.orgId,y.init(g,(r=(e=t.modules)==null?void 0:e.tracing)!=null?r:!0),l.info("DyteClient::init::options",{dyteClientInitOptions:X(U({},t),{authToken:`${(n=t.authToken)==null?void 0:n.slice(0,10)}...
23
+ ${(i=t.authToken)==null?void 0:i.slice(-10)}`})});const v=yield Fa.init(g),I=new Vn(g,v);return Je(s=I,zu,Xv).call(s,t),I})}static setupContext(t,e,r,n){var i;const s=qn.createContext(t,e),a=U(U({},pw),e==null?void 0:e.modules);return s.setValue("peerId",t),s.setValue("modules",a),s.setValue("sdkName","web-core"),s.setValue("meetingId",r),s.setValue("apiBase",n.apiBase),s.setValue("baseURI",n.baseURI),s.setValue("userId",n.participantId),s.setValue("organizationId",n.orgId),s.setValue("authToken",e.authToken),s.setValue("overrides",(i=e.overrides)!=null?i:{}),s.setValue("env",mw({baseURI:n.baseURI})),s.setValue("defaults",e.defaults||{audio:!0,video:!0}),s.setValue("onError",e.onError||(()=>{})),s.setValue("cachedUserDetails",dr(e.cachedUserDetails)),s.setValue("sdkVersion","2.4.4"),s}join(){return u(this,null,function*(){const{selfController:t}=c(this,mt);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){Qv.cleanup();const{selfController:e}=c(this,mt);return e.leaveRoom(t)})}get participants(){var t;return(t=c(this,mt).participantController)==null?void 0:t.participants}get self(){var t;return(t=c(this,mt).selfController)==null?void 0:t.self}get meta(){var t;return(t=c(this,mt).metaController)==null?void 0:t.meta}get ai(){var t;return(t=c(this,mt).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=c(this,mt).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=c(this,mt).chatController)==null?void 0:t.chat}get polls(){var t;return(t=c(this,mt).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=c(this,Sd))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=c(this,mt).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=c(this,mt).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=c(this,mt).stageController)==null?void 0:t.stage}get stores(){return c(this,mt).storesManager}get __internals__(){var t;return(t=c(this,mt).internalsController)==null?void 0:t.internals}joinRoom(){return u(this,null,function*(){return this.join()})}leaveRoom(t){return u(this,null,function*(){return this.leave(t)})}},mt=new WeakMap,Sd=new WeakMap,Ed=new WeakMap,zu=new WeakSet,Xv=function(t){S(this,Sd,vd.init(c(this,Ed),this,t))},Zv);yd([vt("0002"),In.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Vn.prototype,"join",1),yd([vt("0003")],Vn.prototype,"leave",1),yd([vt("0001"),In.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Vn,"init",1),Vn=yd([vt("0000")],Vn);const ey=Vn;return ey}();