@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/index.cjs.js CHANGED
@@ -1,23 +1,23 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});var go,dv=new Uint8Array(16);function lv(){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(dv)}var uv=/^(?:[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 vl(t){return typeof t=="string"&&uv.test(t)}var it=[];for(var Uc=0;Uc<256;++Uc)it.push((Uc+256).toString(16).substr(1));function hv(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=(it[t[e+0]]+it[t[e+1]]+it[t[e+2]]+it[t[e+3]]+"-"+it[t[e+4]]+it[t[e+5]]+"-"+it[t[e+6]]+it[t[e+7]]+"-"+it[t[e+8]]+it[t[e+9]]+"-"+it[t[e+10]]+it[t[e+11]]+it[t[e+12]]+it[t[e+13]]+it[t[e+14]]+it[t[e+15]]).toLowerCase();if(!vl(r))throw TypeError("Stringified UUID is invalid");return r}function si(t,e,r){t=t||{};var n=t.random||(t.rng||lv)();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 hv(n)}const pv={"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"},Hp={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"},ft={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},Kr={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};class O{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=O.getVersionPrecision(e),s=O.getVersionPrecision(r);let o=Math.max(i,s),a=0;const d=O.map([e,r],h=>{const p=o-O.getVersionPrecision(h),f=h+new Array(p+1).join(".0");return O.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 pv[e]}static getBrowserTypeByAlias(e){return Hp[e]||""}}const Te=/version\/(\d+(\.?_?\d+)+)/i,mv=[{test:[/googlebot/i],describe(t){const e={name:"Googlebot"},r=O.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,t)||O.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/opera/i],describe(t){const e={name:"Opera"},r=O.getFirstMatch(Te,t)||O.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/opr\/|opios/i],describe(t){const e={name:"Opera"},r=O.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,t)||O.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/SamsungBrowser/i],describe(t){const e={name:"Samsung Internet for Android"},r=O.getFirstMatch(Te,t)||O.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=O.getFirstMatch(Te,t)||O.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/MZBrowser/i],describe(t){const e={name:"MZ Browser"},r=O.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,t)||O.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/focus/i],describe(t){const e={name:"Focus"},r=O.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,t)||O.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/swing/i],describe(t){const e={name:"Swing"},r=O.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,t)||O.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/coast/i],describe(t){const e={name:"Opera Coast"},r=O.getFirstMatch(Te,t)||O.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=O.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,t)||O.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/yabrowser/i],describe(t){const e={name:"Yandex Browser"},r=O.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,t)||O.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/ucbrowser/i],describe(t){const e={name:"UC Browser"},r=O.getFirstMatch(Te,t)||O.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/Maxthon|mxios/i],describe(t){const e={name:"Maxthon"},r=O.getFirstMatch(Te,t)||O.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/epiphany/i],describe(t){const e={name:"Epiphany"},r=O.getFirstMatch(Te,t)||O.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/puffin/i],describe(t){const e={name:"Puffin"},r=O.getFirstMatch(Te,t)||O.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/sleipnir/i],describe(t){const e={name:"Sleipnir"},r=O.getFirstMatch(Te,t)||O.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=O.getFirstMatch(Te,t)||O.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/micromessenger/i],describe(t){const e={name:"WeChat"},r=O.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,t)||O.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=O.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,t)||O.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/msie|trident/i],describe(t){const e={name:"Internet Explorer"},r=O.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/\sedg\//i],describe(t){const e={name:"Microsoft Edge"},r=O.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=O.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/vivaldi/i],describe(t){const e={name:"Vivaldi"},r=O.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/seamonkey/i],describe(t){const e={name:"SeaMonkey"},r=O.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/sailfish/i],describe(t){const e={name:"Sailfish"},r=O.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=O.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/phantom/i],describe(t){const e={name:"PhantomJS"},r=O.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/slimerjs/i],describe(t){const e={name:"SlimerJS"},r=O.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=O.getFirstMatch(Te,t)||O.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=O.getFirstMatch(Te,t)||O.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=O.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/tizen/i],describe(t){const e={name:"Tizen"},r=O.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,t)||O.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/qupzilla/i],describe(t){const e={name:"QupZilla"},r=O.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,t)||O.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/firefox|iceweasel|fxios/i],describe(t){const e={name:"Firefox"},r=O.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=O.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/MiuiBrowser/i],describe(t){const e={name:"Miui"},r=O.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/chromium/i],describe(t){const e={name:"Chromium"},r=O.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,t)||O.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/chrome|crios|crmo/i],describe(t){const e={name:"Chrome"},r=O.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=O.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=O.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/playstation 4/i],describe(t){const e={name:"PlayStation 4"},r=O.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/safari|applewebkit/i],describe(t){const e={name:"Safari"},r=O.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:O.getFirstMatch(i,t),version:O.getSecondMatch(i,t)}}}];var fv=[{test:[/Roku\/DVP/],describe(t){const e=O.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,t);return{name:ft.Roku,version:e}}},{test:[/windows phone/i],describe(t){const e=O.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,t);return{name:ft.WindowsPhone,version:e}}},{test:[/windows /i],describe(t){const e=O.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,t),r=O.getWindowsVersionName(e);return{name:ft.Windows,version:e,versionName:r}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(t){const e={name:ft.iOS},r=O.getSecondMatch(/(Version\/)(\d[\d.]+)/,t);return r&&(e.version=r),e}},{test:[/macintosh/i],describe(t){const e=O.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,t).replace(/[_\s]/g,"."),r=O.getMacOSVersionName(e),n={name:ft.MacOS,version:e};return r&&(n.versionName=r),n}},{test:[/(ipod|iphone|ipad)/i],describe(t){const e=O.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,t).replace(/[_\s]/g,".");return{name:ft.iOS,version:e}}},{test(t){const e=!t.test(/like android/i),r=t.test(/android/i);return e&&r},describe(t){const e=O.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,t),r=O.getAndroidVersionName(e),n={name:ft.Android,version:e};return r&&(n.versionName=r),n}},{test:[/(web|hpw)[o0]s/i],describe(t){const e=O.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,t),r={name:ft.WebOS};return e&&e.length&&(r.version=e),r}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(t){const e=O.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,t)||O.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,t)||O.getFirstMatch(/\bbb(\d+)/i,t);return{name:ft.BlackBerry,version:e}}},{test:[/bada/i],describe(t){const e=O.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,t);return{name:ft.Bada,version:e}}},{test:[/tizen/i],describe(t){const e=O.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,t);return{name:ft.Tizen,version:e}}},{test:[/linux/i],describe(){return{name:ft.Linux}}},{test:[/CrOS/],describe(){return{name:ft.ChromeOS}}},{test:[/PlayStation 4/],describe(t){const e=O.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,t);return{name:ft.PlayStation4,version:e}}}],gv=[{test:[/googlebot/i],describe(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe(t){const e=O.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=O.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}}}],vv=[{test(t){return t.getBrowserName(!0)==="microsoft edge"},describe(t){if(/\sedg\//i.test(t))return{name:Kr.Blink};const r=O.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,t);return{name:Kr.EdgeHTML,version:r}}},{test:[/trident/i],describe(t){const e={name:Kr.Trident},r=O.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test(t){return t.test(/presto/i)},describe(t){const e={name:Kr.Presto},r=O.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:Kr.Gecko},r=O.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:Kr.Blink}}},{test:[/(apple)?webkit/i],describe(t){const e={name:Kr.WebKit},r=O.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}}];class cu{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=O.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.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=O.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.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=O.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.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=O.find(vv,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 O.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=O.find(a,p=>this.isOS(p));if(d){const p=this.satisfies(r[d]);if(p!==void 0)return p}const h=O.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=O.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=O.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(O.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
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});var eo,ry=new Uint8Array(16);function ny(){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(ry)}var iy=/^(?:[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 iu(t){return typeof t=="string"&&iy.test(t)}var pt=[];for(var kd=0;kd<256;++kd)pt.push((kd+256).toString(16).substr(1));function sy(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=(pt[t[e+0]]+pt[t[e+1]]+pt[t[e+2]]+pt[t[e+3]]+"-"+pt[t[e+4]]+pt[t[e+5]]+"-"+pt[t[e+6]]+pt[t[e+7]]+"-"+pt[t[e+8]]+pt[t[e+9]]+"-"+pt[t[e+10]]+pt[t[e+11]]+pt[t[e+12]]+pt[t[e+13]]+pt[t[e+14]]+pt[t[e+15]]).toLowerCase();if(!iu(r))throw TypeError("Stringified UUID is invalid");return r}function Ei(t,e,r){t=t||{};var n=t.random||(t.rng||ny)();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 sy(n)}const ay={"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"},Am={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"},$e={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},bt={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"},fn={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 ay[e]}static getBrowserTypeByAlias(e){return Am[e]||""}}const be=/version\/(\d+(\.?_?\d+)+)/i,oy=[{test:[/googlebot/i],describe(t){const e={name:"Googlebot"},r=x.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,t)||x.getFirstMatch(be,t);return r&&(e.version=r),e}},{test:[/opera/i],describe(t){const e={name:"Opera"},r=x.getFirstMatch(be,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(be,t);return r&&(e.version=r),e}},{test:[/SamsungBrowser/i],describe(t){const e={name:"Samsung Internet for Android"},r=x.getFirstMatch(be,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(be,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(be,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(be,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(be,t);return r&&(e.version=r),e}},{test:[/coast/i],describe(t){const e={name:"Opera Coast"},r=x.getFirstMatch(be,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(be,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(be,t);return r&&(e.version=r),e}},{test:[/ucbrowser/i],describe(t){const e={name:"UC Browser"},r=x.getFirstMatch(be,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(be,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(be,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(be,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(be,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(be,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(be,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(be,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(be,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(be,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(be,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(be,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(be,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(be,t);return r&&(e.version=r),e}},{test:[/playstation 4/i],describe(t){const e={name:"PlayStation 4"},r=x.getFirstMatch(be,t);return r&&(e.version=r),e}},{test:[/safari|applewebkit/i],describe(t){const e={name:"Safari"},r=x.getFirstMatch(be,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 cy=[{test:[/Roku\/DVP/],describe(t){const e=x.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,t);return{name:bt.Roku,version:e}}},{test:[/windows phone/i],describe(t){const e=x.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,t);return{name:bt.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:bt.Windows,version:e,versionName:r}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(t){const e={name:bt.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:bt.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:bt.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:bt.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:bt.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:bt.BlackBerry,version:e}}},{test:[/bada/i],describe(t){const e=x.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,t);return{name:bt.Bada,version:e}}},{test:[/tizen/i],describe(t){const e=x.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,t);return{name:bt.Tizen,version:e}}},{test:[/linux/i],describe(){return{name:bt.Linux}}},{test:[/CrOS/],describe(){return{name:bt.ChromeOS}}},{test:[/PlayStation 4/],describe(t){const e=x.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,t);return{name:bt.PlayStation4,version:e}}}],dy=[{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:$e.mobile,vendor:"Huawei"};return e&&(r.model=e),r}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe(){return{type:$e.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe(){return{type:$e.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(){return{type:$e.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe(){return{type:$e.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe(){return{type:$e.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe(){return{type:$e.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:$e.mobile,vendor:"Apple",model:e}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe(){return{type:$e.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe(){return{type:$e.mobile}}},{test(t){return t.getBrowserName(!0)==="blackberry"},describe(){return{type:$e.mobile,vendor:"BlackBerry"}}},{test(t){return t.getBrowserName(!0)==="bada"},describe(){return{type:$e.mobile}}},{test(t){return t.getBrowserName()==="windows phone"},describe(){return{type:$e.mobile,vendor:"Microsoft"}}},{test(t){const e=Number(String(t.getOSVersion()).split(".")[0]);return t.getOSName(!0)==="android"&&e>=3},describe(){return{type:$e.tablet}}},{test(t){return t.getOSName(!0)==="android"},describe(){return{type:$e.mobile}}},{test(t){return t.getOSName(!0)==="macos"},describe(){return{type:$e.desktop,vendor:"Apple"}}},{test(t){return t.getOSName(!0)==="windows"},describe(){return{type:$e.desktop}}},{test(t){return t.getOSName(!0)==="linux"},describe(){return{type:$e.desktop}}},{test(t){return t.getOSName(!0)==="playstation 4"},describe(){return{type:$e.tv}}},{test(t){return t.getOSName(!0)==="roku"},describe(){return{type:$e.tv}}}],ly=[{test(t){return t.getBrowserName(!0)==="microsoft edge"},describe(t){if(/\sedg\//i.test(t))return{name:fn.Blink};const r=x.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,t);return{name:fn.EdgeHTML,version:r}}},{test:[/trident/i],describe(t){const e={name:fn.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:fn.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:fn.Gecko},r=x.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:fn.Blink}}},{test:[/(apple)?webkit/i],describe(t){const e={name:fn.WebKit},r=x.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}}];class Yu{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(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.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(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.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(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.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(ly,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 Wp{static getParser(e,r=!1){if(typeof e!="string")throw new Error("UserAgent should be a string");return new cu(e,r)}static parse(e){return new cu(e).getResult()}static get BROWSER_MAP(){return Hp}static get ENGINE_MAP(){return Kr}static get OS_MAP(){return ft}static get PLATFORMS_MAP(){return Ve}}function yl(t){let e=typeof t;if(e=="object"){if(Array.isArray(t))return"array";if(t===null)return"null"}return e}function yv(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}let Rr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),ac=[];for(let t=0;t<Rr.length;t++)ac[Rr[t].charCodeAt(0)]=t;ac["-".charCodeAt(0)]=Rr.indexOf("+");ac["_".charCodeAt(0)]=Rr.indexOf("/");function Ev(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=ac[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 Sv(t){let e="",r=0,n,i=0;for(let s=0;s<t.length;s++)switch(n=t[s],r){case 0:e+=Rr[n>>2],i=(n&3)<<4,r=1;break;case 1:e+=Rr[i|n>>4],i=(n&15)<<2,r=2;break;case 2:e+=Rr[i|n>>6],e+=Rr[n&63],r=0;break}return r&&(e+=Rr[i],e+="=",r==1&&(e+="=")),e}var Ra;(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])})(Ra||(Ra={}));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 Tv(){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 Vc(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 Qo=(1<<16)*(1<<16);function $p(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>=Qo&&(i=i+(n/Qo|0),n=n%Qo)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),[e,n,i]}function Ad(t,e){if(e>>>0<=2097151)return""+(Qo*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 du(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 kv(){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 _v(){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}_v();function Gp(t){if(!t)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const Jp=/^-?[0-9]+$/,Pa=4294967296,vo=2147483648;class qp{constructor(e,r){this.lo=e|0,this.hi=r|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let e=this.hi*Pa+(this.lo>>>0);if(!Number.isSafeInteger(e))throw new Error("cannot convert to safe number");return e}}class lt extends qp{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 lt(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(),!Jp.test(e))throw new Error("string is no integer");let[r,n,i]=$p(e);if(r)throw new Error("signed value for ulong");return new lt(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 lt(e,e/Pa)}throw new Error("unknown value "+typeof e)}toString(){return ke?this.toBigInt().toString():Ad(this.lo,this.hi)}toBigInt(){return Gp(ke),ke.V.setInt32(0,this.lo,!0),ke.V.setInt32(4,this.hi,!0),ke.V.getBigUint64(0,!0)}}lt.ZERO=new lt(0,0);class we extends qp{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 we(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(),!Jp.test(e))throw new Error("string is no integer");let[r,n,i]=$p(e);if(r){if(i>vo||i==vo&&n!=0)throw new Error("signed long too small")}else if(i>=vo)throw new Error("signed long too large");let s=new we(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 we(e,e/Pa):new we(-e,-e/Pa).negate()}throw new Error("unknown value "+typeof e)}isNegative(){return(this.hi&vo)!==0}negate(){let e=~this.hi,r=this.lo;return r?r=~r+1:e+=1,new we(r,e)}toString(){if(ke)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return"-"+Ad(e.lo,e.hi)}return Ad(this.lo,this.hi)}toBigInt(){return Gp(ke),ke.V.setInt32(0,this.lo,!0),ke.V.setInt32(4,this.hi,!0),ke.V.getBigInt64(0,!0)}}we.ZERO=new we(0,0);const lu={readUnknownField:!0,readerFactory:t=>new wv(t)};function bv(t){return t?Object.assign(Object.assign({},lu),t):lu}class wv{constructor(e,r){this.varint64=Tv,this.uint32=kv,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 we(...this.varint64())}uint64(){return new lt(...this.varint64())}sint64(){let[e,r]=this.varint64(),n=-(e&1);return e=(e>>>1|(r&1)<<31)^n,r=r>>>1^n,new we(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 lt(this.sfixed32(),this.sfixed32())}sfixed64(){return new we(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 Cv=34028234663852886e22,Iv=-34028234663852886e22,Rv=4294967295,Pv=2147483647,Av=-2147483648;function Js(t){if(typeof t!="number")throw new Error("invalid int 32: "+typeof t);if(!Number.isInteger(t)||t>Pv||t<Av)throw new Error("invalid int 32: "+t)}function Aa(t){if(typeof t!="number")throw new Error("invalid uint 32: "+typeof t);if(!Number.isInteger(t)||t>Rv||t<0)throw new Error("invalid uint 32: "+t)}function El(t){if(typeof t!="number")throw new Error("invalid float 32: "+typeof t);if(!!Number.isFinite(t)&&(t>Cv||t<Iv))throw new Error("invalid float 32: "+t)}const uu={writeUnknownFields:!0,writerFactory:()=>new Dv};function Mv(t){return t?Object.assign(Object.assign({},uu),t):uu}class Dv{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(Aa(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Js(e),du(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){El(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){Aa(e);let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,e,!0),this.raw(r)}sfixed32(e){Js(e);let r=new Uint8Array(4);return new DataView(r.buffer).setInt32(0,e,!0),this.raw(r)}sint32(e){return Js(e),e=(e<<1^e>>31)>>>0,du(e,this.buf),this}sfixed64(e){let r=new Uint8Array(8),n=new DataView(r.buffer),i=we.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=lt.from(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(r)}int64(e){let r=we.from(e);return Vc(r.lo,r.hi,this.buf),this}sint64(e){let r=we.from(e),n=r.hi>>31,i=r.lo<<1^n,s=(r.hi<<1|r.lo>>>31)^n;return Vc(i,s,this.buf),this}uint64(e){let r=lt.from(e);return Vc(r.lo,r.hi,this.buf),this}}const hu={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},pu={ignoreUnknownFields:!1};function Ov(t){return t?Object.assign(Object.assign({},pu),t):pu}function Nv(t){return t?Object.assign(Object.assign({},hu),t):hu}const Kp=Symbol.for("protobuf-ts/message-type");function mu(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 lr;(function(t){t[t.BIGINT=0]="BIGINT",t[t.STRING=1]="STRING",t[t.NUMBER=2]="NUMBER"})(lr||(lr={}));var Ma;(function(t){t[t.NO=0]="NO",t[t.PACKED=1]="PACKED",t[t.UNPACKED=2]="UNPACKED"})(Ma||(Ma={}));function Lv(t){var e,r,n,i;return t.localName=(e=t.localName)!==null&&e!==void 0?e:mu(t.name),t.jsonName=(r=t.jsonName)!==null&&r!==void 0?r:mu(t.name),t.repeat=(n=t.repeat)!==null&&n!==void 0?n:Ma.NO,t.opt=(i=t.opt)!==null&&i!==void 0?i:t.repeat||t.oneof?!1:t.kind=="message",t}function xv(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 Fv{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(!xv(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 lr.BIGINT:return i=="bigint";case lr.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,lr.STRING)}}}function Xt(t,e){switch(e){case lr.BIGINT:return t.toBigInt();case lr.NUMBER:return t.toNumber();default:return t.toString()}}class Uv{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=yl(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(yv(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,lr.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&&El(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?Aa(a):Js(a),a;case M.INT64:case M.SFIXED64:case M.SINT64:if(e===null)return Xt(we.ZERO,n);if(typeof e!="number"&&typeof e!="string")break;return Xt(we.from(e),n);case M.FIXED64:case M.UINT64:if(e===null)return Xt(lt.ZERO,n);if(typeof e!="number"&&typeof e!="string")break;return Xt(lt.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 Ev(e)}}catch(o){s=o.message}this.assert(!1,i+(s?" - "+s:""),e)}}class Vv{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:(Js(r),r);case M.FIXED32:case M.UINT32:return r===0?o?0:void 0:(Aa(r),r);case M.FLOAT:El(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=lt.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=we.from(r);return d.isZero()&&!o?void 0:d.toString();case M.BYTES:return fe(r instanceof Uint8Array),r.byteLength?Sv(r):o?"":void 0}}}function Md(t,e=lr.STRING){switch(t){case M.BOOL:return!1;case M.UINT64:case M.FIXED64:return Xt(lt.ZERO,e);case M.INT64:case M.SFIXED64:case M.SINT64:return Xt(we.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 Bv{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?Ra.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,lr.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=Md(e.K);o=e.K==M.BOOL?d.toString():d}if(a===void 0)switch(e.V.kind){case"scalar":a=Md(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 Xt(e.int64(),n);case M.UINT64:return Xt(e.uint64(),n);case M.FIXED64:return Xt(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 Xt(e.sfixed64(),n);case M.SINT32:return e.sint32();case M.SINT64:return Xt(e.sint64(),n)}}}class jv{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==Ma.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?Ra.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||we.from(r).isZero(),i="int64";break;case M.UINT64:o=s||lt.from(r).isZero(),i="uint64";break;case M.FIXED64:o=s||lt.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||we.from(r).isZero(),n=Be.Bit64,i="sfixed64";break;case M.SINT32:i="sint32";break;case M.SINT64:o=s||we.from(r).isZero(),i="sint64";break}return[n,i,s||o]}}function Hv(t){const e=t.messagePrototype?Object.create(t.messagePrototype):Object.defineProperty({},Kp,{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]=Md(r.T,r.L);break;case"enum":e[n]=0;break;case"map":e[n]={};break}}return e}function Bc(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 Wv(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?fu(a,s,o):zp(a,s,o)))return!1;break;case"map":if(!(n.V.kind=="message"?gu(n.V.T(),yo(s),yo(o)):fu(n.V.kind=="enum"?M.INT32:n.V.T,yo(s),yo(o))))return!1;break;case"message":let d=n.T();if(!(n.repeat?gu(d,s,o):d.equals(s,o)))return!1;break}}return!0}const yo=Object.values;function zp(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 fu(t,e,r){if(e.length!==r.length)return!1;for(let n=0;n<e.length;n++)if(!zp(t,e[n],r[n]))return!1;return!0}function gu(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 $v=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({}));class k{constructor(e,r,n){this.defaultCheckDepth=16,this.typeName=e,this.fields=r.map(Lv),this.options=n!=null?n:{},this.messagePrototype=Object.create(null,Object.assign(Object.assign({},$v),{[Kp]:{value:this}})),this.refTypeCheck=new Fv(this),this.refJsonReader=new Uv(this),this.refJsonWriter=new Vv(this),this.refBinReader=new Bv(this),this.refBinWriter=new jv(this)}create(e){let r=Hv(this);return e!==void 0&&Bc(this,r,e),r}clone(e){let r=this.create();return Bc(this,r,e),r}equals(e,r){return Wv(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){Bc(this,e,r)}fromBinary(e,r){let n=bv(r);return this.internalBinaryRead(n.readerFactory(e),e.byteLength,n)}fromJson(e,r){return this.internalJsonRead(e,Ov(r))}fromJsonString(e,r){let n=JSON.parse(e);return this.fromJson(n,r)}toJson(e,r){return this.internalJsonWrite(e,Nv(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=Mv(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 ${yl(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 Gv=t=>(e,r)=>(t.set(e,r),r),vu=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,Yp=536870912,yu=Yp*2,Jv=(t,e)=>r=>{const n=e.get(r);let i=n===void 0?r.size:n<yu?n+1:0;if(!r.has(i))return t(r,i);if(r.size<Yp){for(;r.has(i);)i=Math.floor(Math.random()*yu);return t(r,i)}if(r.size>vu)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()*vu);return t(r,i)},Qp=new WeakMap,qv=Gv(Qp),Eo=Jv(qv,Qp),Kv=t=>t.method!==void 0&&t.method==="call",zv=t=>t.error===null&&typeof t.id=="number",Yv=t=>{const e=new Map([[0,()=>{}]]),r=new Map([[0,()=>{}]]),n=new Map,i=new Worker(t);return i.addEventListener("message",({data:h})=>{if(Kv(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(zv(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=Eo(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=Eo(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=Eo(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=Eo(r);return r.set(f,h),i.postMessage({id:null,method:"set",params:{delay:p,now:performance.now(),timerId:f,timerType:"timeout"}}),f}}},Qv=(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}},Xv=`(()=>{"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})}}))})();`,cc=Qv(Yv,Xv),Xp=t=>cc().clearInterval(t),Zv=t=>cc().clearTimeout(t),Zp=(t,e)=>cc().setInterval(t,e),ey=(t,e)=>cc().setTimeout(t,e);var ty=Object.freeze(Object.defineProperty({__proto__:null,clearInterval:Xp,clearTimeout:Zv,setInterval:Zp,setTimeout:ey},Symbol.toStringTag,{value:"Module"})),em={},Sl={exports:{}},Eu=Sl.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(Eu).forEach(function(t){var e=Eu[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=Sl.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}})})}})(em);var jc=Sl.exports,ry=/%[sdv%]/g,ny=function(t){var e=1,r=arguments,n=r.length;return t.replace(ry,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 ny.apply(null,i)},iy=["v","o","s","i","u","e","p","c","b","t","r","z","a"],sy=["i","c","b","a"],oy=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||iy,n=e.innerOrder||sy,i=[];return r.forEach(function(s){jc[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",jc.m[0],s)),n.forEach(function(o){jc[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 Mm{static getParser(e,r=!1){if(typeof e!="string")throw new Error("UserAgent should be a string");return new Yu(e,r)}static parse(e){return new Yu(e).getResult()}static get BROWSER_MAP(){return Am}static get ENGINE_MAP(){return fn}static get OS_MAP(){return bt}static get PLATFORMS_MAP(){return $e}}function su(t){let e=typeof t;if(e=="object"){if(Array.isArray(t))return"array";if(t===null)return"null"}return e}function uy(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}let $r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Gc=[];for(let t=0;t<$r.length;t++)Gc[$r[t].charCodeAt(0)]=t;Gc["-".charCodeAt(0)]=$r.indexOf("+");Gc["_".charCodeAt(0)]=$r.indexOf("/");function hy(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=Gc[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 py(t){let e="",r=0,n,i=0;for(let s=0;s<t.length;s++)switch(n=t[s],r){case 0:e+=$r[n>>2],i=(n&3)<<4,r=1;break;case 1:e+=$r[i|n>>4],i=(n&15)<<2,r=2;break;case 2:e+=$r[i|n>>6],e+=$r[n&63],r=0;break}return r&&(e+=$r[i],e+="=",r==1&&(e+="=")),e}var pc;(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])})(pc||(pc={}));var Ge;(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"})(Ge||(Ge={}));function my(){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 _d(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 xo=(1<<16)*(1<<16);function Dm(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>=xo&&(i=i+(n/xo|0),n=n%xo)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),[e,n,i]}function yl(t,e){if(e>>>0<=2097151)return""+(xo*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 Qu(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 fy(){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 we;function gy(){const t=new DataView(new ArrayBuffer(8));we=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}gy();function Om(t){if(!t)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const Nm=/^-?[0-9]+$/,mc=4294967296,to=2147483648;class Lm{constructor(e,r){this.lo=e|0,this.hi=r|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let e=this.hi*mc+(this.lo>>>0);if(!Number.isSafeInteger(e))throw new Error("cannot convert to safe number");return e}}class vt extends Lm{static from(e){if(we)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=we.C(e);case"number":if(e===0)return this.ZERO;e=we.C(e);case"bigint":if(!e)return this.ZERO;if(e<we.UMIN)throw new Error("signed value for ulong");if(e>we.UMAX)throw new Error("ulong too large");return we.V.setBigUint64(0,e,!0),new vt(we.V.getInt32(0,!0),we.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!Nm.test(e))throw new Error("string is no integer");let[r,n,i]=Dm(e);if(r)throw new Error("signed value for ulong");return new vt(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 vt(e,e/mc)}throw new Error("unknown value "+typeof e)}toString(){return we?this.toBigInt().toString():yl(this.lo,this.hi)}toBigInt(){return Om(we),we.V.setInt32(0,this.lo,!0),we.V.setInt32(4,this.hi,!0),we.V.getBigUint64(0,!0)}}vt.ZERO=new vt(0,0);class Pe extends Lm{static from(e){if(we)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=we.C(e);case"number":if(e===0)return this.ZERO;e=we.C(e);case"bigint":if(!e)return this.ZERO;if(e<we.MIN)throw new Error("signed long too small");if(e>we.MAX)throw new Error("signed long too large");return we.V.setBigInt64(0,e,!0),new Pe(we.V.getInt32(0,!0),we.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!Nm.test(e))throw new Error("string is no integer");let[r,n,i]=Dm(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 Pe(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 Pe(e,e/mc):new Pe(-e,-e/mc).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 Pe(r,e)}toString(){if(we)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return"-"+yl(e.lo,e.hi)}return yl(this.lo,this.hi)}toBigInt(){return Om(we),we.V.setInt32(0,this.lo,!0),we.V.setInt32(4,this.hi,!0),we.V.getBigInt64(0,!0)}}Pe.ZERO=new Pe(0,0);const Xu={readUnknownField:!0,readerFactory:t=>new yy(t)};function vy(t){return t?Object.assign(Object.assign({},Xu),t):Xu}class yy{constructor(e,r){this.varint64=my,this.uint32=fy,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 Ge.Varint:for(;this.buf[this.pos++]&128;);break;case Ge.Bit64:this.pos+=4;case Ge.Bit32:this.pos+=4;break;case Ge.LengthDelimited:let n=this.uint32();this.pos+=n;break;case Ge.StartGroup:let i;for(;(i=this.tag()[1])!==Ge.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 Pe(...this.varint64())}uint64(){return new vt(...this.varint64())}sint64(){let[e,r]=this.varint64(),n=-(e&1);return e=(e>>>1|(r&1)<<31)^n,r=r>>>1^n,new Pe(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 vt(this.sfixed32(),this.sfixed32())}sfixed64(){return new Pe(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 Sy=34028234663852886e22,Ey=-34028234663852886e22,Ty=4294967295,ky=2147483647,_y=-2147483648;function Ma(t){if(typeof t!="number")throw new Error("invalid int 32: "+typeof t);if(!Number.isInteger(t)||t>ky||t<_y)throw new Error("invalid int 32: "+t)}function fc(t){if(typeof t!="number")throw new Error("invalid uint 32: "+typeof t);if(!Number.isInteger(t)||t>Ty||t<0)throw new Error("invalid uint 32: "+t)}function au(t){if(typeof t!="number")throw new Error("invalid float 32: "+typeof t);if(!!Number.isFinite(t)&&(t>Sy||t<Ey))throw new Error("invalid float 32: "+t)}const Zu={writeUnknownFields:!0,writerFactory:()=>new wy};function by(t){return t?Object.assign(Object.assign({},Zu),t):Zu}class wy{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(fc(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Ma(e),Qu(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){au(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){fc(e);let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,e,!0),this.raw(r)}sfixed32(e){Ma(e);let r=new Uint8Array(4);return new DataView(r.buffer).setInt32(0,e,!0),this.raw(r)}sint32(e){return Ma(e),e=(e<<1^e>>31)>>>0,Qu(e,this.buf),this}sfixed64(e){let r=new Uint8Array(8),n=new DataView(r.buffer),i=Pe.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=vt.from(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(r)}int64(e){let r=Pe.from(e);return _d(r.lo,r.hi,this.buf),this}sint64(e){let r=Pe.from(e),n=r.hi>>31,i=r.lo<<1^n,s=(r.hi<<1|r.lo>>>31)^n;return _d(i,s,this.buf),this}uint64(e){let r=vt.from(e);return _d(r.lo,r.hi,this.buf),this}}const eh={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},th={ignoreUnknownFields:!1};function Iy(t){return t?Object.assign(Object.assign({},th),t):th}function Cy(t){return t?Object.assign(Object.assign({},eh),t):eh}const xm=Symbol.for("protobuf-ts/message-type");function rh(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 Tr;(function(t){t[t.BIGINT=0]="BIGINT",t[t.STRING=1]="STRING",t[t.NUMBER=2]="NUMBER"})(Tr||(Tr={}));var gc;(function(t){t[t.NO=0]="NO",t[t.PACKED=1]="PACKED",t[t.UNPACKED=2]="UNPACKED"})(gc||(gc={}));function Py(t){var e,r,n,i;return t.localName=(e=t.localName)!==null&&e!==void 0?e:rh(t.name),t.jsonName=(r=t.jsonName)!==null&&r!==void 0?r:rh(t.name),t.repeat=(n=t.repeat)!==null&&n!==void 0?n:gc.NO,t.opt=(i=t.opt)!==null&&i!==void 0?i:t.repeat||t.oneof?!1:t.kind=="message",t}function Ry(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 Ay{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(!Ry(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 Tr.BIGINT:return i=="bigint";case Tr.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,Tr.STRING)}}}function lr(t,e){switch(e){case Tr.BIGINT:return t.toBigInt();case Tr.NUMBER:return t.toNumber();default:return t.toString()}}class My{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=su(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(uy(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,Tr.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&&au(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?fc(o):Ma(o),o;case L.INT64:case L.SFIXED64:case L.SINT64:if(e===null)return lr(Pe.ZERO,n);if(typeof e!="number"&&typeof e!="string")break;return lr(Pe.from(e),n);case L.FIXED64:case L.UINT64:if(e===null)return lr(vt.ZERO,n);if(typeof e!="number"&&typeof e!="string")break;return lr(vt.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 hy(e)}}catch(a){s=a.message}this.assert(!1,i+(s?" - "+s:""),e)}}class Dy{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:(Ma(r),r);case L.FIXED32:case L.UINT32:return r===0?a?0:void 0:(fc(r),r);case L.FLOAT:au(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=vt.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=Pe.from(r);return d.isZero()&&!a?void 0:d.toString();case L.BYTES:return ye(r instanceof Uint8Array),r.byteLength?py(r):a?"":void 0}}}function Sl(t,e=Tr.STRING){switch(t){case L.BOOL:return!1;case L.UINT64:case L.FIXED64:return lr(vt.ZERO,e);case L.INT64:case L.SFIXED64:case L.SINT64:return lr(Pe.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 Oy{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?pc.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==Ge.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,Tr.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=Sl(e.K);a=e.K==L.BOOL?d.toString():d}if(o===void 0)switch(e.V.kind){case"scalar":o=Sl(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 lr(e.int64(),n);case L.UINT64:return lr(e.uint64(),n);case L.FIXED64:return lr(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 lr(e.sfixed64(),n);case L.SINT32:return e.sint32();case L.SINT64:return lr(e.sint64(),n)}}}class Ny{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==gc.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?pc.onWrite:i)(this.info.typeName,e,r)}mapEntry(e,r,n,i,s){e.tag(n.no,Ge.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,Ge.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,Ge.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=Ge.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=Ge.LengthDelimited,i="string";break;case L.BOOL:a=r===!1,i="bool";break;case L.UINT32:i="uint32";break;case L.DOUBLE:n=Ge.Bit64,i="double";break;case L.FLOAT:n=Ge.Bit32,i="float";break;case L.INT64:a=s||Pe.from(r).isZero(),i="int64";break;case L.UINT64:a=s||vt.from(r).isZero(),i="uint64";break;case L.FIXED64:a=s||vt.from(r).isZero(),n=Ge.Bit64,i="fixed64";break;case L.BYTES:a=s||!r.byteLength,n=Ge.LengthDelimited,i="bytes";break;case L.FIXED32:n=Ge.Bit32,i="fixed32";break;case L.SFIXED32:n=Ge.Bit32,i="sfixed32";break;case L.SFIXED64:a=s||Pe.from(r).isZero(),n=Ge.Bit64,i="sfixed64";break;case L.SINT32:i="sint32";break;case L.SINT64:a=s||Pe.from(r).isZero(),i="sint64";break}return[n,i,s||a]}}function Ly(t){const e=t.messagePrototype?Object.create(t.messagePrototype):Object.defineProperty({},xm,{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]=Sl(r.T,r.L);break;case"enum":e[n]=0;break;case"map":e[n]={};break}}return e}function bd(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 xy(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?nh(o,s,a):Fm(o,s,a)))return!1;break;case"map":if(!(n.V.kind=="message"?ih(n.V.T(),ro(s),ro(a)):nh(n.V.kind=="enum"?L.INT32:n.V.T,ro(s),ro(a))))return!1;break;case"message":let d=n.T();if(!(n.repeat?ih(d,s,a):d.equals(s,a)))return!1;break}}return!0}const ro=Object.values;function Fm(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 nh(t,e,r){if(e.length!==r.length)return!1;for(let n=0;n<e.length;n++)if(!Fm(t,e[n],r[n]))return!1;return!0}function ih(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 Fy=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({}));class E{constructor(e,r,n){this.defaultCheckDepth=16,this.typeName=e,this.fields=r.map(Py),this.options=n!=null?n:{},this.messagePrototype=Object.create(null,Object.assign(Object.assign({},Fy),{[xm]:{value:this}})),this.refTypeCheck=new Ay(this),this.refJsonReader=new My(this),this.refJsonWriter=new Dy(this),this.refBinReader=new Oy(this),this.refBinWriter=new Ny(this)}create(e){let r=Ly(this);return e!==void 0&&bd(this,r,e),r}clone(e){let r=this.create();return bd(this,r,e),r}equals(e,r){return xy(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){bd(this,e,r)}fromBinary(e,r){let n=vy(r);return this.internalBinaryRead(n.readerFactory(e),e.byteLength,n)}fromJson(e,r){return this.internalJsonRead(e,Iy(r))}fromJsonString(e,r){let n=JSON.parse(e);return this.fromJson(n,r)}toJson(e,r){return this.internalJsonWrite(e,Cy(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=by(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 ${su(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 Vy=t=>(e,r)=>(t.set(e,r),r),sh=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,Vm=536870912,ah=Vm*2,Uy=(t,e)=>r=>{const n=e.get(r);let i=n===void 0?r.size:n<ah?n+1:0;if(!r.has(i))return t(r,i);if(r.size<Vm){for(;r.has(i);)i=Math.floor(Math.random()*ah);return t(r,i)}if(r.size>sh)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()*sh);return t(r,i)},Um=new WeakMap,By=Vy(Um),no=Uy(By,Um),jy=t=>t.method!==void 0&&t.method==="call",Hy=t=>t.error===null&&typeof t.id=="number",Wy=t=>{const e=new Map([[0,()=>{}]]),r=new Map([[0,()=>{}]]),n=new Map,i=new Worker(t);return i.addEventListener("message",({data:h})=>{if(jy(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(Hy(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=no(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=no(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=no(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=no(r);return r.set(m,h),i.postMessage({id:null,method:"set",params:{delay:p,now:performance.now(),timerId:m,timerType:"timeout"}}),m}}},$y=(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}},Jy=`(()=>{"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})}}))})();`,qc=$y(Wy,Jy),Bm=t=>qc().clearInterval(t),Gy=t=>qc().clearTimeout(t),jm=(t,e)=>qc().setInterval(t,e),qy=(t,e)=>qc().setTimeout(t,e);var zy=Object.freeze(Object.defineProperty({__proto__:null,clearInterval:Bm,clearTimeout:Gy,setInterval:jm,setTimeout:qy},Symbol.toStringTag,{value:"Module"})),Hm={},ou={exports:{}},oh=ou.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(oh).forEach(function(t){var e=oh[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=ou.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}})})}})(Hm);var wd=ou.exports,Ky=/%[sdv%]/g,Yy=function(t){var e=1,r=arguments,n=r.length;return t.replace(Ky,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""}})},Ns=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 Yy.apply(null,i)},Qy=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Xy=["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||Qy,n=e.innerOrder||Xy,i=[];return r.forEach(function(s){wd[s].forEach(function(a){a.name in t&&t[a.name]!=null?i.push(Ns(s,a,t)):a.push in t&&t[a.push]!=null&&t[a.push].forEach(function(o){i.push(Ns(s,a,o))})})}),t.media.forEach(function(s){i.push(Ns("m",wd.m[0],s)),n.forEach(function(a){wd[a].forEach(function(o){o.name in s&&s[o.name]!=null?i.push(Ns(a,o,s)):o.push in s&&s[o.push]!=null&&s[o.push].forEach(function(d){i.push(Ns(a,o,d))})})})}),i.join(`\r
8
8
  `)+`\r
9
- `},oi=em,ay=oy,cy=ay,Tl=oi.parse;oi.parseParams;oi.parseFmtpConfig;oi.parsePayloads;oi.parseRemoteCandidates;oi.parseImageAttributes;oi.parseSimulcastStreamList;var dy=Object.defineProperty,ly=Object.defineProperties,uy=Object.getOwnPropertyDescriptors,Da=Object.getOwnPropertySymbols,hy=Object.getPrototypeOf,tm=Object.prototype.hasOwnProperty,rm=Object.prototype.propertyIsEnumerable,py=Reflect.get,my=Math.pow,Dd=(t,e,r)=>e in t?dy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,V=(t,e)=>{for(var r in e||(e={}))tm.call(e,r)&&Dd(t,r,e[r]);if(Da)for(var r of Da(e))rm.call(e,r)&&Dd(t,r,e[r]);return t},ne=(t,e)=>ly(t,uy(e)),dc=(t,e)=>{var r={};for(var n in t)tm.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&Da)for(var n of Da(t))e.indexOf(n)<0&&rm.call(t,n)&&(r[n]=t[n]);return r},m=(t,e,r)=>(Dd(t,typeof e!="symbol"?e+"":e,r),r),kl=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},c=(t,e,r)=>(kl(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)=>(kl(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),ue=(t,e,r)=>(kl(t,e,"access private method"),r),fy=(t,e,r)=>py(hy(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())}),Su=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function gy(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var wt={},vy={get exports(){return wt},set exports(t){wt=t}},Wi=typeof Reflect=="object"?Reflect:null,Tu=Wi&&typeof Wi.apply=="function"?Wi.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},Xo;Wi&&typeof Wi.ownKeys=="function"?Xo=Wi.ownKeys:Object.getOwnPropertySymbols?Xo=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Xo=function(t){return Object.getOwnPropertyNames(t)};function yy(t){console&&console.warn&&console.warn(t)}var nm=Number.isNaN||function(t){return t!==t};function Ee(){Ee.init.call(this)}vy.exports=Ee;wt.once=ky;Ee.EventEmitter=Ee;Ee.prototype._events=void 0;Ee.prototype._eventsCount=0;Ee.prototype._maxListeners=void 0;var ku=10;function lc(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 ku},set:function(t){if(typeof t!="number"||t<0||nm(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");ku=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||nm(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 im(t){return t._maxListeners===void 0?Ee.defaultMaxListeners:t._maxListeners}Ee.prototype.getMaxListeners=function(){return im(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")Tu(a,this,e);else for(var d=a.length,h=dm(a,d),r=0;r<d;++r)Tu(h[r],this,e);return!0};function sm(t,e,r,n){var i,s,o;if(lc(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=im(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,yy(a)}return t}Ee.prototype.addListener=function(t,e){return sm(this,t,e,!1)};Ee.prototype.on=Ee.prototype.addListener;Ee.prototype.prependListener=function(t,e){return sm(this,t,e,!0)};function Ey(){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 om(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=Ey.bind(n);return i.listener=r,n.wrapFn=i,i}Ee.prototype.once=function(t,e){return lc(e),this.on(t,om(this,t,e)),this};Ee.prototype.prependOnceListener=function(t,e){return lc(e),this.prependListener(t,om(this,t,e)),this};Ee.prototype.removeListener=function(t,e){var r,n,i,s,o;if(lc(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():Sy(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 am(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?Ty(i):dm(i,i.length)}Ee.prototype.listeners=function(t){return am(this,t,!0)};Ee.prototype.rawListeners=function(t){return am(this,t,!1)};Ee.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):cm.call(t,e)};Ee.prototype.listenerCount=cm;function cm(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?Xo(this._events):[]};function dm(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function Sy(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function Ty(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function ky(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))}lm(t,e,s,{once:!0}),e!=="error"&&_y(t,i,{once:!0})})}function _y(t,e,r){typeof t.on=="function"&&lm(t,"error",e,r)}function lm(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 cr={},by={get exports(){return cr},set exports(t){cr=t}},Hc,_u;function wy(){if(_u)return Hc;_u=1;var t=1e3,e=t*60,r=e*60,n=r*24,i=n*7,s=n*365.25;Hc=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 Hc}function Cy(t){r.debug=r,r.default=r,r.coerce=d,r.disable=s,r.enable=i,r.enabled=o,r.humanize=wy(),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 D=A[H];I=P.call(L,D),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 Iy=Cy;(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{}}function s(){let d;try{d=e.storage.getItem("debug")}catch{}return!d&&typeof process!="undefined"&&"env"in process&&(d={}.DEBUG),d}function o(){try{return localStorage}catch{}}t.exports=Iy(e);const{formatters:a}=t.exports;a.j=function(d){try{return JSON.stringify(d)}catch(h){return"[UnexpectedJSONParseError]: "+h.message}}})(by,cr);const fi="mediasoup-client";let Ry=class{constructor(t){t?(this._debug=cr(`${fi}:${t}`),this._warn=cr(`${fi}:WARN:${t}`),this._error=cr(`${fi}:ERROR:${t}`)):(this._debug=cr(fi),this._warn=cr(`${fi}:WARN`),this._error=cr(`${fi}: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 Py=new Ry("EnhancedEventEmitter");let Oa=class extends wt.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 Py.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 Ay=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 My{constructor(){m(this,"events"),this.events=[]}add(e){this.events.push(e)}flush(){return{entries:this.events.splice(0,25)}}}class Dy extends wt{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 My}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),Ay.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 bu;(function(t){t.CHROMIUM="chromum",t.FIREFOX="firefox",t.SAFARI="safari"})(bu||(bu={}));const qs={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var Wt;(function(t){t.AUDIO="AUDIO",t.VIDEO="VIDEO",t.SPEAKER="SPEAKER",t.SCREENSHARE="SCREENSHARE"})(Wt||(Wt={}));var wu;(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"})(wu||(wu={}));const um=240,hm=720,pm=8,mm=3,uc=10,hc=.02,pc=.03;function Or({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 fm({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 gm({packetsLost:t,packetsSent:e}){return e>0?t*100/e:0}function vm({packetsLost:t,packetsSent:e,jitter:r}){const n=Or({stat:gm({packetsLost:t,packetsSent:e}),weight:.7,rangeMin:0,rangeMax:uc,rangeRankingDirection:"UP"}),i=Or({stat:r,weight:.3,rangeMin:hc,rangeMax:pc,rangeRankingDirection:"UP"});return n+i}function Oy({frameWidth:t,isScreenShare:e}){return t<(e?hm:um)}function Ny({framesPerSecond:t,isScreenShare:e}){return t<(e?mm:pm)}function Ly({framesEncoded:t}){return t===0}function ym({frameWidth:t,framesPerSecond:e,packetsLost:r,packetsSent:n,jitter:i,isScreenShare:s,framesEncoded:o}){const a=Or({stat:gm({packetsLost:r,packetsSent:n}),weight:1,rangeMin:0,rangeMax:uc,rangeRankingDirection:"UP"}),d=Or({stat:i,weight:1,rangeMin:hc,rangeMax:pc,rangeRankingDirection:"UP"}),h=Oy({frameWidth:t,isScreenShare:s}),p=Ny({framesPerSecond:e,isScreenShare:s}),f=Ly({framesEncoded:o,isScreenShare:s});return fm({isLowQualityVideo:h,isVideoLagging:p,isVideoStuck:f,jitterQuality:d,packetsLostQuality:a})}function Em({packetsLost:t,packetsReceived:e}){return e+t>0?t*100/(e+t):0}function Sm({concealmentEvents:t,packetsLost:e,packetsReceived:r,jitter:n}){const i=Or({stat:t,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),s=.5,o=Or({stat:Em({packetsLost:e,packetsReceived:r}),weight:s,rangeMin:0,rangeMax:uc,rangeRankingDirection:"UP"}),a=Or({stat:n,weight:.3,rangeMin:hc,rangeMax:pc,rangeRankingDirection:"UP"});return i+o+a}function xy({framesDecoded:t}){return t===0}function Fy({framesPerSecond:t,isScreenShare:e}){return t<(e?mm:pm)}function Uy({frameWidth:t,isScreenShare:e}){return t<(e?hm:um)}function Tm({frameWidth:t,framesPerSecond:e,packetsLost:r,packetsReceived:n,jitter:i,isScreenShare:s,framesDecoded:o}){const a=Or({stat:Em({packetsLost:r,packetsReceived:n}),weight:1,rangeMin:0,rangeMax:uc,rangeRankingDirection:"UP"}),d=Or({stat:i,weight:1,rangeMin:hc,rangeMax:pc,rangeRankingDirection:"UP"}),h=Uy({frameWidth:t,isScreenShare:s}),p=Fy({framesPerSecond:e,isScreenShare:s}),f=xy({framesDecoded:o,isScreenShare:s});return fm({isLowQualityVideo:h,isVideoLagging:p,isVideoStuck:f,jitterQuality:d,packetsLostQuality:a})}class Nr{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=Nr.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=Nr.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
+ `},Ti=Hm,eS=Zy,tS=eS,cu=Ti.parse;Ti.parseParams;Ti.parseFmtpConfig;Ti.parsePayloads;Ti.parseRemoteCandidates;Ti.parseImageAttributes;Ti.parseSimulcastStreamList;var rS=Object.defineProperty,nS=Object.defineProperties,iS=Object.getOwnPropertyDescriptors,vc=Object.getOwnPropertySymbols,sS=Object.getPrototypeOf,Wm=Object.prototype.hasOwnProperty,$m=Object.prototype.propertyIsEnumerable,aS=Reflect.get,oS=Math.pow,El=(t,e,r)=>e in t?rS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,B=(t,e)=>{for(var r in e||(e={}))Wm.call(e,r)&&El(t,r,e[r]);if(vc)for(var r of vc(e))$m.call(e,r)&&El(t,r,e[r]);return t},Z=(t,e)=>nS(t,iS(e)),zc=(t,e)=>{var r={};for(var n in t)Wm.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&vc)for(var n of vc(t))e.indexOf(n)<0&&$m.call(t,n)&&(r[n]=t[n]);return r},f=(t,e,r)=>(El(t,typeof e!="symbol"?e+"":e,r),r),du=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},c=(t,e,r)=>(du(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)=>(du(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),Ke=(t,e,r)=>(du(t,e,"access private method"),r),cS=(t,e,r)=>aS(sS(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())}),ch=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function dS(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var mt={},lS={get exports(){return mt},set exports(t){mt=t}},rs=typeof Reflect=="object"?Reflect:null,dh=rs&&typeof rs.apply=="function"?rs.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},Fo;rs&&typeof rs.ownKeys=="function"?Fo=rs.ownKeys:Object.getOwnPropertySymbols?Fo=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Fo=function(t){return Object.getOwnPropertyNames(t)};function uS(t){console&&console.warn&&console.warn(t)}var Jm=Number.isNaN||function(t){return t!==t};function Te(){Te.init.call(this)}lS.exports=Te;mt.once=fS;Te.EventEmitter=Te;Te.prototype._events=void 0;Te.prototype._eventsCount=0;Te.prototype._maxListeners=void 0;var lh=10;function Kc(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(Te,"defaultMaxListeners",{enumerable:!0,get:function(){return lh},set:function(t){if(typeof t!="number"||t<0||Jm(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");lh=t}});Te.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};Te.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Jm(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 Gm(t){return t._maxListeners===void 0?Te.defaultMaxListeners:t._maxListeners}Te.prototype.getMaxListeners=function(){return Gm(this)};Te.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")dh(o,this,e);else for(var d=o.length,h=Qm(o,d),r=0;r<d;++r)dh(h[r],this,e);return!0};function qm(t,e,r,n){var i,s,a;if(Kc(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=Gm(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,uS(o)}return t}Te.prototype.addListener=function(t,e){return qm(this,t,e,!1)};Te.prototype.on=Te.prototype.addListener;Te.prototype.prependListener=function(t,e){return qm(this,t,e,!0)};function hS(){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 zm(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=hS.bind(n);return i.listener=r,n.wrapFn=i,i}Te.prototype.once=function(t,e){return Kc(e),this.on(t,zm(this,t,e)),this};Te.prototype.prependOnceListener=function(t,e){return Kc(e),this.prependListener(t,zm(this,t,e)),this};Te.prototype.removeListener=function(t,e){var r,n,i,s,a;if(Kc(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():pS(r,i),r.length===1&&(n[t]=r[0]),n.removeListener!==void 0&&this.emit("removeListener",t,a||e)}return this};Te.prototype.off=Te.prototype.removeListener;Te.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 Km(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?mS(i):Qm(i,i.length)}Te.prototype.listeners=function(t){return Km(this,t,!0)};Te.prototype.rawListeners=function(t){return Km(this,t,!1)};Te.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Ym.call(t,e)};Te.prototype.listenerCount=Ym;function Ym(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}Te.prototype.eventNames=function(){return this._eventsCount>0?Fo(this._events):[]};function Qm(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function pS(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function mS(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function fS(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))}Xm(t,e,s,{once:!0}),e!=="error"&&gS(t,i,{once:!0})})}function gS(t,e,r){typeof t.on=="function"&&Xm(t,"error",e,r)}function Xm(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 X;(function(t){t[t.MAJOR_EVENT=0]="MAJOR_EVENT",t[t.MINOR_EVENT=1]="MINOR_EVENT"})(X||(X={}));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 vS=new Map([[V.PRECALL_TEST_BEGIN,X.MINOR_EVENT],[V.PRECALL_TEST_COMPLETE,X.MINOR_EVENT],[V.CALL_JOIN_BEGIN,X.MAJOR_EVENT],[V.NET_QUALITY_TEST_BEGIN,X.MINOR_EVENT],[V.NET_QUALITY_TEST_END,X.MINOR_EVENT],[V.WEBSOCKET_CONNECTED,X.MINOR_EVENT],[V.TRANSPORT_CONNECTED,X.MAJOR_EVENT],[V.AUDIO_ON,X.MINOR_EVENT],[V.AUDIO_OFF,X.MINOR_EVENT],[V.VIDEO_ON,X.MINOR_EVENT],[V.VIDEO_OFF,X.MINOR_EVENT],[V.PARTICIPANT_ROLE,X.MINOR_EVENT],[V.PING_STAT,X.MAJOR_EVENT],[V.DISCONNECT,X.MAJOR_EVENT],[V.RECONNECT_ATTEMPT,X.MAJOR_EVENT],[V.SCREENSHARE_START_REQUESTED,X.MINOR_EVENT],[V.SCREENSHARE_STARTED,X.MINOR_EVENT],[V.SCREENSHARE_STOPPED,X.MINOR_EVENT],[V.TAB_CHANGE,X.MINOR_EVENT],[V.BROWSER_BACKGROUNDED,X.MINOR_EVENT],[V.BROWSER_FOREGROUNDED,X.MINOR_EVENT],[V.DOMINANT_SPEAKER,X.MINOR_EVENT],[V.AUDIO_DEVICES_UPDATES,X.MINOR_EVENT],[V.VIDEO_DEVICES_UPDATES,X.MINOR_EVENT],[V.SPEAKER_DEVICES_UPDATES,X.MINOR_EVENT],[V.SELECTED_MICROHPONE_UPDATE,X.MINOR_EVENT],[V.SELECTED_CAMERA_UPDATE,X.MINOR_EVENT],[V.SELECTED_SPEAKER_UPDATE,X.MINOR_EVENT],[V.MEDIA_PERMISSION,X.MINOR_EVENT],[V.LEGACY_SWITCH,X.MINOR_EVENT],[V.AUDIO_PLAY_FAILED,X.MINOR_EVENT],[V.VIDEO_PLAY_FAILED,X.MINOR_EVENT],[V.AUDIO_TRACK_MUTED,X.MINOR_EVENT],[V.VIDEO_TRACK_MUTED,X.MINOR_EVENT],[V.IVS_PLAYER_REBUFFERING,X.MAJOR_EVENT],[V.IVS_PLAYER_AUDIO_BLOCKED,X.MAJOR_EVENT],[V.IVS_PLAYER_PLAYBACK_BLOCKED,X.MAJOR_EVENT],[V.IVS_PLAYER_ERROR,X.MAJOR_EVENT],[V.IVS_PLAYER_RECOVERABLE_ERROR,X.MAJOR_EVENT],[V.IVS_PLAYER_WORKER_ERROR,X.MAJOR_EVENT],[V.IVS_PLAYER_NETWORK_UNAVAILABLE,X.MAJOR_EVENT],[V.LIVESTREAM_LATENCY,X.MAJOR_EVENT],[V.IVS_PLAYER_ANALYTICS_EVENT,X.MINOR_EVENT],[V.IVS_PLAYER_PLAYBACK_RATE_CHANGED,X.MINOR_EVENT],[V.IVS_PLAYER_QUALITY_CHANGED,X.MINOR_EVENT],[V.IVS_PLAYER_INITIALIZED,X.MINOR_EVENT],[V.EXPECTED_VIDEO_RESOLUTION,X.MINOR_EVENT],[V.EXPECTED_SCREENSHARE_RESOLUTION,X.MINOR_EVENT]]);class yS{constructor(){f(this,"events"),this.events=[]}add(e){this.events.push(e)}flush(){return{entries:this.events.splice(0,25)}}}class SS extends mt{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 yS}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),vS.get(e.event)===X.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 uh;(function(t){t.CHROMIUM="chromum",t.FIREFOX="firefox",t.SAFARI="safari"})(uh||(uh={}));const Da={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var Zt;(function(t){t.AUDIO="AUDIO",t.VIDEO="VIDEO",t.SPEAKER="SPEAKER",t.SCREENSHARE="SCREENSHARE"})(Zt||(Zt={}));var hh;(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"})(hh||(hh={}));function An(t){return t?t.split(".").slice(0,2).concat(["0","0"]).join("."):""}function yc({packetsLost:t,packetsSent:e}){return e>0?t*100/e:0}function Sc({packetsLost:t,packetsReceived:e}){return e+t>0?t*100/(e+t):0}const Zm=240,ef=720,tf=8,rf=3,Yc=10,Qc=.02,Xc=.03;function Kr({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 nf({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 sf({packetsLost:t,packetsSent:e}){return e>0?t*100/e:0}function af({packetsLost:t,packetsSent:e,jitter:r}){const n=Kr({stat:sf({packetsLost:t,packetsSent:e}),weight:.7,rangeMin:0,rangeMax:Yc,rangeRankingDirection:"UP"}),i=Kr({stat:r,weight:.3,rangeMin:Qc,rangeMax:Xc,rangeRankingDirection:"UP"});return n+i}function ES({frameWidth:t,isScreenShare:e}){return t<(e?ef:Zm)}function TS({framesPerSecond:t,isScreenShare:e}){return t<(e?rf:tf)}function kS({framesEncoded:t}){return t===0}function of({frameWidth:t,framesPerSecond:e,packetsLost:r,packetsSent:n,jitter:i,isScreenShare:s,framesEncoded:a}){const o=Kr({stat:sf({packetsLost:r,packetsSent:n}),weight:1,rangeMin:0,rangeMax:Yc,rangeRankingDirection:"UP"}),d=Kr({stat:i,weight:1,rangeMin:Qc,rangeMax:Xc,rangeRankingDirection:"UP"}),h=ES({frameWidth:t,isScreenShare:s}),p=TS({framesPerSecond:e,isScreenShare:s}),m=kS({framesEncoded:a,isScreenShare:s});return nf({isLowQualityVideo:h,isVideoLagging:p,isVideoStuck:m,jitterQuality:d,packetsLostQuality:o})}function cf({packetsLost:t,packetsReceived:e}){return e+t>0?t*100/(e+t):0}function df({concealmentEvents:t,packetsLost:e,packetsReceived:r,jitter:n}){const i=Kr({stat:t,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),s=.5,a=Kr({stat:cf({packetsLost:e,packetsReceived:r}),weight:s,rangeMin:0,rangeMax:Yc,rangeRankingDirection:"UP"}),o=Kr({stat:n,weight:.3,rangeMin:Qc,rangeMax:Xc,rangeRankingDirection:"UP"});return i+a+o}function _S({framesDecoded:t}){return t===0}function bS({framesPerSecond:t,isScreenShare:e}){return t<(e?rf:tf)}function wS({frameWidth:t,isScreenShare:e}){return t<(e?ef:Zm)}function lf({frameWidth:t,framesPerSecond:e,packetsLost:r,packetsReceived:n,jitter:i,isScreenShare:s,framesDecoded:a}){const o=Kr({stat:cf({packetsLost:r,packetsReceived:n}),weight:1,rangeMin:0,rangeMax:Yc,rangeRankingDirection:"UP"}),d=Kr({stat:i,weight:1,rangeMin:Qc,rangeMax:Xc,rangeRankingDirection:"UP"}),h=wS({frameWidth:t,isScreenShare:s}),p=bS({framesPerSecond:e,isScreenShare:s}),m=_S({framesDecoded:a,isScreenShare:s});return nf({isLowQualityVideo:h,isVideoLagging:p,isVideoStuck:m,jitterQuality:d,packetsLostQuality:o})}class Qr{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=Qr.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=Qr.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{return}})}close(){this.pc1.close(),this.pc2.close()}}class km extends wt{constructor(e){super(),m(this,"call"),m(this,"timeOut"),this.call=new Nr(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 Vy=8,By=1/1e3;class jy extends km{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(Nr.isNotHostCandidate),this.senderChannel=this.call.pc1.createDataChannel(null);for(let r=0;r<1024*256;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{}}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)*Vy/(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*By)})}}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 _l extends km{constructor(e,r=Nr.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{}}dataChannelHandler(e){const r=e.channel;this.ch2=r,r.addEventListener("message",this.onCh2Recieve.bind(this))}hangup(e){this.testFailed(e)}}class Hy extends _l{constructor(e){super(e,Nr.isHost)}}class Wy extends _l{constructor(e){super(e,Nr.isRelay)}}class $y extends _l{constructor(e){super(e,Nr.isReflexive)}}class Gy{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{}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 bl=new Gy,Cu=[{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 Iu(t){const[e,r]=t.split(",");return{coords:{latitude:Number(e),longitude:Number(r)}}}class _m{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 bm extends Oa{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 Oa}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 _m,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,D=I,ae={nominated:S!=null?S:P,currentRoundTripTime:D.currentRoundTripTime,totalRoundTripTime:D.totalRoundTripTime,bytesReceived:D.bytesReceived,bytesSent:D.bytesSent,availableOutgoingBitrate:D.availableOutgoingBitrate,lastPacketReceivedTimestamp:D.lastPacketReceivedTimestamp,lastPacketSentTimestamp:D.lastPacketSentTimestamp,localCandidateId:D.localCandidateId,remoteCandidateId:D.remoteCandidateId,bytesDiscardedOnSend:D.bytesDiscardedOnSend,packetsSent:D.packetsSent,packetsReceived:D.packetsReceived,packetsDiscardedOnSend:D.packetsDiscardedOnSend};F.push(ae),(I.nominated===!0||I.selected===!0)&&(v.candidatePair=ae);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 D=this.overallProducingTransportsStatsMap[s.id];this.processProducingTransportStats(s.id,D,P)}if(s.consuming){const D=this.overallConsumingTransportsStatsMap[s.id];this.processConsumingTransportStats(s.id,D,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),D=this.pausedProducerMap.get(P);if(D){if(D.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const ae=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 De=this.callStatsInstance.producers.get(P);if(((o=De==null?void 0:De.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,ve=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,ve),v.outboundVideoRtp.set(I.id,ve),v.producerStreamMap.get(P).outboundVideoRtpId.push(I.id),this.processOutboundProducerVideoStats(P,ae,ve)}else if(S.mediaType==="audio"||S.kind==="audio"){const x=S,ve=V({retransmittedBytesSent:x.retransmittedBytesSent,retransmittedPacketsSent:x.retransmittedPacketsSent},$);this.audioProducerToStatsMap.set(P,ve),v.outboundAudioRtp.set(I.id,ve),v.producerStreamMap.get(P).outboundAudioRtpId.push(I.id),this.processOutboundProducerAudioStats(P,ae,ve)}}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),D=this.pausedConsumerMap.get(P);if(D){if(D.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 ae=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 De={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},De);x.score=Tm({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,ae,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},De);x.score=Sm({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,ae,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,D,ae,De,$,x,ve,Ur,gn,vn,ct;if(I.outboundVideoRtpId.length>0){const qe=[];I.outboundVideoRtpId.forEach(cs=>{qe.push(v.outboundVideoRtp.get(cs))});const Ke=this.getWorkingSimulcastVideoStats(qe);Ke.score=ym({frameWidth:Ke.frameWidth||0,framesPerSecond:Ke.framesPerSecond||0,jitter:((P=Ke.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsSent:(Ke.packetsSent||0)-(((D=this.videoProducerToStatsMap.get(S))==null?void 0:D.packetsSent)||0),packetsLost:(((ae=Ke.remoteData)==null?void 0:ae.packetsLost)||0)-((($=(De=this.videoProducerToStatsMap.get(S))==null?void 0:De.remoteData)==null?void 0:$.packetsLost)||0),framesEncoded:(Ke.framesEncoded||0)-(((x=this.videoProducerToStatsMap.get(S))==null?void 0:x.framesEncoded)||0)}),W.set(S,Ke.score)}else if(I.outboundAudioRtpId.length>0){const qe=v.outboundAudioRtp.get(I.outboundAudioRtpId[0]);qe.score=vm({packetsSent:(qe.packetsSent||0)-(((ve=this.audioProducerToStatsMap.get(S))==null?void 0:ve.packetsSent)||0),packetsLost:(((Ur=qe.remoteData)==null?void 0:Ur.packetsLost)||0)-(((vn=(gn=this.audioProducerToStatsMap.get(S))==null?void 0:gn.remoteData)==null?void 0:vn.packetsLost)||0),jitter:((ct=qe.remoteData)==null?void 0:ct.jitter)||0}),W.set(S,qe.score)}}),F.forEach(I=>{const S=A.find(D=>D.id===I.localCandidateId?(I.localCandidateId=D.id,D):null),P=L.find(D=>D.id===I.remoteCandidateId?(I.remoteCandidateId=D.id,D):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,D)=>{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||Cu},n=new Promise((h,p)=>{try{const f=new Hy(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 Wy(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 $y(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{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||Cu},o=new jy(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{return}})}getIPDetails(){return u(this,null,function*(){var e,r;try{return this.ipDetails||(this.ipDetails=yield bl.getIPDetails({peerId:(e=this.callStatsInstance)==null?void 0:e.peerId,apiHostnames:(r=this.callStatsInstance)==null?void 0:r.apiHostnames})),this.ipDetails}catch{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?Iu(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?Iu(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 bm{}class wm extends bm{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 _m,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,D=I,ae={nominated:S!=null?S:P,currentRoundTripTime:D.currentRoundTripTime,totalRoundTripTime:D.totalRoundTripTime,bytesReceived:D.bytesReceived,bytesSent:D.bytesSent,availableOutgoingBitrate:D.availableOutgoingBitrate,lastPacketReceivedTimestamp:D.lastPacketReceivedTimestamp,lastPacketSentTimestamp:D.lastPacketSentTimestamp,localCandidateId:D.localCandidateId,remoteCandidateId:D.remoteCandidateId,bytesDiscardedOnSend:D.bytesDiscardedOnSend,packetsSent:D.packetsSent,packetsReceived:D.packetsReceived,packetsDiscardedOnSend:D.packetsDiscardedOnSend};F.push(ae),(I.nominated===!0||I.selected===!0)&&(v.candidatePair=ae);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 D=this.overallProducingTransportsStatsMap[s.id];this.processProducingTransportStats(s.id,D,P)}if(s.consuming){const D=this.overallConsumingTransportsStatsMap[s.id];this.processConsumingTransportStats(s.id,D,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),D=this.pausedProducerMap.get(P);if(D){if(D.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const ae=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 De=this.callStatsInstance.producers.get(P);if(((o=De==null?void 0:De.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,ve=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,ve),v.outboundVideoRtp.set(I.id,ve),v.producerStreamMap.get(P).outboundVideoRtpId.push(I.id),this.processOutboundProducerVideoStats(P,ae,ve)}else if(S.mediaType==="audio"||S.kind==="audio"){const x=S,ve=V({retransmittedBytesSent:x.retransmittedBytesSent,retransmittedPacketsSent:x.retransmittedPacketsSent},$);this.audioProducerToStatsMap.set(I.id,ve),v.outboundAudioRtp.set(I.id,ve),v.producerStreamMap.get(P).outboundAudioRtpId.push(I.id),this.processOutboundProducerAudioStats(P,ae,ve)}}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),D=this.pausedConsumerMap.get(P);if(D){if(D.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 ae=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 De={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},De);x.score=Tm({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,ae,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},De);x.score=Sm({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,ae,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,D,ae,De,$,x,ve,Ur,gn,vn,ct;if(I.outboundVideoRtpId.length>0){const qe=[];I.outboundVideoRtpId.forEach(cs=>{qe.push(v.outboundVideoRtp.get(cs))});const Ke=this.getWorkingSimulcastVideoStats(qe);Ke.score=ym({frameWidth:Ke.frameWidth||0,framesPerSecond:Ke.framesPerSecond||0,jitter:((P=Ke.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsSent:(Ke.packetsSent||0)-(((D=this.videoProducerToStatsMap.get(S))==null?void 0:D.packetsSent)||0),packetsLost:(((ae=Ke.remoteData)==null?void 0:ae.packetsLost)||0)-((($=(De=this.videoProducerToStatsMap.get(S))==null?void 0:De.remoteData)==null?void 0:$.packetsLost)||0),framesEncoded:(Ke.framesEncoded||0)-(((x=this.videoProducerToStatsMap.get(S))==null?void 0:x.framesEncoded)||0)}),W.set(S,Ke.score)}else if(I.outboundAudioRtpId.length>0){const qe=v.outboundAudioRtp.get(I.outboundAudioRtpId[0]);qe.score=vm({packetsSent:(qe.packetsSent||0)-(((ve=this.audioProducerToStatsMap.get(S))==null?void 0:ve.packetsSent)||0),packetsLost:(((Ur=qe.remoteData)==null?void 0:Ur.packetsLost)||0)-(((vn=(gn=this.audioProducerToStatsMap.get(S))==null?void 0:gn.remoteData)==null?void 0:vn.packetsLost)||0),jitter:((ct=qe.remoteData)==null?void 0:ct.jitter)||0}),W.set(S,qe.score)}}),F.forEach(I=>{const S=A.find(D=>D.id===I.localCandidateId?(I.localCandidateId=D.id,D):null),P=L.find(D=>D.id===I.remoteCandidateId?(I.remoteCandidateId=D.id,D):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,D)=>{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 qy extends wm{}function Na(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 Ru(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=>{Na(this,e,r,o)}):s}catch(s){Na(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=>{Na(this,t,e,d)}):a}catch(a){Na(this,t,e,a)}return null},i},Ky=(t,e)=>(r,n,i)=>{if(i)return Ru(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,Ru(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 Q=class extends Oa{constructor(t="https://api.testingv3.dyte.in",e="Blink",r=qs.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 Dy({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 wm;break;case"WebKit":this.measurements=new qy;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 Oa,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===Wt.AUDIO&&U.AUDIO_DEVICES_UPDATES||t===Wt.VIDEO&&U.VIDEO_DEVICES_UPDATES||t===Wt.SPEAKER&&U.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:e},timestamp:new Date})}selectedDevice(t,e){this.eventHandler.callEvent({event:t===Wt.AUDIO&&U.SELECTED_MICROHPONE_UPDATE||t===Wt.VIDEO&&U.SELECTED_CAMERA_UPDATE||t===Wt.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===Wt.AUDIO&&U.AUDIO_PLAY_FAILED||t===Wt.VIDEO&&U.VIDEO_PLAY_FAILED,metaData:{deviceType:t},timestamp:new Date})}mediaTrackMuted(t){this.eventHandler.callEvent({event:t===Wt.AUDIO&&U.AUDIO_TRACK_MUTED||t===Wt.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))],Q.prototype,"registerIceServers",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"registerConsumer",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"registerProducer",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendConsumerSharedMediaStateEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"registerProducingTransport",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"registerConsumingTransport",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"deRegisterConsumer",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"deRegisterProducer",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"disconnectConsumingTransport",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"disconnectProducingTransport",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendPreCallTestBeginEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendScreenShareToggleEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendScreenShareRequestedEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendActiveSpeakerEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"devices",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"selectedDevice",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"mediaPermission",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"mediaPlaybackFailed",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"mediaTrackMuted",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"tabChanged",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"browserBackgrounded",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"browserForegrounded",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"legacySwitch",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"getPreCallTestResults",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendCallJoinBeginEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendNetworkQualityTestBeginEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendWebSocketConnectedEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendTransportConnectedEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendAudioToggleEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendVideoToggleEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendParticipantRoleToggleEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"startPingStats",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"stopPingStats",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendPingStatsEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendIVSPlayerRebufferEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendIVSPlayerAudioBlockEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendIVSPlayerPlaybackBlockedEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendIVSPlayerNetworkUnavailableEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendIVSPlayerInitializedEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendIVSPlayerWorkerErrorEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendIVSPlayerErrorEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendIVSPlayerRecoverableErrorEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendIVSPlayerAnalyticsEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendIVSPlayerQualityChanged",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendPlayerLiveLatency",null);Q=Z([Ky(TypeError,(t,e)=>ee.error(e,t))],Q);const zy=Q;class Yy extends wt{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=qs.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 bl.getIPDetails({peerId:r,apiHostnames:h}),this.backend=new zy(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 Yy;B.setMaxListeners(30);function Qy(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:Qy});function Xy(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:Xy});var Je;(function(t){t.GroupCall="GROUP_CALL",t.Webinar="WEBINAR",t.AudioRoom="AUDIO_ROOM",t.Livestream="LIVESTREAM",t.Chat="CHAT"})(Je||(Je={}));var La;(function(t){t.Skip="SKIP",t.OnPrivilegedUserEntry="ON_PRIVILEGED_USER_ENTRY",t.SkipOnAccept="SKIP_ON_ACCEPT"})(La||(La={}));var q;(function(t){t.Allowed="ALLOWED",t.NotAllowed="NOT_ALLOWED",t.CanRequest="CAN_REQUEST"})(q||(q={}));var xa;(function(t){t.Allowed="ALLOWED",t.NotAllowed="NOT_ALLOWED"})(xa||(xa={}));var Pu;(function(t){t.FULL_ACCESS="FULL_ACCESS",t.VIEW_ONLY="VIEW_ONLY"})(Pu||(Pu={}));var Fa;(function(t){t.skip="SKIP",t.onAccept="ON_ACCEPT",t.skipOnPrivilegedUserEntry="SKIP_ON_PRIVILEGED_USER_ENTRY",t.skipOnAccept="SKIP_ON_ACCEPT"})(Fa||(Fa={}));var zi;(function(t){t.none="NONE",t.recorder="RECORDER",t.livestreamer="LIVESTREAMER"})(zi||(zi={}));var Od;(function(t){t.groupCall="GROUP_CALL",t.webinar="WEBINAR",t.audioRoom="AUDIO_ROOM",t.livestream="LIVESTREAM",t.chat="CHAT"})(Od||(Od={}));var Au;(function(t){t.SKIP="skip",t.SKIP_ON_PRIVILEGED_USER_ENTRY="skipOnPrivilegedUserEntry",t.ON_ACCEPT="skipOnAccept",t.SKIP_ON_ACCEPT="skipOnAccept"})(Au||(Au={}));Od.groupCall,Fa.skipOnAccept,zi.none;var Nd={},Zy={get exports(){return Nd},set exports(t){Nd=t}},Ua={},eE={get exports(){return Ua},set exports(t){Ua=t}},Cm=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)}},tE=Cm,hn=Object.prototype.toString;function wl(t){return Array.isArray(t)}function Ld(t){return typeof t=="undefined"}function rE(t){return t!==null&&!Ld(t)&&t.constructor!==null&&!Ld(t.constructor)&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t)}function Im(t){return hn.call(t)==="[object ArrayBuffer]"}function nE(t){return hn.call(t)==="[object FormData]"}function iE(t){var e;return typeof ArrayBuffer!="undefined"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&Im(t.buffer),e}function sE(t){return typeof t=="string"}function oE(t){return typeof t=="number"}function Rm(t){return t!==null&&typeof t=="object"}function Zo(t){if(hn.call(t)!=="[object Object]")return!1;var e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}function aE(t){return hn.call(t)==="[object Date]"}function cE(t){return hn.call(t)==="[object File]"}function dE(t){return hn.call(t)==="[object Blob]"}function Pm(t){return hn.call(t)==="[object Function]"}function lE(t){return Rm(t)&&Pm(t.pipe)}function uE(t){return hn.call(t)==="[object URLSearchParams]"}function hE(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function pE(){return typeof navigator!="undefined"&&(navigator.product==="ReactNative"||navigator.product==="NativeScript"||navigator.product==="NS")?!1:typeof window!="undefined"&&typeof document!="undefined"}function Cl(t,e){if(!(t===null||typeof t=="undefined"))if(typeof t!="object"&&(t=[t]),wl(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 xd(){var t={};function e(i,s){Zo(t[s])&&Zo(i)?t[s]=xd(t[s],i):Zo(i)?t[s]=xd({},i):wl(i)?t[s]=i.slice():t[s]=i}for(var r=0,n=arguments.length;r<n;r++)Cl(arguments[r],e);return t}function mE(t,e,r){return Cl(e,function(n,i){r&&typeof n=="function"?t[i]=tE(n,r):t[i]=n}),t}function fE(t){return t.charCodeAt(0)===65279&&(t=t.slice(1)),t}var Ct={isArray:wl,isArrayBuffer:Im,isBuffer:rE,isFormData:nE,isArrayBufferView:iE,isString:sE,isNumber:oE,isObject:Rm,isPlainObject:Zo,isUndefined:Ld,isDate:aE,isFile:cE,isBlob:dE,isFunction:Pm,isStream:lE,isURLSearchParams:uE,isStandardBrowserEnv:pE,forEach:Cl,merge:xd,extend:mE,trim:hE,stripBOM:fE},gi=Ct;function Mu(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var Am=function(t,e,r){if(!e)return t;var n;if(r)n=r(e);else if(gi.isURLSearchParams(e))n=e.toString();else{var i=[];gi.forEach(e,function(o,a){o===null||typeof o=="undefined"||(gi.isArray(o)?a=a+"[]":o=[o],gi.forEach(o,function(d){gi.isDate(d)?d=d.toISOString():gi.isObject(d)&&(d=JSON.stringify(d)),i.push(Mu(a)+"="+Mu(d))}))}),n=i.join("&")}if(n){var s=t.indexOf("#");s!==-1&&(t=t.slice(0,s)),t+=(t.indexOf("?")===-1?"?":"&")+n}return t},gE=Ct;function mc(){this.handlers=[]}mc.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};mc.prototype.eject=function(t){this.handlers[t]&&(this.handlers[t]=null)};mc.prototype.forEach=function(t){gE.forEach(this.handlers,function(e){e!==null&&t(e)})};var vE=mc,yE=Ct,EE=function(t,e){yE.forEach(t,function(r,n){n!==e&&n.toUpperCase()===e.toUpperCase()&&(t[e]=r,delete t[n])})},Mm=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},Wc,Du;function Dm(){if(Du)return Wc;Du=1;var t=Mm;return Wc=function(e,r,n,i,s){var o=new Error(e);return t(o,r,n,i,s)},Wc}var $c,Ou;function SE(){if(Ou)return $c;Ou=1;var t=Dm();return $c=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))},$c}var Gc,Nu;function TE(){if(Nu)return Gc;Nu=1;var t=Ct;return Gc=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(){}}}(),Gc}var Lu,xu;function kE(){return xu||(xu=1,Lu=function(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}),Lu}var Fu,Uu;function _E(){return Uu||(Uu=1,Fu=function(t,e){return e?t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):t}),Fu}var Jc,Vu;function bE(){if(Vu)return Jc;Vu=1;var t=kE(),e=_E();return Jc=function(r,n){return r&&!t(n)?e(r,n):n},Jc}var qc,Bu;function wE(){if(Bu)return qc;Bu=1;var t=Ct,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 qc=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},qc}var Kc,ju;function CE(){if(ju)return Kc;ju=1;var t=Ct;return Kc=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}}(),Kc}var zc,Hu;function fc(){if(Hu)return zc;Hu=1;function t(e){this.message=e}return t.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},t.prototype.__CANCEL__=!0,zc=t,zc}var Yc,Wu;function IE(){if(Wu)return Yc;Wu=1;var t=Ct,e=SE(),r=TE(),n=Am,i=bE(),s=wE(),o=CE(),a=Dm(),d=gc(),h=fc();return Yc=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 D="getAllResponseHeaders"in F?s(F.getAllResponseHeaders()):null,ae=!R||R==="text"||R==="json"?F.responseText:F.response,De={data:ae,status:F.status,statusText:F.statusText,headers:D,config:p,request:F};e(function($){f($),L()},function($){g($),L()},De),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 D=p.timeout?"timeout of "+p.timeout+"ms exceeded":"timeout exceeded",ae=p.transitional||d.transitional;p.timeoutErrorMessage&&(D=p.timeoutErrorMessage),g(a(D,p,ae.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(D,ae){typeof E=="undefined"&&ae.toLowerCase()==="content-type"?delete v[ae]:F.setRequestHeader(ae,D)}),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(D){F&&(g(!D||D&&D.type?new h("canceled"):D),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)})},Yc}var Qc,$u;function gc(){if($u)return Qc;$u=1;var t=Ct,e=EE,r=Mm,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=IE()),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)}),Qc=a,Qc}var RE=Ct,PE=gc(),AE=function(t,e,r){var n=this||PE;return RE.forEach(r,function(i){t=i.call(n,t,e)}),t},Gu,Ju;function Om(){return Ju||(Ju=1,Gu=function(t){return!!(t&&t.__CANCEL__)}),Gu}var qu=Ct,Xc=AE,ME=Om(),DE=gc(),OE=fc();function Zc(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new OE("canceled")}var NE=function(t){Zc(t),t.headers=t.headers||{},t.data=Xc.call(t,t.data,t.headers,t.transformRequest),t.headers=qu.merge(t.headers.common||{},t.headers[t.method]||{},t.headers),qu.forEach(["delete","get","head","post","put","patch","common"],function(r){delete t.headers[r]});var e=t.adapter||DE.adapter;return e(t).then(function(r){return Zc(t),r.data=Xc.call(t,r.data,r.headers,t.transformResponse),r},function(r){return ME(r)||(Zc(t),r&&r.response&&(r.response.data=Xc.call(t,r.response.data,r.response.headers,t.transformResponse))),Promise.reject(r)})},At=Ct,Nm=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},Ku,zu;function Lm(){return zu||(zu=1,Ku={version:"0.25.0"}),Ku}var LE=Lm().version,Il={};["object","boolean","number","function","string","symbol"].forEach(function(t,e){Il[t]=function(r){return typeof r===t||"a"+(e<1?"n ":" ")+t}});var Yu={};Il.transitional=function(t,e,r){function n(i,s){return"[Axios v"+LE+"] 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&&!Yu[s]&&(Yu[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 xE(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 FE={assertOptions:xE,validators:Il},xm=Ct,UE=Am,Qu=vE,Xu=NE,vc=Nm,Fm=FE,vi=Fm.validators;function io(t){this.defaults=t,this.interceptors={request:new Qu,response:new Qu}}io.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=vc(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&&Fm.assertOptions(r,{silentJSONParsing:vi.transitional(vi.boolean),forcedJSONParsing:vi.transitional(vi.boolean),clarifyTimeoutError:vi.transitional(vi.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=[Xu,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=Xu(d)}catch(f){return Promise.reject(f)}for(;s.length;)o=o.then(s.shift(),s.shift());return o};io.prototype.getUri=function(t){if(!t.url)throw new Error("Provided config url is not valid");return t=vc(this.defaults,t),UE(t.url,t.params,t.paramsSerializer).replace(/^\?/,"")};xm.forEach(["delete","get","head","options"],function(t){io.prototype[t]=function(e,r){return this.request(vc(r||{},{method:t,url:e,data:(r||{}).data}))}});xm.forEach(["post","put","patch"],function(t){io.prototype[t]=function(e,r,n){return this.request(vc(n||{},{method:t,url:e,data:r}))}});var VE=io,ed,Zu;function BE(){if(Zu)return ed;Zu=1;var t=fc();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}},ed=e,ed}var eh,th;function jE(){return th||(th=1,eh=function(t){return function(e){return t.apply(null,e)}}),eh}var td,rh;function HE(){if(rh)return td;rh=1;var t=Ct;return td=function(e){return t.isObject(e)&&e.isAxiosError===!0},td}var nh=Ct,WE=Cm,ea=VE,$E=Nm,GE=gc();function Um(t){var e=new ea(t),r=WE(ea.prototype.request,e);return nh.extend(r,ea.prototype,e),nh.extend(r,e),r.create=function(n){return Um($E(t,n))},r}var mr=Um(GE);mr.Axios=ea;mr.Cancel=fc();mr.CancelToken=BE();mr.isCancel=Om();mr.VERSION=Lm().version;mr.all=function(t){return Promise.all(t)};mr.spread=jE();mr.isAxiosError=HE();eE.exports=mr;Ua.default=mr;(function(t){t.exports=Ua})(Zy);const Va=gy(Nd);let Vm="hXgU8Wc8pwuGNq9ms5q9Hh";var ih;typeof process!="undefined"&&(ih=process==null?void 0:process.env)!=null&&ih.FLAGSMITH_ENVIRONMENT_KEY&&(Vm={}.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 qE{constructor(e=Vm){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 Va.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{}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 qE,Bm=[-2,-1,0,1,2],KE=[0,1,2,3,4];function zE(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 YE=(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)]},QE=(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]},XE=(t,e,r)=>{const n=i=>i.toString(16).padStart(2,"0");return`#${n(t)}${n(e)}${n(r)}`},jm=(t,e=Bm,r=.4)=>{const n=[],[i,s,o]=zE(t),[a,d,h]=QE(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]=YE(a,d,L/100);n.push(XE(F,W,H))}return n},sh={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"}},ZE=t=>{const[e,r,n,i,s]=jm(t,Bm);return{300:e,400:r,500:n,600:i,700:s}},eS=t=>{if(t==="#FFFFFF")return sh.light.background;if(t==="#000000")return sh.dark.background;const[e,r,n,i,s]=jm(t,KE);return{1e3:e,900:r,800:n,700:i,600:s}};function tS(){this.__data__=[],this.size=0}function yc(t,e){return t===e||t!==t&&e!==e}function Ec(t,e){for(var r=t.length;r--;)if(yc(t[r][0],e))return r;return-1}var rS=Array.prototype,nS=rS.splice;function iS(t){var e=this.__data__,r=Ec(e,t);if(r<0)return!1;var n=e.length-1;return r==n?e.pop():nS.call(e,r,1),--this.size,!0}function sS(t){var e=this.__data__,r=Ec(e,t);return r<0?void 0:e[r][1]}function oS(t){return Ec(this.__data__,t)>-1}function aS(t,e){var r=this.__data__,n=Ec(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}function xr(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])}}xr.prototype.clear=tS;xr.prototype.delete=iS;xr.prototype.get=sS;xr.prototype.has=oS;xr.prototype.set=aS;function cS(){this.__data__=new xr,this.size=0}function dS(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r}function lS(t){return this.__data__.get(t)}function uS(t){return this.__data__.has(t)}var hS=typeof global=="object"&&global&&global.Object===Object&&global;const Hm=hS;var pS=typeof self=="object"&&self&&self.Object===Object&&self,mS=Hm||pS||Function("return this")();const tr=mS;var fS=tr.Symbol;const Yi=fS;var Wm=Object.prototype,gS=Wm.hasOwnProperty,vS=Wm.toString,ls=Yi?Yi.toStringTag:void 0;function yS(t){var e=gS.call(t,ls),r=t[ls];try{t[ls]=void 0;var n=!0}catch{}var i=vS.call(t);return n&&(e?t[ls]=r:delete t[ls]),i}var ES=Object.prototype,SS=ES.toString;function TS(t){return SS.call(t)}var kS="[object Null]",_S="[object Undefined]",oh=Yi?Yi.toStringTag:void 0;function ai(t){return t==null?t===void 0?_S:kS:oh&&oh in Object(t)?yS(t):TS(t)}function er(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var bS="[object AsyncFunction]",wS="[object Function]",CS="[object GeneratorFunction]",IS="[object Proxy]";function Rl(t){if(!er(t))return!1;var e=ai(t);return e==wS||e==CS||e==bS||e==IS}var RS=tr["__core-js_shared__"];const rd=RS;var ah=function(){var t=/[^.]+$/.exec(rd&&rd.keys&&rd.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();function PS(t){return!!ah&&ah in t}var AS=Function.prototype,MS=AS.toString;function ci(t){if(t!=null){try{return MS.call(t)}catch{}try{return t+""}catch{}}return""}var DS=/[\\^$.*+?()[\]{}|]/g,OS=/^\[object .+?Constructor\]$/,NS=Function.prototype,LS=Object.prototype,xS=NS.toString,FS=LS.hasOwnProperty,US=RegExp("^"+xS.call(FS).replace(DS,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function VS(t){if(!er(t)||PS(t))return!1;var e=Rl(t)?US:OS;return e.test(ci(t))}function BS(t,e){return t==null?void 0:t[e]}function di(t,e){var r=BS(t,e);return VS(r)?r:void 0}var jS=di(tr,"Map");const Zs=jS;var HS=di(Object,"create");const eo=HS;function WS(){this.__data__=eo?eo(null):{},this.size=0}function $S(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var GS="__lodash_hash_undefined__",JS=Object.prototype,qS=JS.hasOwnProperty;function KS(t){var e=this.__data__;if(eo){var r=e[t];return r===GS?void 0:r}return qS.call(e,t)?e[t]:void 0}var zS=Object.prototype,YS=zS.hasOwnProperty;function QS(t){var e=this.__data__;return eo?e[t]!==void 0:YS.call(e,t)}var XS="__lodash_hash_undefined__";function ZS(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=eo&&e===void 0?XS:e,this}function ei(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])}}ei.prototype.clear=WS;ei.prototype.delete=$S;ei.prototype.get=KS;ei.prototype.has=QS;ei.prototype.set=ZS;function eT(){this.size=0,this.__data__={hash:new ei,map:new(Zs||xr),string:new ei}}function tT(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function Sc(t,e){var r=t.__data__;return tT(e)?r[typeof e=="string"?"string":"hash"]:r.map}function rT(t){var e=Sc(this,t).delete(t);return this.size-=e?1:0,e}function nT(t){return Sc(this,t).get(t)}function iT(t){return Sc(this,t).has(t)}function sT(t,e){var r=Sc(this,t),n=r.size;return r.set(t,e),this.size+=r.size==n?0:1,this}function rs(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])}}rs.prototype.clear=eT;rs.prototype.delete=rT;rs.prototype.get=nT;rs.prototype.has=iT;rs.prototype.set=sT;var oT=200;function aT(t,e){var r=this.__data__;if(r instanceof xr){var n=r.__data__;if(!Zs||n.length<oT-1)return n.push([t,e]),this.size=++r.size,this;r=this.__data__=new rs(n)}return r.set(t,e),this.size=r.size,this}function li(t){var e=this.__data__=new xr(t);this.size=e.size}li.prototype.clear=cS;li.prototype.delete=dS;li.prototype.get=lS;li.prototype.has=uS;li.prototype.set=aT;function cT(t,e){for(var r=-1,n=t==null?0:t.length;++r<n&&e(t[r],r,t)!==!1;);return t}var dT=function(){try{var t=di(Object,"defineProperty");return t({},"",{}),t}catch{}}();const Ba=dT;function Pl(t,e,r){e=="__proto__"&&Ba?Ba(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}var lT=Object.prototype,uT=lT.hasOwnProperty;function $m(t,e,r){var n=t[e];(!(uT.call(t,e)&&yc(n,r))||r===void 0&&!(e in t))&&Pl(t,e,r)}function so(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?Pl(r,a,d):$m(r,a,d)}return r}function hT(t,e){for(var r=-1,n=Array(t);++r<t;)n[r]=e(r);return n}function pn(t){return t!=null&&typeof t=="object"}var pT="[object Arguments]";function ch(t){return pn(t)&&ai(t)==pT}var Gm=Object.prototype,mT=Gm.hasOwnProperty,fT=Gm.propertyIsEnumerable,gT=ch(function(){return arguments}())?ch:function(t){return pn(t)&&mT.call(t,"callee")&&!fT.call(t,"callee")};const ja=gT;var vT=Array.isArray;const Qi=vT;function yT(){return!1}var Jm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,dh=Jm&&typeof module=="object"&&module&&!module.nodeType&&module,ET=dh&&dh.exports===Jm,lh=ET?tr.Buffer:void 0,ST=lh?lh.isBuffer:void 0,TT=ST||yT;const Tc=TT;var kT=9007199254740991,_T=/^(?:0|[1-9]\d*)$/;function qm(t,e){var r=typeof t;return e=e==null?kT:e,!!e&&(r=="number"||r!="symbol"&&_T.test(t))&&t>-1&&t%1==0&&t<e}var bT=9007199254740991;function Km(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=bT}var wT="[object Arguments]",CT="[object Array]",IT="[object Boolean]",RT="[object Date]",PT="[object Error]",AT="[object Function]",MT="[object Map]",DT="[object Number]",OT="[object Object]",NT="[object RegExp]",LT="[object Set]",xT="[object String]",FT="[object WeakMap]",UT="[object ArrayBuffer]",VT="[object DataView]",BT="[object Float32Array]",jT="[object Float64Array]",HT="[object Int8Array]",WT="[object Int16Array]",$T="[object Int32Array]",GT="[object Uint8Array]",JT="[object Uint8ClampedArray]",qT="[object Uint16Array]",KT="[object Uint32Array]",Pe={};Pe[BT]=Pe[jT]=Pe[HT]=Pe[WT]=Pe[$T]=Pe[GT]=Pe[JT]=Pe[qT]=Pe[KT]=!0;Pe[wT]=Pe[CT]=Pe[UT]=Pe[IT]=Pe[VT]=Pe[RT]=Pe[PT]=Pe[AT]=Pe[MT]=Pe[DT]=Pe[OT]=Pe[NT]=Pe[LT]=Pe[xT]=Pe[FT]=!1;function zT(t){return pn(t)&&Km(t.length)&&!!Pe[ai(t)]}function Al(t){return function(e){return t(e)}}var zm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ks=zm&&typeof module=="object"&&module&&!module.nodeType&&module,YT=Ks&&Ks.exports===zm,nd=YT&&Hm.process,QT=function(){try{var t=Ks&&Ks.require&&Ks.require("util").types;return t||nd&&nd.binding&&nd.binding("util")}catch{}}();const Xi=QT;var uh=Xi&&Xi.isTypedArray,XT=uh?Al(uh):zT;const Ml=XT;var ZT=Object.prototype,ek=ZT.hasOwnProperty;function Ym(t,e){var r=Qi(t),n=!r&&ja(t),i=!r&&!n&&Tc(t),s=!r&&!n&&!i&&Ml(t),o=r||n||i||s,a=o?hT(t.length,String):[],d=a.length;for(var h in t)(e||ek.call(t,h))&&!(o&&(h=="length"||i&&(h=="offset"||h=="parent")||s&&(h=="buffer"||h=="byteLength"||h=="byteOffset")||qm(h,d)))&&a.push(h);return a}var tk=Object.prototype;function kc(t){var e=t&&t.constructor,r=typeof e=="function"&&e.prototype||tk;return t===r}function Qm(t,e){return function(r){return t(e(r))}}var rk=Qm(Object.keys,Object);const nk=rk;var ik=Object.prototype,sk=ik.hasOwnProperty;function Xm(t){if(!kc(t))return nk(t);var e=[];for(var r in Object(t))sk.call(t,r)&&r!="constructor"&&e.push(r);return e}function oo(t){return t!=null&&Km(t.length)&&!Rl(t)}function Dl(t){return oo(t)?Ym(t):Xm(t)}function ok(t,e){return t&&so(e,Dl(e),t)}function ak(t){var e=[];if(t!=null)for(var r in Object(t))e.push(r);return e}var ck=Object.prototype,dk=ck.hasOwnProperty;function lk(t){if(!er(t))return ak(t);var e=kc(t),r=[];for(var n in t)n=="constructor"&&(e||!dk.call(t,n))||r.push(n);return r}function ao(t){return oo(t)?Ym(t,!0):lk(t)}function uk(t,e){return t&&so(e,ao(e),t)}var Zm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,hh=Zm&&typeof module=="object"&&module&&!module.nodeType&&module,hk=hh&&hh.exports===Zm,ph=hk?tr.Buffer:void 0,mh=ph?ph.allocUnsafe:void 0;function ef(t,e){if(e)return t.slice();var r=t.length,n=mh?mh(r):new t.constructor(r);return t.copy(n),n}function tf(t,e){var r=-1,n=t.length;for(e||(e=Array(n));++r<n;)e[r]=t[r];return e}function pk(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 rf(){return[]}var mk=Object.prototype,fk=mk.propertyIsEnumerable,fh=Object.getOwnPropertySymbols,gk=fh?function(t){return t==null?[]:(t=Object(t),pk(fh(t),function(e){return fk.call(t,e)}))}:rf;const Ol=gk;function vk(t,e){return so(t,Ol(t),e)}function nf(t,e){for(var r=-1,n=e.length,i=t.length;++r<n;)t[i+r]=e[r];return t}var yk=Qm(Object.getPrototypeOf,Object);const Nl=yk;var Ek=Object.getOwnPropertySymbols,Sk=Ek?function(t){for(var e=[];t;)nf(e,Ol(t)),t=Nl(t);return e}:rf;const sf=Sk;function Tk(t,e){return so(t,sf(t),e)}function of(t,e,r){var n=e(t);return Qi(t)?n:nf(n,r(t))}function kk(t){return of(t,Dl,Ol)}function _k(t){return of(t,ao,sf)}var bk=di(tr,"DataView");const Fd=bk;var wk=di(tr,"Promise");const Ud=wk;var Ck=di(tr,"Set");const Vd=Ck;var Ik=di(tr,"WeakMap");const Bd=Ik;var gh="[object Map]",Rk="[object Object]",vh="[object Promise]",yh="[object Set]",Eh="[object WeakMap]",Sh="[object DataView]",Pk=ci(Fd),Ak=ci(Zs),Mk=ci(Ud),Dk=ci(Vd),Ok=ci(Bd),Nn=ai;(Fd&&Nn(new Fd(new ArrayBuffer(1)))!=Sh||Zs&&Nn(new Zs)!=gh||Ud&&Nn(Ud.resolve())!=vh||Vd&&Nn(new Vd)!=yh||Bd&&Nn(new Bd)!=Eh)&&(Nn=function(t){var e=ai(t),r=e==Rk?t.constructor:void 0,n=r?ci(r):"";if(n)switch(n){case Pk:return Sh;case Ak:return gh;case Mk:return vh;case Dk:return yh;case Ok:return Eh}return e});const _c=Nn;var Nk=Object.prototype,Lk=Nk.hasOwnProperty;function xk(t){var e=t.length,r=new t.constructor(e);return e&&typeof t[0]=="string"&&Lk.call(t,"index")&&(r.index=t.index,r.input=t.input),r}var Fk=tr.Uint8Array;const Th=Fk;function Ll(t){var e=new t.constructor(t.byteLength);return new Th(e).set(new Th(t)),e}function Uk(t,e){var r=e?Ll(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.byteLength)}var Vk=/\w*$/;function Bk(t){var e=new t.constructor(t.source,Vk.exec(t));return e.lastIndex=t.lastIndex,e}var kh=Yi?Yi.prototype:void 0,_h=kh?kh.valueOf:void 0;function jk(t){return _h?Object(_h.call(t)):{}}function af(t,e){var r=e?Ll(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.length)}var Hk="[object Boolean]",Wk="[object Date]",$k="[object Map]",Gk="[object Number]",Jk="[object RegExp]",qk="[object Set]",Kk="[object String]",zk="[object Symbol]",Yk="[object ArrayBuffer]",Qk="[object DataView]",Xk="[object Float32Array]",Zk="[object Float64Array]",e_="[object Int8Array]",t_="[object Int16Array]",r_="[object Int32Array]",n_="[object Uint8Array]",i_="[object Uint8ClampedArray]",s_="[object Uint16Array]",o_="[object Uint32Array]";function a_(t,e,r){var n=t.constructor;switch(e){case Yk:return Ll(t);case Hk:case Wk:return new n(+t);case Qk:return Uk(t,r);case Xk:case Zk:case e_:case t_:case r_:case n_:case i_:case s_:case o_:return af(t,r);case $k:return new n;case Gk:case Kk:return new n(t);case Jk:return Bk(t);case qk:return new n;case zk:return jk(t)}}var bh=Object.create,c_=function(){function t(){}return function(e){if(!er(e))return{};if(bh)return bh(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();const d_=c_;function cf(t){return typeof t.constructor=="function"&&!kc(t)?d_(Nl(t)):{}}var l_="[object Map]";function u_(t){return pn(t)&&_c(t)==l_}var wh=Xi&&Xi.isMap,h_=wh?Al(wh):u_;const p_=h_;var m_="[object Set]";function f_(t){return pn(t)&&_c(t)==m_}var Ch=Xi&&Xi.isSet,g_=Ch?Al(Ch):f_;const v_=g_;var y_=1,E_=2,S_=4,df="[object Arguments]",T_="[object Array]",k_="[object Boolean]",__="[object Date]",b_="[object Error]",lf="[object Function]",w_="[object GeneratorFunction]",C_="[object Map]",I_="[object Number]",uf="[object Object]",R_="[object RegExp]",P_="[object Set]",A_="[object String]",M_="[object Symbol]",D_="[object WeakMap]",O_="[object ArrayBuffer]",N_="[object DataView]",L_="[object Float32Array]",x_="[object Float64Array]",F_="[object Int8Array]",U_="[object Int16Array]",V_="[object Int32Array]",B_="[object Uint8Array]",j_="[object Uint8ClampedArray]",H_="[object Uint16Array]",W_="[object Uint32Array]",be={};be[df]=be[T_]=be[O_]=be[N_]=be[k_]=be[__]=be[L_]=be[x_]=be[F_]=be[U_]=be[V_]=be[C_]=be[I_]=be[uf]=be[R_]=be[P_]=be[A_]=be[M_]=be[B_]=be[j_]=be[H_]=be[W_]=!0;be[b_]=be[lf]=be[D_]=!1;function ta(t,e,r,n,i,s){var o,a=e&y_,d=e&E_,h=e&S_;if(r&&(o=i?r(t,n,i,s):r(t)),o!==void 0)return o;if(!er(t))return t;var p=Qi(t);if(p){if(o=xk(t),!a)return tf(t,o)}else{var f=_c(t),g=f==lf||f==w_;if(Tc(t))return ef(t,a);if(f==uf||f==df||g&&!i){if(o=d||g?{}:cf(t),!a)return d?Tk(t,uk(o,t)):vk(t,ok(o,t))}else{if(!be[f])return i?t:{};o=a_(t,f,a)}}s||(s=new li);var E=s.get(t);if(E)return E;s.set(t,o),v_(t)?t.forEach(function(A){o.add(ta(A,e,r,A,t,s))}):p_(t)&&t.forEach(function(A,L){o.set(L,ta(A,e,r,L,t,s))});var v=h?d?_k:kk:d?ao:Dl,R=p?void 0:v(t);return cT(R||t,function(A,L){R&&(L=A,A=t[L]),$m(o,L,ta(A,e,r,L,t,s))}),o}var $_=1,G_=4;function xl(t){return ta(t,$_|G_)}var J_="[object Symbol]";function q_(t){return typeof t=="symbol"||pn(t)&&ai(t)==J_}const K_={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:ZE("#2160FD"),background:eS("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function hf(){return xl(K_)}const z_={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:La.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:xa.Allowed},audio:{can_produce:q.Allowed},screenshare:{can_produce:q.Allowed,can_consume:xa.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:zi.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:hf(),config_diff:{}},config:{view_type:Je.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 Y_(){return xl(z_)}zi.none,Fa.skip;const Q_={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:La.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:zi.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:hf(),config_diff:{}},config:{view_type:Je.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 Fl(){return xl(Q_)}var X_=/\s/;function Z_(t){for(var e=t.length;e--&&X_.test(t.charAt(e)););return e}var eb=/^\s+/;function tb(t){return t&&t.slice(0,Z_(t)+1).replace(eb,"")}var Ih=0/0,rb=/^[-+]0x[0-9a-f]+$/i,nb=/^0b[01]+$/i,ib=/^0o[0-7]+$/i,sb=parseInt;function Rh(t){if(typeof t=="number")return t;if(q_(t))return Ih;if(er(t)){var e=typeof t.valueOf=="function"?t.valueOf():t;t=er(e)?e+"":e}if(typeof t!="string")return t===0?t:+t;t=tb(t);var r=nb.test(t);return r||ib.test(t)?sb(t.slice(2),r?2:8):rb.test(t)?Ih:+t}function pf(t){return t}function ob(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 ab=800,cb=16,db=Date.now;function lb(t){var e=0,r=0;return function(){var n=db(),i=cb-(n-r);if(r=n,i>0){if(++e>=ab)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function ub(t){return function(){return t}}var hb=Ba?function(t,e){return Ba(t,"toString",{configurable:!0,enumerable:!1,value:ub(e),writable:!0})}:pf;const pb=hb;var mb=lb(pb);const fb=mb;var Ph=Math.max;function gb(t,e,r){return e=Ph(e===void 0?t.length-1:e,0),function(){for(var n=arguments,i=-1,s=Ph(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),ob(t,this,a)}}function vb(t,e){return fb(gb(t,e,pf),t+"")}function yb(t,e,r){if(!er(r))return!1;var n=typeof e;return(n=="number"?oo(r)&&qm(e,r.length):n=="string"&&e in r)?yc(r[e],t):!1}function Eb(t){return vb(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&&yb(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 Sb="[object Object]",Tb=Function.prototype,kb=Object.prototype,mf=Tb.toString,_b=kb.hasOwnProperty,bb=mf.call(Object);function wb(t){if(!pn(t)||ai(t)!=Sb)return!1;var e=Nl(t);if(e===null)return!0;var r=_b.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&mf.call(r)==bb}function Cb(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 Ib=Cb();const Rb=Ib;var Pb=function(){return tr.Date.now()};const id=Pb;var Ab="Expected a function",Mb=Math.max,Db=Math.min;function ur(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(Ab);e=Rh(e)||0,er(r)&&(p=!!r.leading,f="maxWait"in r,s=f?Mb(Rh(r.maxWait)||0,e):s,g="trailing"in r?!!r.trailing:g);function E(S){var P=n,D=i;return n=i=void 0,h=S,o=t.apply(D,P),o}function v(S){return h=S,a=setTimeout(L,e),p?E(S):o}function R(S){var P=S-d,D=S-h,ae=e-P;return f?Db(ae,s-D):ae}function A(S){var P=S-d,D=S-h;return d===void 0||P>=e||P<0||f&&D>=s}function L(){var S=id();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(id())}function I(){var S=id(),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 jd(t,e,r){(r!==void 0&&!yc(t[e],r)||r===void 0&&!(e in t))&&Pl(t,e,r)}function Ob(t){return pn(t)&&oo(t)}function Hd(t,e){if(!(e==="constructor"&&typeof t[e]=="function")&&e!="__proto__")return t[e]}function Nb(t){return so(t,ao(t))}function Lb(t,e,r,n,i,s,o){var a=Hd(t,r),d=Hd(e,r),h=o.get(d);if(h){jd(t,r,h);return}var p=s?s(a,d,r+"",t,e,o):void 0,f=p===void 0;if(f){var g=Qi(d),E=!g&&Tc(d),v=!g&&!E&&Ml(d);p=d,g||E||v?Qi(a)?p=a:Ob(a)?p=tf(a):E?(f=!1,p=ef(d,!0)):v?(f=!1,p=af(d,!0)):p=[]:wb(d)||ja(d)?(p=a,ja(a)?p=Nb(a):(!er(a)||Rl(a))&&(p=cf(d))):f=!1}f&&(o.set(d,p),i(p,d,n,s,o),o.delete(d)),jd(t,r,p)}function ff(t,e,r,n,i){t!==e&&Rb(e,function(s,o){if(i||(i=new li),er(s))Lb(t,e,o,r,ff,n,i);else{var a=n?n(Hd(t,o),s,o+"",t,e,i):void 0;a===void 0&&(a=s),jd(t,o,a)}},ao)}var xb="[object Map]",Fb="[object Set]",Ub=Object.prototype,Vb=Ub.hasOwnProperty;function Bb(t){if(t==null)return!0;if(oo(t)&&(Qi(t)||typeof t=="string"||typeof t.splice=="function"||Tc(t)||Ml(t)||ja(t)))return!t.length;var e=_c(t);if(e==xb||e==Fb)return!t.size;if(kc(t))return!Xm(t).length;for(var r in t)if(Vb.call(t,r))return!1;return!0}var jb=Eb(function(t,e,r){ff(t,e,r)});const zr=jb;var Wd=(t=>(t.PARTICIPANT="PARTICIPANT",t.PEER="PEER",t.CLIENT="CLIENT",t))(Wd||{});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 gf(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 Hb(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 vf(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"?vf(t[n],s,r):["number","string","boolean"].includes(typeof t[n])&&(r[s]=t[n])}),r}function Ah(t,e,r={},n=""){const i={};try{const s=JSON.stringify(r),o=JSON.parse(s),a=vf(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 gf(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 to="chrome",yf="opera",Ef="firefox",Sf="iexplorer",Tf="safari",kf="nwjs",_f="electron",bf="react-native",Ul="unknown",Ha={Chrome:to,Chromium:to,Opera:yf,Firefox:Ef,"Internet Explorer":Sf,Safari:Tf};function Wb(){const{userAgent:t}=navigator,e={name:Ul,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=to,e.version=r)}else e.name=to,e.version=t.match(/Chrome\/([\d.]+)/)[1];return e}function $b(){const{userAgent:t}=navigator;if(t.match(/Electron/)){const e=t.match(/Electron\/([\d.]+)/)[1];return{name:_f,version:e}}return null}function Gb(){const{userAgent:t}=navigator;if(t.match(/JitsiMeetNW/)){const e=t.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:kf,version:e}}}function Jb(){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:bf,version:e}}function qb(t){let e;const r=[Jb,$b,Gb];for(let i=0;i<r.length;i+=1)if(e=r[i](),e)return e;const n=t.getBrowserName();return n in Ha?{name:Ha[n],version:t.getBrowserVersion()}:(e=Wb(),e||{name:Ul,version:void 0})}class Kb{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=Wp.getParser(navigator.userAgent),typeof e=="undefined"){const i=qb(this._bowser);r=i.name,n=i.version}else e.name in Ha?(r=Ha[e.name],n=e.version):(r=Ul,n=void 0);this._name=r,this._version=n}getName(){return this._name}isChrome(){return this._name===to}isOpera(){return this._name===yf}isFirefox(){return this._name===Ef}isIExplorer(){return this._name===Sf}isSafari(){return this._name===Tf}isNWJS(){return this._name===kf}isElectron(){return this._name===_f}isReactNative(){return this._name===bf||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 zb extends Kb{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{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 zb,$d={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},us={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"},Yb={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 Mh(t,e){const r=t.getValue("overrides");return r&&r[e]?r[e]:!1}function Qb({baseURI:t}){return t!=null&&t.includes("preprod.dyte")?qs.PREPROD:t!=null&&t.includes("devel.dyte")?qs.DEVEL:qs.PROD}function $i({servicePrefix:t,baseURI:e}){return`${t}.${e}`}function wf(t){const e=t.getValue("baseURI");return{location:$i({servicePrefix:"location",baseURI:e}),locationLegacy:$i({servicePrefix:"location-legacy",baseURI:e}),daCollector:$i({servicePrefix:"da-collector",baseURI:e})}}function Xb(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 Zb{constructor(){m(this,"contexts",new Map)}createContext(e,r){return this.contexts.has(e)?this.contexts.get(e):(this.contexts.set(e,Xb(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 zs=new Zb,me=class{static get logsEndpoint(){const t=zs.getContext(me.meetingMetadata.peerId);return`https://${$i({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=si().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=zs.getContext(me.meetingMetadata.peerId);if(gf(i)&&(Bb(r)?console[t]("DyteInternalLogs:: ",t,e):console[t]("DyteInternalLogs:: ",t,e,r)),!!Hb(t))try{const s=Ah(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=zs.getContext(me.meetingMetadata.peerId);Va.post(me.logsEndpoint,{meetingMetadata:Ah(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 ew=()=>{!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")}))},tw={"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"},na={"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(na).forEach(t=>{na[t]=`{${tw[t.slice(0,2)]}} ${na[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}]: ${na[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{}}}function So(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 Dh(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){So(this,e,r,o)}}),s&&(t.set=function(o){try{return s.apply(this,[o])}catch(a){So(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=>{So(this,e,r,o)}):s}catch(s){So(this,e,r,s)}},t}function rw(t,e){return(r,n,i)=>{if(i)return Dh(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,Dh(o,t,e))}}}const ut=t=>rw(Error,t);function nw(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 Yr,Qr;const Cf=class extends wt.EventEmitter{constructor(){super(),_(this,Yr,void 0),_(this,Qr,void 0),m(this,"asyncPromiseTimeout"),T(this,Yr,new Map),T(this,Qr,new Map),this.asyncPromiseTimeout=8e3}emitAsync(t,...e){return u(this,null,function*(){c(this,Yr).set(t,[]);const r=c(this,Qr).get(t).map(()=>new Promise(n=>{c(this,Yr).get(t).push(n)}));fy(Cf.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,Yr).delete(t)})}onAsync(t,e){const r=c(this,Yr),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,Qr).get(t)||c(this,Qr).set(t,[]),c(this,Qr).get(t).push(n),super.on(t,n)}reset(){T(this,Yr,new Map),T(this,Qr,new Map),super.removeAllListeners()}};let iw=Cf;Yr=new WeakMap,Qr=new WeakMap;const w=new iw;function sw(){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 Nt;(function(t){t[t.PUBLISHER=0]="PUBLISHER",t[t.SUBSCRIBER=1]="SUBSCRIBER"})(Nt||(Nt={}));var bt;(function(t){t[t.AUDIO=0]="AUDIO",t[t.VIDEO=1]="VIDEO"})(bt||(bt={}));class ow extends k{constructor(){super("media.Codec",[])}}new ow;class aw extends k{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new aw;class cw extends k{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",Nt]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const rr=new cw;class dw 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:()=>rr}])}}const If=new dw;class lw extends k{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>rr},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8}])}}const Vl=new lw;class uw extends k{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>rr}])}}const Rf=new uw;class hw extends k{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>rr}])}}new hw;class pw 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 mw=new pw;class fw 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 gw=new fw;class vw 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 vw;class yw 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 yw;class Ew extends k{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",bt]},{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 co=new Ew;class Sw extends k{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>co},{no:3,name:"producer_track",kind:"message",T:()=>gw}])}}const Tw=new Sw;class kw extends k{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>Tw}}])}}const Pf=new kw;class _w 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 bw=new _w;class ww 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:()=>bw}])}}const Af=new ww;class Cw extends k{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const Mf=new Cw;class Iw extends k{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const Df=new Iw;class Rw 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 Rw;class Pw 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 Of=new Pw;class Aw 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:()=>rr},{no:5,name:"msid",kind:"scalar",T:9},{no:6,name:"app_data",kind:"scalar",opt:!0,T:9}])}}const Nf=new Aw;class Mw extends k{constructor(){super("media.edge.SelectedPeersRequest",[])}}new Mw;class Dw extends k{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Lf=new Dw;class Ow 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 cn=new Ow;class Nw 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 Wa=new Nw;class Lw extends k{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>rr}])}}const xf=new Lw;class xw 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:()=>rr}])}}const Ff=new xw;class Fw extends k{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Uf=new Fw;class Uw extends k{constructor(){super("media.edge.KickAllPeersRequest",[])}}const Vf=new Uw;class Vw 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 Bf=new Vw;class Bw 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 jf=new Bw;class jw 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 Hf=new jw;class Hw 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 Ww=new Hw;class $w 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 Gw=new $w;class Jw extends k{constructor(){super("media.edge.EmptyResponse",[])}}new Jw;class qw 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:()=>co},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"user_id",kind:"scalar",opt:!0,T:9}])}}const Wf=new qw;class Kw 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 Gd=new Kw;class zw 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 Yw=new zw;class Qw extends k{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>Yw}])}}const Oh=new Qw;class Xw extends k{constructor(){super("media.edge.PeerJoinResponse",[])}}new Xw;class Zw extends k{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>Ww},{no:2,name:"participants",kind:"message",repeat:1,T:()=>Wf},{no:3,name:"selected_peers",kind:"message",T:()=>Gd},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const $a=new Zw;class e0 extends k{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const $f=new e0;class t0 extends k{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Pf}])}}new t0;class r0 extends k{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Pf},{no:3,name:"description",kind:"message",T:()=>rr}])}}const Gf=new r0;class n0 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:()=>rr}])}}const Jf=new n0;class i0 extends k{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>mw}])}}new i0;class s0 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 s0;class o0 extends k{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new o0;class a0 extends k{constructor(){super("media.edge.ProducerToggleResponse",[])}}new a0;class c0 extends k{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new c0;class d0 extends k{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>rr}])}}const qf=new d0;class l0 extends k{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>rr}])}}new l0;class u0 extends k{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new u0;class h0 extends k{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Kf=new h0;class p0 extends k{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const zf=new p0;class m0 extends k{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Yf=new m0;class f0 extends k{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Qf=new f0;class g0 extends k{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Xf=new g0;class v0 extends k{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>Wf}])}}const Nh=new v0;class y0 extends k{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>Vl}])}}new y0;class E0 extends k{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>co}])}}const Zf=new E0;class S0 extends k{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>co}])}}const eg=new S0;class T0 extends k{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>co}])}}const tg=new T0;class k0 extends k{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Ga=new k0;class _0 extends k{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Lh=new _0;class b0 extends k{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new b0;class w0 extends k{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new w0;class C0 extends k{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new C0;class I0 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 I0;class R0 extends k{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new R0;class P0 extends k{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new P0;class A0 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 sd=new A0;class M0 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 M0;class D0 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 O0=new D0;var Ja;(function(t){t[t.BROWSER=0]="BROWSER",t[t.TRACK=1]="TRACK",t[t.COMPOSITE=2]="COMPOSITE"})(Ja||(Ja={}));var Pr;(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"})(Pr||(Pr={}));var Jd;(function(t){t[t.NONE=0]="NONE",t[t.RECORDER=1]="RECORDER",t[t.LIVESTREAMER=2]="LIVESTREAMER"})(Jd||(Jd={}));var qa;(function(t){t[t.HIVE=0]="HIVE",t[t.CHAT=1]="CHAT",t[t.PING=2]="PING"})(qa||(qa={}));class N0 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 L0=new N0;class x0 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",Pr,"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:()=>L0}])}}const bc=new x0;class F0 extends k{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>bc}])}}const Oi=new F0;class U0 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",Pr,"STAGE_TYPE_"]}])}}const xh=new U0;class V0 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 B0=new V0;class j0 extends k{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>bc}])}}const od=new j0;class H0 extends k{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const Fh=new H0;class W0 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:()=>G0},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const rg=new W0;class $0 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",Ja]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const G0=new $0;class J0 extends k{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>rg}])}}const Uh=new J0;class q0 extends k{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const ng=new q0;class K0 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 K0;class z0 extends k{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>bc},{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",qa,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const Y0=new z0;class Q0 extends k{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>bc},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const X0=new Q0;class Z0 extends k{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>rg}])}}new Z0;class eC extends k{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new eC;class tC 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 Bl=new tC;class rC 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 nC=new rC;class iC 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:()=>nC}])}}const Vh=new iC;class sC extends k{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>Vh},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>Vh}])}}const oC=new sC;class aC extends k{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const cC=new aC;class dC extends k{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>cC}])}}const lC=new dC;class uC 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:()=>Bl}])}}const hC=new uC;class pC extends k{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>hC}])}}const Bh=new pC;class mC 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 fC=new mC;class gC extends k{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>fC}])}}new gC;class vC extends k{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const yC=new vC;class EC extends k{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>yC}])}}const SC=new EC;class TC extends k{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>bC}])}}const kC=new TC;class _C 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:()=>Bl}])}}const bC=new _C;class wC 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 CC=new wC;class IC 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:()=>CC}])}}const RC=new IC;class PC 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:()=>Bl}])}}const ig=new PC;class AC extends k{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>ig}])}}new AC;class MC 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 DC=new MC;class OC extends k{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>xC}])}}const NC=new OC;class LC 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 xC=new LC;class FC extends k{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const UC=new FC;class VC 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 To=new VC;class BC extends k{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const jC=new BC;class HC extends k{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const WC=new HC;class $C 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 GC=new $C;class JC extends k{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>GC}])}}const jh=new JC;class qC 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 Hh=new qC;var qd;(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"})(qd||(qd={}));var Ka;(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"})(Ka||(Ka={}));class KC 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 zC=new KC;class YC 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 QC=new YC;class XC 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 ZC=new XC;class eI 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 tI=new eI;class rI extends k{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>ZC},{no:2,name:"private",kind:"message",T:()=>tI}])}}const nI=new rI;class iI 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 sI=new iI;class oI extends k{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Ka,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Ka,"STREAM_PERMISSION_TYPE_"]}])}}const ad=new oI;class aI extends k{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>ad},{no:2,name:"audio",kind:"message",T:()=>ad},{no:3,name:"screenshare",kind:"message",T:()=>ad}])}}const cI=new aI;class dI extends k{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>zC},{no:2,name:"plugins",kind:"message",T:()=>QC},{no:3,name:"chat",kind:"message",T:()=>nI},{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",qd,"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",Jd,"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:()=>sI},{no:23,name:"media",kind:"message",T:()=>cI}])}}const jl=new dI;class lI extends k{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const uI=new lI;class hI 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 pI=new hI;class mI extends k{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>pI}])}}const fI=new mI;class gI extends k{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>jl}])}}const sg=new gI;class vI extends k{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>sg}])}}const yI=new vI;class EI extends k{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>sg}])}}const Wh=new EI;class SI 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 TI=new SI;class kI extends k{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>TI},{no:2,name:"patch",kind:"message",T:()=>jl}])}}new kI;class _I extends k{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>jl}])}}new _I;class bI 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 ui=new bI;class wI 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 CI=new wI;class II extends k{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>ui},{no:2,name:"next",kind:"scalar",T:8}])}}const RI=new II;class PI extends k{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>ui}])}}const og=new PI;class AI 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 MI=new AI;class DI extends k{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>ui}])}}const cd=new DI;class OI 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 NI=new OI;class LI extends k{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>ui}])}}const dd=new LI;class xI 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 FI=new xI;class UI extends k{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>ui}])}}new UI;class VI 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 BI=new VI;class jI 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 HI=new jI;class WI 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 ko=new WI;class $I extends k{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>ui}])}}const _o=new $I;class GI 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 JI=new GI;class qI 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 bo=new qI;class KI 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 zI=new KI;class YI 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 QI=new YI;class XI extends k{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}const ZI=new XI;class eR 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 tR=new eR;class rR 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 nR=new rR;class iR extends k{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new iR;class sR extends k{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}const oR=new sR;class aR extends k{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>ui},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const cR=new aR;class dR 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:()=>cR},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const lR=new dR;class uR extends k{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>lR}])}}const _r=new uR;class hR 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 pR=new hR;class mR extends k{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>pR}])}}const fR=new mR;class gR 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 vR=new gR;class yR 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 ER=new yR;class SR extends k{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const TR=new SR;class kR extends k{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const _R=new kR;class bR 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 wR=new bR;class CR 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 IR=new CR;class RR 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 PR=new RR;class AR 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 MR=new AR;class DR 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 Hl=new DR;class OR 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:()=>Hl}])}}const $h=new OR;class NR 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:()=>Hl}])}}const LR=new NR;class xR 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:()=>Hl}])}}const FR=new xR;class UR 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 VR=new UR;class BR 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 Kd=new BR;class jR extends k{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>Kd}])}}const HR=new jR;class WR 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 Gh=new WR;class $R 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 GR=new $R;class JR 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:()=>GR}])}}const Jh=new JR;class qR 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 qh=new qR;class KR 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 Kh=new KR;class zR extends k{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const zh=new zR;class YR 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 QR=new YR;class XR extends k{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>QR}])}}const ld=new XR;class ZR extends k{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const eP=new ZR;class tP extends k{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const rP=new tP;class nP extends k{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const Yh=new nP;class iP 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:()=>oP},{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 ag=new iP;class sP 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:()=>cP}])}}const oP=new sP;class aP 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 cP=new aP;class dP 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 lP=new dP;class uP 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 hP=new uP;class pP extends k{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>ag}])}}const ud=new pP;class mP extends k{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>ag}])}}const fP=new mP;class gP 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",Ja]}])}}const Qh=new gP;class vP 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=we.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}toDate(e){return new Date(we.from(e.seconds).toNumber()*1e3+Math.ceil(e.nanos/1e6))}fromDate(e){const r=this.create(),n=e.getTime();return r.seconds=we.from(Math.floor(n/1e3)).toBigInt(),r.nanos=n%1e3*1e6,r}internalJsonWrite(e,r){let n=we.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 "+yl(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=we.from(s/1e3).toBigInt(),n.nanos=0,i[7]&&(n.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),n}}new vP;class ns extends wt.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{}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{}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 xt extends wt.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{}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{}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 yP=0,EP=1,SP=2,TP=3,kP=4,_P=5,bP={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},wP={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,sendMessageToChannel:6,searchChannelMessages:7,getAllChatChannels:8,markChannelIndexAsRead:9,pinMessage:10},CP={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},IP={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},cg={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},RP={createChatChannel:0,getChatChannel:1,deprecatedGetAllChatChannels:2,getChannelMembers:3,updateChatChannel:4},PP={getUserPresets:0,updateUserPreset:1};function is(t,e){return Object.keys(e).reduce((r,n)=>(r[n]=(t<<16)+e[n],r),{})}function dg(t,e){return Object.keys(t).reduce((r,n)=>(r[n]=e|t[n],r),{})}const j=is(yP,bP),Ne=is(EP,wP),J=is(SP,CP),Cr=is(TP,IP),Yn=is(kP,RP),ie=dg(cg,16777216),se=dg(cg,50331648),ia=is(_P,PP);var AP=Object.defineProperty,MP=Object.getOwnPropertyDescriptor,Wl=(t,e,r,n)=>{for(var i=n>1?void 0:n?MP(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&&AP(e,r,i),i},yn,Xh;const zd=(Xh=class{constructor(t){_(this,yn,void 0),T(this,yn,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,yn).sendMessagePromise(Yn.createChatChannel,tR.toBinary(s)),a=_r.fromBinary(o.payload).chatChannels;return zd.formatChannel(a[0])})}updateChannel(t,e){return u(this,null,function*(){const r=yield c(this,yn).sendMessagePromise(Yn.updateChatChannel,nR.toBinary({chatChannelId:t,targetUserIds:e.memberIds,displayName:e.displayName,displayPictureUrl:e.displayPictureUrl,visibility:e.visibility})),n=_r.fromBinary(r.payload).chatChannels;return zd.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=Mr.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,yn).sendMessagePromise(Yn.getChannelMembers,oR.toBinary({chatChannelId:t}));return fR.fromBinary(e.payload).channelMembers.map(r=>{var n=r,{id:i}=n,s=dc(n,["id"]);return ne(V({},s),{userId:i})})}catch{return[]}})}on(t,e){let r,n;switch(t){case Yn.createChatChannel:{r=_r.fromBinary.bind(_r),n=_r.create();break}case Yn.updateChatChannel:{r=_r.fromBinary.bind(_r),n=_r.create();break}}if(!r){l.warn(`ChatChannelSocketHandler::Event ${t} is not recognized`);return}c(this,yn).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)})}},yn=new WeakMap,Xh);let ti=zd;Wl([y.trace("ChatChannelHandler.createChannel")],ti.prototype,"createChannel",1);Wl([y.trace("ChatChannelHandler.updateChannel")],ti.prototype,"updateChannel",1);Wl([y.trace("ChatChannelHandler.getChannelMembers")],ti.prototype,"getChannelMembers",1);var DP=Object.defineProperty,OP=Object.getOwnPropertyDescriptor,nr=(t,e,r,n)=>{for(var i=n>1?void 0:n?OP(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&&DP(e,r,i),i},Tt=(t=>(t[t.TEXT=0]="TEXT",t[t.IMAGE=1]="IMAGE",t[t.FILE=2]="FILE",t[t.CUSTOM=3]="CUSTOM",t))(Tt||{}),gt;class $t{constructor(e){_(this,gt,void 0),T(this,gt,e)}getChatMessages(){return c(this,gt).sendMessagePromise(Ne.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,gt).sendMessagePromise(Ne.getPaginatedMessages,CI.toBinary(o));return a.payload?RI.fromBinary(a.payload):{messages:[],next:!1}})}sendMessageToRoom(e,r){const n={payloadType:r,payload:e};c(this,gt).sendMessage(Ne.sendMessageToRoom,MI.toBinary(n))}sendMessageToPeers(e,r,n){const i={payloadType:r,peerIds:n,payload:e};c(this,gt).sendMessage(Ne.sendMessageToPeers,NI.toBinary(i))}sendMessageToChannel(e,r,n){const i={payloadType:r,channelId:n,payload:e};c(this,gt).sendMessage(Ne.sendMessageToChannel,FI.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,gt).sendMessagePromise(Ne.editMessage,BI.toBinary(o));return _o.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,gt).sendMessagePromise(Ne.deleteMessage,JI.toBinary(n)),s=bo.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,gt).sendMessagePromise(Ne.searchChannelMessages,zI.toBinary(o));return og.fromBinary(a.payload).messages}catch{return[]}})}getAllChannels(){return u(this,null,function*(){try{const e=yield c(this,gt).sendMessagePromise(Ne.getAllChatChannels);return _r.fromBinary(e.payload).chatChannels.map(ti.formatChannel)}catch{return[]}})}markLastReadMessage(e,r){return u(this,null,function*(){const n=yield c(this,gt).sendMessagePromise(Ne.markChannelIndexAsRead,QI.toBinary({channelId:e,userId:r.userId,channelIndex:r.channelIndex}));return ZI.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,gt).sendMessagePromise(Ne.pinMessage,HI.toBinary(n));return ko.fromBinary(i.payload)})}on(e,r){let n,i;switch(e){case Ne.sendMessageToRoom:{n=cd.fromBinary.bind(cd),i=cd.create();break}case Ne.sendMessageToPeers:{n=dd.fromBinary.bind(dd),i=dd.create();break}case Ne.editMessage:{n=_o.fromBinary.bind(_o),i=_o.create();break}case Ne.pinMessage:{n=ko.fromBinary.bind(ko),i=ko.create();break}case Ne.deleteMessage:{n=bo.fromBinary.bind(bo),i=bo.create();break}}if(!n){l.warn(`ChatSocketHandler::Event ${e} is not recognized`);return}c(this,gt).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)})}}gt=new WeakMap;nr([y.trace("SocketService.getChatMessages")],$t.prototype,"getChatMessages",1);nr([y.trace("SocketService.getChatMessagesPaginated")],$t.prototype,"getChatMessagesPaginated",1);nr([y.trace("SocketService.sendMessageToRoom")],$t.prototype,"sendMessageToRoom",1);nr([y.trace("SocketService.sendMessageToPeers")],$t.prototype,"sendMessageToPeers",1);nr([y.trace("SocketService.sendMessageToChannel")],$t.prototype,"sendMessageToChannel",1);nr([y.trace("SocketService.sendMessage")],$t.prototype,"sendMessage",1);nr([y.trace("SocketService.editMessage")],$t.prototype,"editMessage",1);nr([y.trace("SocketService.deleteMessage")],$t.prototype,"deleteMessage",1);nr([y.trace("SocketService.searchMessages")],$t.prototype,"searchMessages",1);nr([y.trace("SocketService.getAllChannels")],$t.prototype,"getAllChannels",1);nr([y.trace("SocketService.markLastReadMessage")],$t.prototype,"markLastReadMessage",1);function NP(t){return t.replace(/([-_]\w)/g,e=>e[1].toUpperCase())}function hr(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>hr(r));const e={};return Object.keys(t).forEach(r=>{const n=vl(r)?r:NP(r);e[n]=hr(t[r])}),e}function LP(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function lg(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>lg(r));const e={};return Object.keys(t).forEach(r=>{const n=vl(r)?r:LP(r);e[n]=t[r]}),e}function za(t,e={}){return t==null?{}:(Object.getOwnPropertyNames(t).forEach(r=>{if(typeof t[r]!="function"){if(typeof t[r]=="object"){za(t[r],e[r]={});return}e[r]=t[r]}}),e)}const xP=3,FP=30,UP=8e3;class VP{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=UP,retry:i=xP,retryDelay:s=FP,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=Va.create({baseURL:o,responseType:"json",timeout:n,retry:i,retryDelay:s}),this.axios=Va,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 BP=Object.defineProperty,jP=Object.getOwnPropertyDescriptor,$l=(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};class wc extends VP{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 bl.getIPDetails({peerId:r,apiHostnames:wf(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({},us),{tags:[...us.tags]});v.baseURL=`http://localhost:${p.port}`,v.name=p.name,v.picture=(f=p.picture)!=null?f:us.picture,v.description=(g=p.description)!=null?g:us.description,v.staggered=(E=p.staggered)!=null?E:us.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}})})}}$l([y.trace("APIClient.getIPDetails")],wc.prototype,"getIPDetails",1);$l([y.trace("APIClient.getICEServers")],wc.prototype,"getICEServers",1);$l([y.trace("APIClient.getPlugins")],wc.prototype,"getPlugins",1);var HP=Object.defineProperty,WP=Object.getOwnPropertyDescriptor,Fr=(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&&HP(e,r,i),i};class fr extends wc{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}=hr((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 hr(e)})}startRecording(e,r){return u(this,null,function*(){return(yield this.requests.post("/v2/recordings",ne(V({},lg(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{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}=hr((yield this.requests.post("v2/internals/rooms",{ip_information:e})).data.data);return{roomNodeUrl:r,meetingTitle:n,useHiveMedia:i!=null?i:!1,sfu:s}})}}Fr([y.trace("APIClient.startLivestreaming")],fr.prototype,"startLivestreaming",1);Fr([y.trace("APIClient.stopLivestreaming")],fr.prototype,"stopLivestreaming",1);Fr([y.trace("APIClient.getActiveLivestream")],fr.prototype,"getActiveLivestream",1);Fr([y.trace("APIClient.getUserDetails")],fr.prototype,"getUserDetails",1);Fr([y.trace("APIClient.startRecording")],fr.prototype,"startRecording",1);Fr([y.trace("APIClient.stopRecording")],fr.prototype,"updateRecording",1);Fr([y.trace("APIClient.getActiveRecording")],fr.prototype,"getActiveRecording",1);Fr([y.trace("APIClient.getActiveTranscript")],fr.prototype,"getActiveTranscript",1);Fr([y.trace("APIClient.getRoomNodeData")],fr.prototype,"getRoomNodeData",1);let Yd;function $P(t,e){return Yd=new fr(t,e),Yd}function He(){return Yd}function GP(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{return}})}close(){this.pc1.close(),this.pc2.close()}}class uf extends mt{constructor(e){super(),f(this,"call"),f(this,"timeOut"),this.call=new Qr(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 IS=8,CS=1/1e3;class PS extends uf{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(Qr.isNotHostCandidate),this.senderChannel=this.call.pc1.createDataChannel(null);for(let r=0;r<1024*256;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{}}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)*IS/(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*CS)})}}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 lu extends uf{constructor(e,r=Qr.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{}}dataChannelHandler(e){const r=e.channel;this.ch2=r,r.addEventListener("message",this.onCh2Recieve.bind(this))}hangup(e){this.testFailed(e)}}class RS extends lu{constructor(e){super(e,Qr.isHost)}}class AS extends lu{constructor(e){super(e,Qr.isRelay)}}class MS extends lu{constructor(e){super(e,Qr.isReflexive)}}class DS{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=An(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=An(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 uu=new DS,ph=[{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 mh(t){const[e,r]=t.split(",");return{coords:{latitude:Number(e),longitude:Number(r)}}}class hf{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 pf extends mt{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 mt}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 hf,G=r.length?new Set(r):void 0,W=[],oe=[],se=[],Oe=new Map,Et=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":{oe.push(this.getIceCandidateStats(O));break}case"candidate-pair":{const{nominated:k}=O,{selected:R}=O,H=O,Re={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};se.push(Re),(O.nominated===!0||O.selected===!0)&&(C.candidatePair=Re);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 Re=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 Xe=this.callStatsInstance.producers.get(R);if(((a=Xe==null?void 0:Xe.track)==null?void 0:a.readyState)==="ended")break;C.producerStreamMap.has(R)||C.producerStreamMap.set(R,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const U={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,Ze=B({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},U);C.outboundVideoRtp.set(O.id,Ze),C.producerStreamMap.get(R).outboundVideoRtpId.push(O.id),this.processOutboundProducerVideoStats(R,Re,Ze)}else if(k.mediaType==="audio"||k.kind==="audio"){const M=k,Ze=B({retransmittedBytesSent:M.retransmittedBytesSent,retransmittedPacketsSent:M.retransmittedPacketsSent},U);C.outboundAudioRtp.set(O.id,Ze),C.producerStreamMap.get(R).outboundAudioRtpId.push(O.id),this.processOutboundProducerAudioStats(R,Re,Ze)}}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 Re=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 Xe={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 U=k,M=B({frameHeight:U.frameHeight,frameWidth:U.frameWidth,framesDecoded:U.framesDecoded,framesDropped:U.framesDropped,framesPerSecond:U.framesPerSecond,framesReceived:U.framesReceived,keyFramesDecoded:U.keyFramesDecoded,firCount:U.firCount,decoderImplementation:U.decoderImplementation,pliCount:U.pliCount,totalProcessingDelay:U.totalProcessingDelay,qpSum:U.qpSum||0,totalAssemblyTime:U.totalAssemblyTime||0,totalDecodeTime:U.totalDecodeTime||0,totalFreezesDuration:U.totalFreezesDuration||0,totalInterFrameDelay:U.totalInterFrameDelay||0,totalPausesDuration:U.totalPausesDuration||0,totalSquaredInterFrameDelay:U.totalSquaredInterFrameDelay||0,freezeCount:U.freezeCount||0,pauseCount:U.pauseCount||0,powerEfficientDecoder:U.powerEfficientDecoder},Xe);M.score=lf({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)}),Et.set(R,{score:+(M.score*10).toFixed(),frameWidth:M.frameWidth||0,frameHeight:M.frameHeight||0,framesPerSecond:M.framesPerSecond||0,packetsLostPercentage:Sc({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,Re,M)}else if(k.mediaType==="audio"||k.kind==="audio"){const U=k,M=B({audioLevel:U.audioLevel,concealedSamples:U.concealedSamples,concealmentEvents:U.concealmentEvents,totalAudioEnergy:U.totalAudioEnergy,totalSamplesDuration:U.totalSamplesDuration,totalSamplesReceived:U.totalSamplesReceived,fecPacketsDiscarded:U.fecPacketsDiscarded||0,fecPacketsReceived:U.fecPacketsReceived||0,insertedSamplesForDeceleration:U.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:U.removedSamplesForAcceleration||0,silentConcealedSamples:U.silentConcealedSamples||0,playoutId:U.playoutId},Xe);M.score=df({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}),Et.set(R,{score:+(M.score*10).toFixed(),packetsLostPercentage:Sc({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,Re,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,Re,Xe,U,M,Ze,Cr,Ss,Es,Ts,ks,_s,bs,ws,Is,Cs,Ps,Rs,As,Ms,Ds,Os;if(O.outboundVideoRtpId.length>0){const _e=[];O.outboundVideoRtpId.forEach(Td=>{_e.push(C.outboundVideoRtp.get(Td))});const he=this.getWorkingSimulcastVideoStats(_e);he.score=of({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:(((Re=he.remoteData)==null?void 0:Re.packetsLost)||0)-(((U=(Xe=this.videoProducerToStatsMap.get(k))==null?void 0:Xe.remoteData)==null?void 0:U.packetsLost)||0),framesEncoded:(he.framesEncoded||0)-(((M=this.videoProducerToStatsMap.get(k))==null?void 0:M.framesEncoded)||0)}),Oe.set(k,{score:+(he.score*10).toFixed(),frameWidth:he.frameWidth||0,frameHeight:he.frameHeight||0,framesPerSecond:he.framesPerSecond||0,jitter:((Ze=he.remoteData)==null?void 0:Ze.jitter)||0,isScreenShare:this.screenShareProducers.has(k),packetsLostPercentage:yc({packetsSent:(he.packetsSent||0)-(((Cr=this.videoProducerToStatsMap.get(k))==null?void 0:Cr.packetsSent)||0),packetsLost:(((Ss=he.remoteData)==null?void 0:Ss.packetsLost)||0)-(((Ts=(Es=this.videoProducerToStatsMap.get(k))==null?void 0:Es.remoteData)==null?void 0:Ts.packetsLost)||0)}),bitrate:((he.bytesSent||0)-(((ks=this.videoProducerToStatsMap.get(k))==null?void 0:ks.bytesSent)||0))*8/7,cpuLimitations:he.qualityLimitationReason==="cpu",bandwidthLimitations:he.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(k,he)}else if(O.outboundAudioRtpId.length>0){const _e=C.outboundAudioRtp.get(O.outboundAudioRtpId[0]);_e.score=af({packetsSent:(_e.packetsSent||0)-(((_s=this.audioProducerToStatsMap.get(k))==null?void 0:_s.packetsSent)||0),packetsLost:(((bs=_e.remoteData)==null?void 0:bs.packetsLost)||0)-(((Is=(ws=this.audioProducerToStatsMap.get(k))==null?void 0:ws.remoteData)==null?void 0:Is.packetsLost)||0),jitter:((Cs=_e.remoteData)==null?void 0:Cs.jitter)||0}),Oe.set(k,{score:+(_e.score*10).toFixed(),bitrate:((_e.bytesSent||0)-(((Ps=this.audioProducerToStatsMap.get(k))==null?void 0:Ps.bytesSent)||0))*8/7,packetsLostPercentage:yc({packetsSent:(_e.packetsSent||0)-(((Rs=this.audioProducerToStatsMap.get(k))==null?void 0:Rs.packetsSent)||0),packetsLost:(((As=_e.remoteData)==null?void 0:As.packetsLost)||0)-(((Ds=(Ms=this.audioProducerToStatsMap.get(k))==null?void 0:Ms.remoteData)==null?void 0:Ds.packetsLost)||0)}),jitter:((Os=_e.remoteData)==null?void 0:Os.jitter)||0,isScreenShare:this.screenShareProducers.has(k)}),this.audioProducerToStatsMap.set(k,_e)}}),se.forEach(O=>{const k=W.find(H=>H.id===O.localCandidateId?(O.localCandidateId=H.id,H):null),R=oe.find(H=>H.id===O.remoteCandidateId?(O.remoteCandidateId=H.id,H):null);k&&(O.localCandidateType=k.type,O.localCandidateAddress=An(k.address),O.localCandidatePort=k.port,O.localCandidateProtocol=k.protocol,O.localCandidateUrl=k.url,O.localCandidateNetworkType=k.networkType,O.localCandidateRelatedAddress=An(k.relatedAddress),O.localCandidateRelatedPort=k.relatedPort),R&&(O.remoteCandidateType=R.type,O.remoteCandidateAddress=An(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=se),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(Et.size>0)try{this.observer.emit("consumer_score",Et)}catch{}if(Oe.size>0)try{this.observer.emit("producer_score",Oe)}catch{}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||ph},n=new Promise((h,p)=>{try{const m=new RS(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 AS(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 MS(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{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||ph},a=new PS(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{return}})}getIPDetails(){return u(this,null,function*(){var e,r;try{return this.ipDetails||(this.ipDetails=yield uu.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{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?mh(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?mh(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 OS extends pf{}class mf extends pf{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 hf,G=r.length?new Set(r):void 0,W=[],oe=[],se=[],Oe=new Map,Et=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":{oe.push(this.getIceCandidateStats(O));break}case"candidate-pair":{const{nominated:k}=O,{selected:R}=O,H=O,Re={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};se.push(Re),(O.nominated===!0||O.selected===!0)&&(C.candidatePair=Re);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 Re=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 Xe=this.callStatsInstance.producers.get(R);if(((a=Xe==null?void 0:Xe.track)==null?void 0:a.readyState)==="ended")break;C.producerStreamMap.has(R)||C.producerStreamMap.set(R,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const U={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,Ze=B({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},U);C.outboundVideoRtp.set(O.id,Ze),C.producerStreamMap.get(R).outboundVideoRtpId.push(O.id),this.processOutboundProducerVideoStats(R,Re,Ze)}else if(k.mediaType==="audio"||k.kind==="audio"){const M=k,Ze=B({retransmittedBytesSent:M.retransmittedBytesSent,retransmittedPacketsSent:M.retransmittedPacketsSent},U);C.outboundAudioRtp.set(O.id,Ze),C.producerStreamMap.get(R).outboundAudioRtpId.push(O.id),this.processOutboundProducerAudioStats(R,Re,Ze)}}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 Re=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 Xe={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 U=k,M=B({frameHeight:U.frameHeight,frameWidth:U.frameWidth,framesDecoded:U.framesDecoded,framesDropped:U.framesDropped?U.framesDropped:U.droppedFrames,framesPerSecond:U.framesPerSecond?U.framesPerSecond:U.framerateMean,framesReceived:U.framesReceived,keyFramesDecoded:U.keyFramesDecoded,firCount:U.firCount,decoderImplementation:U.decoderImplementation,pliCount:U.pliCount,totalProcessingDelay:U.totalProcessingDelay,qpSum:U.qpSum||0,totalAssemblyTime:U.totalAssemblyTime||0,totalDecodeTime:U.totalDecodeTime||0,totalFreezesDuration:U.totalFreezesDuration||0,totalInterFrameDelay:U.totalInterFrameDelay||0,totalPausesDuration:U.totalPausesDuration||0,totalSquaredInterFrameDelay:U.totalSquaredInterFrameDelay||0,freezeCount:U.freezeCount||0,pauseCount:U.pauseCount||0,powerEfficientDecoder:U.powerEfficientDecoder},Xe);M.score=lf({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)}),Et.set(R,{score:+(M.score*10).toFixed(),frameWidth:M.frameWidth||0,frameHeight:M.frameHeight||0,framesPerSecond:M.framesPerSecond||0,packetsLostPercentage:Sc({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,Re,M)}else if(k.mediaType==="audio"||k.kind==="audio"){const U=k,M=B({audioLevel:U.audioLevel,concealedSamples:U.concealedSamples,concealmentEvents:U.concealmentEvents,totalAudioEnergy:U.totalAudioEnergy,totalSamplesDuration:U.totalSamplesDuration,totalSamplesReceived:U.totalSamplesReceived,fecPacketsDiscarded:U.fecPacketsDiscarded||0,fecPacketsReceived:U.fecPacketsReceived||0,insertedSamplesForDeceleration:U.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:U.removedSamplesForAcceleration||0,silentConcealedSamples:U.silentConcealedSamples||0,playoutId:U.playoutId},Xe);M.score=df({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}),Et.set(R,{score:+(M.score*10).toFixed(),packetsLostPercentage:Sc({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,Re,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,Re,Xe,U,M,Ze,Cr,Ss,Es,Ts,ks,_s,bs,ws,Is,Cs,Ps,Rs,As,Ms,Ds,Os;if(O.outboundVideoRtpId.length>0){const _e=[];O.outboundVideoRtpId.forEach(Td=>{_e.push(C.outboundVideoRtp.get(Td))});const he=this.getWorkingSimulcastVideoStats(_e);he.score=of({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:(((Re=he.remoteData)==null?void 0:Re.packetsLost)||0)-(((U=(Xe=this.videoProducerToStatsMap.get(k))==null?void 0:Xe.remoteData)==null?void 0:U.packetsLost)||0),framesEncoded:(he.framesEncoded||0)-(((M=this.videoProducerToStatsMap.get(k))==null?void 0:M.framesEncoded)||0)}),Oe.set(k,{score:+(he.score*10).toFixed(),frameWidth:he.frameWidth||0,frameHeight:he.frameHeight||0,framesPerSecond:he.framesPerSecond||0,jitter:((Ze=he.remoteData)==null?void 0:Ze.jitter)||0,isScreenShare:this.screenShareProducers.has(k),packetsLostPercentage:yc({packetsSent:(he.packetsSent||0)-(((Cr=this.videoProducerToStatsMap.get(k))==null?void 0:Cr.packetsSent)||0),packetsLost:(((Ss=he.remoteData)==null?void 0:Ss.packetsLost)||0)-(((Ts=(Es=this.videoProducerToStatsMap.get(k))==null?void 0:Es.remoteData)==null?void 0:Ts.packetsLost)||0)}),bitrate:((he.bytesSent||0)-(((ks=this.videoProducerToStatsMap.get(k))==null?void 0:ks.bytesSent)||0))*8/7,cpuLimitations:he.qualityLimitationReason==="cpu",bandwidthLimitations:he.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(k,he)}else if(O.outboundAudioRtpId.length>0){const _e=C.outboundAudioRtp.get(O.outboundAudioRtpId[0]);_e.score=af({packetsSent:(_e.packetsSent||0)-(((_s=this.audioProducerToStatsMap.get(k))==null?void 0:_s.packetsSent)||0),packetsLost:(((bs=_e.remoteData)==null?void 0:bs.packetsLost)||0)-(((Is=(ws=this.audioProducerToStatsMap.get(k))==null?void 0:ws.remoteData)==null?void 0:Is.packetsLost)||0),jitter:((Cs=_e.remoteData)==null?void 0:Cs.jitter)||0}),Oe.set(k,{score:+(_e.score*10).toFixed(),bitrate:((_e.bytesSent||0)-(((Ps=this.audioProducerToStatsMap.get(k))==null?void 0:Ps.bytesSent)||0))*8/7,packetsLostPercentage:yc({packetsSent:(_e.packetsSent||0)-(((Rs=this.audioProducerToStatsMap.get(k))==null?void 0:Rs.packetsSent)||0),packetsLost:(((As=_e.remoteData)==null?void 0:As.packetsLost)||0)-(((Ds=(Ms=this.audioProducerToStatsMap.get(k))==null?void 0:Ms.remoteData)==null?void 0:Ds.packetsLost)||0)}),jitter:((Os=_e.remoteData)==null?void 0:Os.jitter)||0,isScreenShare:this.screenShareProducers.has(k)}),this.audioProducerToStatsMap.set(k,_e)}}),se.forEach(O=>{const k=W.find(H=>H.id===O.localCandidateId?(O.localCandidateId=H.id,H):null),R=oe.find(H=>H.id===O.remoteCandidateId?(O.remoteCandidateId=H.id,H):null);k&&(O.localCandidateType=k.type,O.localCandidateAddress=An(k.address),O.localCandidatePort=k.port,O.localCandidateProtocol=k.protocol,O.localCandidateUrl=k.url,O.localCandidateNetworkType=k.networkType,O.localCandidateRelatedAddress=An(k.relatedAddress),O.localCandidateRelatedPort=k.relatedPort),R&&(O.remoteCandidateType=R.type,O.remoteCandidateAddress=An(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=se),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(Et.size>0)try{this.observer.emit("consumer_score",Et)}catch{}if(Oe.size>0)try{this.observer.emit("producer_score",Oe)}catch{}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 NS extends mf{}function Ec(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 fh(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=>{Ec(this,e,r,a)}):s}catch(s){Ec(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=>{Ec(this,t,e,d)}):o}catch(o){Ec(this,t,e,o)}return null},i},LS=(t,e)=>(r,n,i)=>{if(i)return fh(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,fh(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 mt{constructor(t="https://api.testingv3.dyte.in",e="Blink",r=Da.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 SS({logger:i,peerId:s,apiHostnames:a}),this.logger.debug("callStats::engineName: ",{engineName:e}),e){case"Blink":this.measurements=new OS;break;case"Gecko":this.measurements=new mf;break;case"WebKit":this.measurements=new NS;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 mt,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===Zt.AUDIO&&V.AUDIO_DEVICES_UPDATES||t===Zt.VIDEO&&V.VIDEO_DEVICES_UPDATES||t===Zt.SPEAKER&&V.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:e},timestamp:r})}selectedDevice(t,e,r){this.eventHandler.callEvent({event:t===Zt.AUDIO&&V.SELECTED_MICROHPONE_UPDATE||t===Zt.VIDEO&&V.SELECTED_CAMERA_UPDATE||t===Zt.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===Zt.AUDIO&&V.AUDIO_PLAY_FAILED||t===Zt.VIDEO&&V.VIDEO_PLAY_FAILED,metaData:{deviceType:t},timestamp:e})}mediaTrackMuted(t,e){this.eventHandler.callEvent({event:t===Zt.AUDIO&&V.AUDIO_TRACK_MUTED||t===Zt.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=Z(B({},t),{meetingEnv:this.env}),t.deviceInfo=Z(B({},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(Z(B({},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([LS(TypeError,(t,e)=>te.error(e,t))],Y);const xS=Y;class FS extends mt{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=Da.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 uu.getIPDetails({peerId:r,apiHostnames:h,logger:d}),this.backend=new xS(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 FS;$.setMaxListeners(30);function VS(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:VS});function US(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:US});var Tl={},BS={get exports(){return Tl},set exports(t){Tl=t}},Tc={},jS={get exports(){return Tc},set exports(t){Tc=t}},ff=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)}},HS=ff,Ln=Object.prototype.toString;function hu(t){return Array.isArray(t)}function kl(t){return typeof t=="undefined"}function WS(t){return t!==null&&!kl(t)&&t.constructor!==null&&!kl(t.constructor)&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t)}function gf(t){return Ln.call(t)==="[object ArrayBuffer]"}function $S(t){return Ln.call(t)==="[object FormData]"}function JS(t){var e;return typeof ArrayBuffer!="undefined"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&gf(t.buffer),e}function GS(t){return typeof t=="string"}function qS(t){return typeof t=="number"}function vf(t){return t!==null&&typeof t=="object"}function Vo(t){if(Ln.call(t)!=="[object Object]")return!1;var e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}function zS(t){return Ln.call(t)==="[object Date]"}function KS(t){return Ln.call(t)==="[object File]"}function YS(t){return Ln.call(t)==="[object Blob]"}function yf(t){return Ln.call(t)==="[object Function]"}function QS(t){return vf(t)&&yf(t.pipe)}function XS(t){return Ln.call(t)==="[object URLSearchParams]"}function ZS(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function eE(){return typeof navigator!="undefined"&&(navigator.product==="ReactNative"||navigator.product==="NativeScript"||navigator.product==="NS")?!1:typeof window!="undefined"&&typeof document!="undefined"}function pu(t,e){if(!(t===null||typeof t=="undefined"))if(typeof t!="object"&&(t=[t]),hu(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 _l(){var t={};function e(i,s){Vo(t[s])&&Vo(i)?t[s]=_l(t[s],i):Vo(i)?t[s]=_l({},i):hu(i)?t[s]=i.slice():t[s]=i}for(var r=0,n=arguments.length;r<n;r++)pu(arguments[r],e);return t}function tE(t,e,r){return pu(e,function(n,i){r&&typeof n=="function"?t[i]=HS(n,r):t[i]=n}),t}function rE(t){return t.charCodeAt(0)===65279&&(t=t.slice(1)),t}var Ft={isArray:hu,isArrayBuffer:gf,isBuffer:WS,isFormData:$S,isArrayBufferView:JS,isString:GS,isNumber:qS,isObject:vf,isPlainObject:Vo,isUndefined:kl,isDate:zS,isFile:KS,isBlob:YS,isFunction:yf,isStream:QS,isURLSearchParams:XS,isStandardBrowserEnv:eE,forEach:pu,merge:_l,extend:tE,trim:ZS,stripBOM:rE},Ri=Ft;function gh(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var Sf=function(t,e,r){if(!e)return t;var n;if(r)n=r(e);else if(Ri.isURLSearchParams(e))n=e.toString();else{var i=[];Ri.forEach(e,function(a,o){a===null||typeof a=="undefined"||(Ri.isArray(a)?o=o+"[]":a=[a],Ri.forEach(a,function(d){Ri.isDate(d)?d=d.toISOString():Ri.isObject(d)&&(d=JSON.stringify(d)),i.push(gh(o)+"="+gh(d))}))}),n=i.join("&")}if(n){var s=t.indexOf("#");s!==-1&&(t=t.slice(0,s)),t+=(t.indexOf("?")===-1?"?":"&")+n}return t},nE=Ft;function Zc(){this.handlers=[]}Zc.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};Zc.prototype.eject=function(t){this.handlers[t]&&(this.handlers[t]=null)};Zc.prototype.forEach=function(t){nE.forEach(this.handlers,function(e){e!==null&&t(e)})};var iE=Zc,sE=Ft,aE=function(t,e){sE.forEach(t,function(r,n){n!==e&&n.toUpperCase()===e.toUpperCase()&&(t[e]=r,delete t[n])})},Ef=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},Id,vh;function Tf(){if(vh)return Id;vh=1;var t=Ef;return Id=function(e,r,n,i,s){var a=new Error(e);return t(a,r,n,i,s)},Id}var Cd,yh;function oE(){if(yh)return Cd;yh=1;var t=Tf();return Cd=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))},Cd}var Pd,Sh;function cE(){if(Sh)return Pd;Sh=1;var t=Ft;return Pd=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(){}}}(),Pd}var Eh,Th;function dE(){return Th||(Th=1,Eh=function(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}),Eh}var kh,_h;function lE(){return _h||(_h=1,kh=function(t,e){return e?t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):t}),kh}var Rd,bh;function uE(){if(bh)return Rd;bh=1;var t=dE(),e=lE();return Rd=function(r,n){return r&&!t(n)?e(r,n):n},Rd}var Ad,wh;function hE(){if(wh)return Ad;wh=1;var t=Ft,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 Ad=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},Ad}var Md,Ih;function pE(){if(Ih)return Md;Ih=1;var t=Ft;return Md=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}}(),Md}var Dd,Ch;function ed(){if(Ch)return Dd;Ch=1;function t(e){this.message=e}return t.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},t.prototype.__CANCEL__=!0,Dd=t,Dd}var Od,Ph;function mE(){if(Ph)return Od;Ph=1;var t=Ft,e=oE(),r=cE(),n=Sf,i=uE(),s=hE(),a=pE(),o=Tf(),d=td(),h=ed();return Od=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 se="getAllResponseHeaders"in N?s(N.getAllResponseHeaders()):null,Oe=!A||A==="text"||A==="json"?N.responseText:N.response,Et={data:Oe,status:N.status,statusText:N.statusText,headers:se,config:p,request:N};e(function(O){m(O),D()},function(O){g(O),D()},Et),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 se=p.timeout?"timeout of "+p.timeout+"ms exceeded":"timeout exceeded",Oe=p.transitional||d.transitional;p.timeoutErrorMessage&&(se=p.timeoutErrorMessage),g(o(se,p,Oe.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",N)),N=null},t.isStandardBrowserEnv()){var oe=(p.withCredentials||a(G))&&p.xsrfCookieName?r.read(p.xsrfCookieName):void 0;oe&&(I[p.xsrfHeaderName]=oe)}"setRequestHeader"in N&&t.forEach(I,function(se,Oe){typeof v=="undefined"&&Oe.toLowerCase()==="content-type"?delete I[Oe]:N.setRequestHeader(Oe,se)}),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(se){N&&(g(!se||se&&se.type?new h("canceled"):se),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)})},Od}var Nd,Rh;function td(){if(Rh)return Nd;Rh=1;var t=Ft,e=aE,r=Ef,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=mE()),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)}),Nd=o,Nd}var fE=Ft,gE=td(),vE=function(t,e,r){var n=this||gE;return fE.forEach(r,function(i){t=i.call(n,t,e)}),t},Ah,Mh;function kf(){return Mh||(Mh=1,Ah=function(t){return!!(t&&t.__CANCEL__)}),Ah}var Dh=Ft,Ld=vE,yE=kf(),SE=td(),EE=ed();function xd(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new EE("canceled")}var TE=function(t){xd(t),t.headers=t.headers||{},t.data=Ld.call(t,t.data,t.headers,t.transformRequest),t.headers=Dh.merge(t.headers.common||{},t.headers[t.method]||{},t.headers),Dh.forEach(["delete","get","head","post","put","patch","common"],function(r){delete t.headers[r]});var e=t.adapter||SE.adapter;return e(t).then(function(r){return xd(t),r.data=Ld.call(t,r.data,r.headers,t.transformResponse),r},function(r){return yE(r)||(xd(t),r&&r.response&&(r.response.data=Ld.call(t,r.response.data,r.response.headers,t.transformResponse))),Promise.reject(r)})},Bt=Ft,_f=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},Oh,Nh;function bf(){return Nh||(Nh=1,Oh={version:"0.25.0"}),Oh}var kE=bf().version,mu={};["object","boolean","number","function","string","symbol"].forEach(function(t,e){mu[t]=function(r){return typeof r===t||"a"+(e<1?"n ":" ")+t}});var Lh={};mu.transitional=function(t,e,r){function n(i,s){return"[Axios v"+kE+"] 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&&!Lh[s]&&(Lh[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 _E(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 bE={assertOptions:_E,validators:mu},wf=Ft,wE=Sf,xh=iE,Fh=TE,rd=_f,If=bE,Ai=If.validators;function Ha(t){this.defaults=t,this.interceptors={request:new xh,response:new xh}}Ha.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=rd(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&&If.assertOptions(r,{silentJSONParsing:Ai.transitional(Ai.boolean),forcedJSONParsing:Ai.transitional(Ai.boolean),clarifyTimeoutError:Ai.transitional(Ai.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=[Fh,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=Fh(d)}catch(m){return Promise.reject(m)}for(;s.length;)a=a.then(s.shift(),s.shift());return a};Ha.prototype.getUri=function(t){if(!t.url)throw new Error("Provided config url is not valid");return t=rd(this.defaults,t),wE(t.url,t.params,t.paramsSerializer).replace(/^\?/,"")};wf.forEach(["delete","get","head","options"],function(t){Ha.prototype[t]=function(e,r){return this.request(rd(r||{},{method:t,url:e,data:(r||{}).data}))}});wf.forEach(["post","put","patch"],function(t){Ha.prototype[t]=function(e,r,n){return this.request(rd(n||{},{method:t,url:e,data:r}))}});var IE=Ha,Fd,Vh;function CE(){if(Vh)return Fd;Vh=1;var t=ed();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}},Fd=e,Fd}var Uh,Bh;function PE(){return Bh||(Bh=1,Uh=function(t){return function(e){return t.apply(null,e)}}),Uh}var Vd,jh;function RE(){if(jh)return Vd;jh=1;var t=Ft;return Vd=function(e){return t.isObject(e)&&e.isAxiosError===!0},Vd}var Hh=Ft,AE=ff,Uo=IE,ME=_f,DE=td();function Cf(t){var e=new Uo(t),r=AE(Uo.prototype.request,e);return Hh.extend(r,Uo.prototype,e),Hh.extend(r,e),r.create=function(n){return Cf(ME(t,n))},r}var wr=Cf(DE);wr.Axios=Uo;wr.Cancel=ed();wr.CancelToken=CE();wr.isCancel=kf();wr.VERSION=bf().version;wr.all=function(t){return Promise.all(t)};wr.spread=PE();wr.isAxiosError=RE();jS.exports=wr;Tc.default=wr;(function(t){t.exports=Tc})(BS);const kc=dS(Tl);function OE(){this.__data__=[],this.size=0}function Wa(t,e){return t===e||t!==t&&e!==e}function nd(t,e){for(var r=t.length;r--;)if(Wa(t[r][0],e))return r;return-1}var NE=Array.prototype,LE=NE.splice;function xE(t){var e=this.__data__,r=nd(e,t);if(r<0)return!1;var n=e.length-1;return r==n?e.pop():LE.call(e,r,1),--this.size,!0}function FE(t){var e=this.__data__,r=nd(e,t);return r<0?void 0:e[r][1]}function VE(t){return nd(this.__data__,t)>-1}function UE(t,e){var r=this.__data__,n=nd(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}function Zr(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])}}Zr.prototype.clear=OE;Zr.prototype.delete=xE;Zr.prototype.get=FE;Zr.prototype.has=VE;Zr.prototype.set=UE;function BE(){this.__data__=new Zr,this.size=0}function jE(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r}function HE(t){return this.__data__.get(t)}function WE(t){return this.__data__.has(t)}var $E=typeof global=="object"&&global&&global.Object===Object&&global;const Pf=$E;var JE=typeof self=="object"&&self&&self.Object===Object&&self,GE=Pf||JE||Function("return this")();const mr=GE;var qE=mr.Symbol;const Dn=qE;var Rf=Object.prototype,zE=Rf.hasOwnProperty,KE=Rf.toString,Ls=Dn?Dn.toStringTag:void 0;function YE(t){var e=zE.call(t,Ls),r=t[Ls];try{t[Ls]=void 0;var n=!0}catch{}var i=KE.call(t);return n&&(e?t[Ls]=r:delete t[Ls]),i}var QE=Object.prototype,XE=QE.toString;function ZE(t){return XE.call(t)}var eT="[object Null]",tT="[object Undefined]",Wh=Dn?Dn.toStringTag:void 0;function ki(t){return t==null?t===void 0?tT:eT:Wh&&Wh in Object(t)?YE(t):ZE(t)}function pr(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var rT="[object AsyncFunction]",nT="[object Function]",iT="[object GeneratorFunction]",sT="[object Proxy]";function fu(t){if(!pr(t))return!1;var e=ki(t);return e==nT||e==iT||e==rT||e==sT}var aT=mr["__core-js_shared__"];const Ud=aT;var $h=function(){var t=/[^.]+$/.exec(Ud&&Ud.keys&&Ud.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();function oT(t){return!!$h&&$h in t}var cT=Function.prototype,dT=cT.toString;function _i(t){if(t!=null){try{return dT.call(t)}catch{}try{return t+""}catch{}}return""}var lT=/[\\^$.*+?()[\]{}|]/g,uT=/^\[object .+?Constructor\]$/,hT=Function.prototype,pT=Object.prototype,mT=hT.toString,fT=pT.hasOwnProperty,gT=RegExp("^"+mT.call(fT).replace(lT,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function vT(t){if(!pr(t)||oT(t))return!1;var e=fu(t)?gT:uT;return e.test(_i(t))}function yT(t,e){return t==null?void 0:t[e]}function bi(t,e){var r=yT(t,e);return vT(r)?r:void 0}var ST=bi(mr,"Map");const Fa=ST;var ET=bi(Object,"create");const Va=ET;function TT(){this.__data__=Va?Va(null):{},this.size=0}function kT(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var _T="__lodash_hash_undefined__",bT=Object.prototype,wT=bT.hasOwnProperty;function IT(t){var e=this.__data__;if(Va){var r=e[t];return r===_T?void 0:r}return wT.call(e,t)?e[t]:void 0}var CT=Object.prototype,PT=CT.hasOwnProperty;function RT(t){var e=this.__data__;return Va?e[t]!==void 0:PT.call(e,t)}var AT="__lodash_hash_undefined__";function MT(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=Va&&e===void 0?AT:e,this}function fi(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])}}fi.prototype.clear=TT;fi.prototype.delete=kT;fi.prototype.get=IT;fi.prototype.has=RT;fi.prototype.set=MT;function DT(){this.size=0,this.__data__={hash:new fi,map:new(Fa||Zr),string:new fi}}function OT(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function id(t,e){var r=t.__data__;return OT(e)?r[typeof e=="string"?"string":"hash"]:r.map}function NT(t){var e=id(this,t).delete(t);return this.size-=e?1:0,e}function LT(t){return id(this,t).get(t)}function xT(t){return id(this,t).has(t)}function FT(t,e){var r=id(this,t),n=r.size;return r.set(t,e),this.size+=r.size==n?0:1,this}function wi(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])}}wi.prototype.clear=DT;wi.prototype.delete=NT;wi.prototype.get=LT;wi.prototype.has=xT;wi.prototype.set=FT;var VT=200;function UT(t,e){var r=this.__data__;if(r instanceof Zr){var n=r.__data__;if(!Fa||n.length<VT-1)return n.push([t,e]),this.size=++r.size,this;r=this.__data__=new wi(n)}return r.set(t,e),this.size=r.size,this}function kr(t){var e=this.__data__=new Zr(t);this.size=e.size}kr.prototype.clear=BE;kr.prototype.delete=jE;kr.prototype.get=HE;kr.prototype.has=WE;kr.prototype.set=UT;function BT(t,e){for(var r=-1,n=t==null?0:t.length;++r<n&&e(t[r],r,t)!==!1;);return t}var jT=function(){try{var t=bi(Object,"defineProperty");return t({},"",{}),t}catch{}}();const _c=jT;function gu(t,e,r){e=="__proto__"&&_c?_c(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}var HT=Object.prototype,WT=HT.hasOwnProperty;function Af(t,e,r){var n=t[e];(!(WT.call(t,e)&&Wa(n,r))||r===void 0&&!(e in t))&&gu(t,e,r)}function $a(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?gu(r,o,d):Af(r,o,d)}return r}function $T(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 JT="[object Arguments]";function Jh(t){return br(t)&&ki(t)==JT}var Mf=Object.prototype,GT=Mf.hasOwnProperty,qT=Mf.propertyIsEnumerable,zT=Jh(function(){return arguments}())?Jh:function(t){return br(t)&&GT.call(t,"callee")&&!qT.call(t,"callee")};const bc=zT;var KT=Array.isArray;const On=KT;function YT(){return!1}var Df=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Gh=Df&&typeof module=="object"&&module&&!module.nodeType&&module,QT=Gh&&Gh.exports===Df,qh=QT?mr.Buffer:void 0,XT=qh?qh.isBuffer:void 0,ZT=XT||YT;const os=ZT;var ek=9007199254740991,tk=/^(?:0|[1-9]\d*)$/;function Of(t,e){var r=typeof t;return e=e==null?ek:e,!!e&&(r=="number"||r!="symbol"&&tk.test(t))&&t>-1&&t%1==0&&t<e}var rk=9007199254740991;function Nf(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=rk}var nk="[object Arguments]",ik="[object Array]",sk="[object Boolean]",ak="[object Date]",ok="[object Error]",ck="[object Function]",dk="[object Map]",lk="[object Number]",uk="[object Object]",hk="[object RegExp]",pk="[object Set]",mk="[object String]",fk="[object WeakMap]",gk="[object ArrayBuffer]",vk="[object DataView]",yk="[object Float32Array]",Sk="[object Float64Array]",Ek="[object Int8Array]",Tk="[object Int16Array]",kk="[object Int32Array]",_k="[object Uint8Array]",bk="[object Uint8ClampedArray]",wk="[object Uint16Array]",Ik="[object Uint32Array]",De={};De[yk]=De[Sk]=De[Ek]=De[Tk]=De[kk]=De[_k]=De[bk]=De[wk]=De[Ik]=!0;De[nk]=De[ik]=De[gk]=De[sk]=De[vk]=De[ak]=De[ok]=De[ck]=De[dk]=De[lk]=De[uk]=De[hk]=De[pk]=De[mk]=De[fk]=!1;function Ck(t){return br(t)&&Nf(t.length)&&!!De[ki(t)]}function vu(t){return function(e){return t(e)}}var Lf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Oa=Lf&&typeof module=="object"&&module&&!module.nodeType&&module,Pk=Oa&&Oa.exports===Lf,Bd=Pk&&Pf.process,Rk=function(){try{var t=Oa&&Oa.require&&Oa.require("util").types;return t||Bd&&Bd.binding&&Bd.binding("util")}catch{}}();const cs=Rk;var zh=cs&&cs.isTypedArray,Ak=zh?vu(zh):Ck;const sd=Ak;var Mk=Object.prototype,Dk=Mk.hasOwnProperty;function xf(t,e){var r=On(t),n=!r&&bc(t),i=!r&&!n&&os(t),s=!r&&!n&&!i&&sd(t),a=r||n||i||s,o=a?$T(t.length,String):[],d=o.length;for(var h in t)(e||Dk.call(t,h))&&!(a&&(h=="length"||i&&(h=="offset"||h=="parent")||s&&(h=="buffer"||h=="byteLength"||h=="byteOffset")||Of(h,d)))&&o.push(h);return o}var Ok=Object.prototype;function ad(t){var e=t&&t.constructor,r=typeof e=="function"&&e.prototype||Ok;return t===r}function Ff(t,e){return function(r){return t(e(r))}}var Nk=Ff(Object.keys,Object);const Lk=Nk;var xk=Object.prototype,Fk=xk.hasOwnProperty;function Vf(t){if(!ad(t))return Lk(t);var e=[];for(var r in Object(t))Fk.call(t,r)&&r!="constructor"&&e.push(r);return e}function Ja(t){return t!=null&&Nf(t.length)&&!fu(t)}function yu(t){return Ja(t)?xf(t):Vf(t)}function Vk(t,e){return t&&$a(e,yu(e),t)}function Uk(t){var e=[];if(t!=null)for(var r in Object(t))e.push(r);return e}var Bk=Object.prototype,jk=Bk.hasOwnProperty;function Hk(t){if(!pr(t))return Uk(t);var e=ad(t),r=[];for(var n in t)n=="constructor"&&(e||!jk.call(t,n))||r.push(n);return r}function Ga(t){return Ja(t)?xf(t,!0):Hk(t)}function Wk(t,e){return t&&$a(e,Ga(e),t)}var Uf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Kh=Uf&&typeof module=="object"&&module&&!module.nodeType&&module,$k=Kh&&Kh.exports===Uf,Yh=$k?mr.Buffer:void 0,Qh=Yh?Yh.allocUnsafe:void 0;function Bf(t,e){if(e)return t.slice();var r=t.length,n=Qh?Qh(r):new t.constructor(r);return t.copy(n),n}function jf(t,e){var r=-1,n=t.length;for(e||(e=Array(n));++r<n;)e[r]=t[r];return e}function Jk(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 Hf(){return[]}var Gk=Object.prototype,qk=Gk.propertyIsEnumerable,Xh=Object.getOwnPropertySymbols,zk=Xh?function(t){return t==null?[]:(t=Object(t),Jk(Xh(t),function(e){return qk.call(t,e)}))}:Hf;const Su=zk;function Kk(t,e){return $a(t,Su(t),e)}function Wf(t,e){for(var r=-1,n=e.length,i=t.length;++r<n;)t[i+r]=e[r];return t}var Yk=Ff(Object.getPrototypeOf,Object);const Eu=Yk;var Qk=Object.getOwnPropertySymbols,Xk=Qk?function(t){for(var e=[];t;)Wf(e,Su(t)),t=Eu(t);return e}:Hf;const $f=Xk;function Zk(t,e){return $a(t,$f(t),e)}function Jf(t,e,r){var n=e(t);return On(t)?n:Wf(n,r(t))}function bl(t){return Jf(t,yu,Su)}function e0(t){return Jf(t,Ga,$f)}var t0=bi(mr,"DataView");const wl=t0;var r0=bi(mr,"Promise");const Il=r0;var n0=bi(mr,"Set");const Cl=n0;var i0=bi(mr,"WeakMap");const Pl=i0;var Zh="[object Map]",s0="[object Object]",ep="[object Promise]",tp="[object Set]",rp="[object WeakMap]",np="[object DataView]",a0=_i(wl),o0=_i(Fa),c0=_i(Il),d0=_i(Cl),l0=_i(Pl),Yn=ki;(wl&&Yn(new wl(new ArrayBuffer(1)))!=np||Fa&&Yn(new Fa)!=Zh||Il&&Yn(Il.resolve())!=ep||Cl&&Yn(new Cl)!=tp||Pl&&Yn(new Pl)!=rp)&&(Yn=function(t){var e=ki(t),r=e==s0?t.constructor:void 0,n=r?_i(r):"";if(n)switch(n){case a0:return np;case o0:return Zh;case c0:return ep;case d0:return tp;case l0:return rp}return e});const ds=Yn;var u0=Object.prototype,h0=u0.hasOwnProperty;function p0(t){var e=t.length,r=new t.constructor(e);return e&&typeof t[0]=="string"&&h0.call(t,"index")&&(r.index=t.index,r.input=t.input),r}var m0=mr.Uint8Array;const wc=m0;function Tu(t){var e=new t.constructor(t.byteLength);return new wc(e).set(new wc(t)),e}function f0(t,e){var r=e?Tu(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.byteLength)}var g0=/\w*$/;function v0(t){var e=new t.constructor(t.source,g0.exec(t));return e.lastIndex=t.lastIndex,e}var ip=Dn?Dn.prototype:void 0,sp=ip?ip.valueOf:void 0;function y0(t){return sp?Object(sp.call(t)):{}}function Gf(t,e){var r=e?Tu(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.length)}var S0="[object Boolean]",E0="[object Date]",T0="[object Map]",k0="[object Number]",_0="[object RegExp]",b0="[object Set]",w0="[object String]",I0="[object Symbol]",C0="[object ArrayBuffer]",P0="[object DataView]",R0="[object Float32Array]",A0="[object Float64Array]",M0="[object Int8Array]",D0="[object Int16Array]",O0="[object Int32Array]",N0="[object Uint8Array]",L0="[object Uint8ClampedArray]",x0="[object Uint16Array]",F0="[object Uint32Array]";function V0(t,e,r){var n=t.constructor;switch(e){case C0:return Tu(t);case S0:case E0:return new n(+t);case P0:return f0(t,r);case R0:case A0:case M0:case D0:case O0:case N0:case L0:case x0:case F0:return Gf(t,r);case T0:return new n;case k0:case w0:return new n(t);case _0:return v0(t);case b0:return new n;case I0:return y0(t)}}var ap=Object.create,U0=function(){function t(){}return function(e){if(!pr(e))return{};if(ap)return ap(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();const B0=U0;function qf(t){return typeof t.constructor=="function"&&!ad(t)?B0(Eu(t)):{}}var j0="[object Map]";function H0(t){return br(t)&&ds(t)==j0}var op=cs&&cs.isMap,W0=op?vu(op):H0;const $0=W0;var J0="[object Set]";function G0(t){return br(t)&&ds(t)==J0}var cp=cs&&cs.isSet,q0=cp?vu(cp):G0;const z0=q0;var K0=1,Y0=2,Q0=4,zf="[object Arguments]",X0="[object Array]",Z0="[object Boolean]",e_="[object Date]",t_="[object Error]",Kf="[object Function]",r_="[object GeneratorFunction]",n_="[object Map]",i_="[object Number]",Yf="[object Object]",s_="[object RegExp]",a_="[object Set]",o_="[object String]",c_="[object Symbol]",d_="[object WeakMap]",l_="[object ArrayBuffer]",u_="[object DataView]",h_="[object Float32Array]",p_="[object Float64Array]",m_="[object Int8Array]",f_="[object Int16Array]",g_="[object Int32Array]",v_="[object Uint8Array]",y_="[object Uint8ClampedArray]",S_="[object Uint16Array]",E_="[object Uint32Array]",Ce={};Ce[zf]=Ce[X0]=Ce[l_]=Ce[u_]=Ce[Z0]=Ce[e_]=Ce[h_]=Ce[p_]=Ce[m_]=Ce[f_]=Ce[g_]=Ce[n_]=Ce[i_]=Ce[Yf]=Ce[s_]=Ce[a_]=Ce[o_]=Ce[c_]=Ce[v_]=Ce[y_]=Ce[S_]=Ce[E_]=!0;Ce[t_]=Ce[Kf]=Ce[d_]=!1;function Bo(t,e,r,n,i,s){var a,o=e&K0,d=e&Y0,h=e&Q0;if(r&&(a=i?r(t,n,i,s):r(t)),a!==void 0)return a;if(!pr(t))return t;var p=On(t);if(p){if(a=p0(t),!o)return jf(t,a)}else{var m=ds(t),g=m==Kf||m==r_;if(os(t))return Bf(t,o);if(m==Yf||m==zf||g&&!i){if(a=d||g?{}:qf(t),!o)return d?Zk(t,Wk(a,t)):Kk(t,Vk(a,t))}else{if(!Ce[m])return i?t:{};a=V0(t,m,o)}}s||(s=new kr);var v=s.get(t);if(v)return v;s.set(t,a),z0(t)?t.forEach(function(P){a.add(Bo(P,e,r,P,t,s))}):$0(t)&&t.forEach(function(P,D){a.set(D,Bo(P,e,r,D,t,s))});var I=h?d?e0:bl:d?Ga:yu,A=p?void 0:I(t);return BT(A||t,function(P,D){A&&(D=P,P=t[D]),Af(a,D,Bo(P,e,r,D,t,s))}),a}var T_=1,k_=4;function ku(t){return Bo(t,T_|k_)}var __="[object Symbol]";function b_(t){return typeof t=="symbol"||br(t)&&ki(t)==__}var w_=Object.defineProperty,I_=(t,e)=>{for(var r in e)w_(t,r,{get:e[r],enumerable:!0})},C_={};I_(C_,{permissions:()=>P_,theme:()=>R_});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||{}),P_={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},R_={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}},Qf="hXgU8Wc8pwuGNq9ms5q9Hh",dp;typeof process!="undefined"&&(dp=process==null?void 0:process.env)!=null&&dp.FLAGSMITH_ENVIRONMENT_KEY&&(Qf={}.FLAGSMITH_ENVIRONMENT_KEY);function A_(t=[]){const e={};return t.forEach(r=>{e[r.feature.name]={enabled:r.enabled,value:r.feature_state_value}}),e}var M_=class{constructor(t=Qf){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 kc.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=A_(h.data.flags||[])}catch{}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 M_,Xf=[-2,-1,0,1,2],D_=[0,1,2,3,4];function O_(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 N_=(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)]},L_=(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]},x_=(t,e,r)=>{const n=i=>i.toString(16).padStart(2,"0");return`#${n(t)}${n(e)}${n(r)}`},Zf=(t,e=Xf,r=.4)=>{const n=[],[i,s,a]=O_(t),[o,d,h]=L_(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]=N_(o,d,D/100);n.push(x_(N,J,C))}return n},lp={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"}},F_=t=>{const[e,r,n,i,s]=Zf(t,Xf);return{300:e,400:r,500:n,600:i,700:s}},V_=t=>{if(t==="#FFFFFF")return lp.light.background;if(t==="#000000")return lp.dark.background;const[e,r,n,i,s]=Zf(t,D_);return{1e3:e,900:r,800:n,700:i,600:s}},U_={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:F_("#2160FD"),background:V_("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function eg(){return ku(U_)}var B_={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:eg(),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 j_(){return ku(B_)}var H_={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:eg(),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 _u(){return ku(H_)}var W_=/\s/;function $_(t){for(var e=t.length;e--&&W_.test(t.charAt(e)););return e}var J_=/^\s+/;function G_(t){return t&&t.slice(0,$_(t)+1).replace(J_,"")}var up=0/0,q_=/^[-+]0x[0-9a-f]+$/i,z_=/^0b[01]+$/i,K_=/^0o[0-7]+$/i,Y_=parseInt;function hp(t){if(typeof t=="number")return t;if(b_(t))return up;if(pr(t)){var e=typeof t.valueOf=="function"?t.valueOf():t;t=pr(e)?e+"":e}if(typeof t!="string")return t===0?t:+t;t=G_(t);var r=z_.test(t);return r||K_.test(t)?Y_(t.slice(2),r?2:8):q_.test(t)?up:+t}function tg(t){return t}function Q_(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 X_=800,Z_=16,eb=Date.now;function tb(t){var e=0,r=0;return function(){var n=eb(),i=Z_-(n-r);if(r=n,i>0){if(++e>=X_)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function rb(t){return function(){return t}}var nb=_c?function(t,e){return _c(t,"toString",{configurable:!0,enumerable:!1,value:rb(e),writable:!0})}:tg;const ib=nb;var sb=tb(ib);const ab=sb;var pp=Math.max;function ob(t,e,r){return e=pp(e===void 0?t.length-1:e,0),function(){for(var n=arguments,i=-1,s=pp(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),Q_(t,this,o)}}function cb(t,e){return ab(ob(t,e,tg),t+"")}function db(t,e,r){if(!pr(r))return!1;var n=typeof e;return(n=="number"?Ja(r)&&Of(e,r.length):n=="string"&&e in r)?Wa(r[e],t):!1}function lb(t){return cb(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&&db(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 ub="[object Object]",hb=Function.prototype,pb=Object.prototype,rg=hb.toString,mb=pb.hasOwnProperty,fb=rg.call(Object);function gb(t){if(!br(t)||ki(t)!=ub)return!1;var e=Eu(t);if(e===null)return!0;var r=mb.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&rg.call(r)==fb}var vb="__lodash_hash_undefined__";function yb(t){return this.__data__.set(t,vb),this}function Sb(t){return this.__data__.has(t)}function Ic(t){var e=-1,r=t==null?0:t.length;for(this.__data__=new wi;++e<r;)this.add(t[e])}Ic.prototype.add=Ic.prototype.push=yb;Ic.prototype.has=Sb;function Eb(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 Tb(t,e){return t.has(e)}var kb=1,_b=2;function ng(t,e,r,n,i,s){var a=r&kb,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&_b?new Ic: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(!Eb(e,function(D,N){if(!Tb(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 bb(t){var e=-1,r=Array(t.size);return t.forEach(function(n,i){r[++e]=[i,n]}),r}function wb(t){var e=-1,r=Array(t.size);return t.forEach(function(n){r[++e]=n}),r}var Ib=1,Cb=2,Pb="[object Boolean]",Rb="[object Date]",Ab="[object Error]",Mb="[object Map]",Db="[object Number]",Ob="[object RegExp]",Nb="[object Set]",Lb="[object String]",xb="[object Symbol]",Fb="[object ArrayBuffer]",Vb="[object DataView]",mp=Dn?Dn.prototype:void 0,jd=mp?mp.valueOf:void 0;function Ub(t,e,r,n,i,s,a){switch(r){case Vb:if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case Fb:return!(t.byteLength!=e.byteLength||!s(new wc(t),new wc(e)));case Pb:case Rb:case Db:return Wa(+t,+e);case Ab:return t.name==e.name&&t.message==e.message;case Ob:case Lb:return t==e+"";case Mb:var o=bb;case Nb:var d=n&Ib;if(o||(o=wb),t.size!=e.size&&!d)return!1;var h=a.get(t);if(h)return h==e;n|=Cb,a.set(t,e);var p=ng(o(t),o(e),n,i,s,a);return a.delete(t),p;case xb:if(jd)return jd.call(t)==jd.call(e)}return!1}var Bb=1,jb=Object.prototype,Hb=jb.hasOwnProperty;function Wb(t,e,r,n,i,s){var a=r&Bb,o=bl(t),d=o.length,h=bl(e),p=h.length;if(d!=p&&!a)return!1;for(var m=d;m--;){var g=o[m];if(!(a?g in e:Hb.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 $b=1,fp="[object Arguments]",gp="[object Array]",io="[object Object]",Jb=Object.prototype,vp=Jb.hasOwnProperty;function Gb(t,e,r,n,i,s){var a=On(t),o=On(e),d=a?gp:ds(t),h=o?gp:ds(e);d=d==fp?io:d,h=h==fp?io:h;var p=d==io,m=h==io,g=d==h;if(g&&os(t)){if(!os(e))return!1;a=!0,p=!1}if(g&&!p)return s||(s=new kr),a||sd(t)?ng(t,e,r,n,i,s):Ub(t,e,d,r,n,i,s);if(!(r&$b)){var v=p&&vp.call(t,"__wrapped__"),I=m&&vp.call(e,"__wrapped__");if(v||I){var A=v?t.value():t,P=I?e.value():e;return s||(s=new kr),i(A,P,r,n,s)}}return g?(s||(s=new kr),Wb(t,e,r,n,i,s)):!1}function ig(t,e,r,n,i){return t===e?!0:t==null||e==null||!br(t)&&!br(e)?t!==t&&e!==e:Gb(t,e,r,n,ig,i)}function qb(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 zb=qb();const Kb=zb;var Yb=function(){return mr.Date.now()};const Hd=Yb;var Qb="Expected a function",Xb=Math.max,Zb=Math.min;function Yr(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(Qb);e=hp(e)||0,pr(r)&&(p=!!r.leading,m="maxWait"in r,s=m?Xb(hp(r.maxWait)||0,e):s,g="trailing"in r?!!r.trailing:g);function v(W){var oe=n,se=i;return n=i=void 0,h=W,a=t.apply(se,oe),a}function I(W){return h=W,o=setTimeout(D,e),p?v(W):a}function A(W){var oe=W-d,se=W-h,Oe=e-oe;return m?Zb(Oe,s-se):Oe}function P(W){var oe=W-d,se=W-h;return d===void 0||oe>=e||oe<0||m&&se>=s}function D(){var W=Hd();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(Hd())}function G(){var W=Hd(),oe=P(W);if(n=arguments,i=this,d=W,oe){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 Rl(t,e,r){(r!==void 0&&!Wa(t[e],r)||r===void 0&&!(e in t))&&gu(t,e,r)}function ew(t){return br(t)&&Ja(t)}function Al(t,e){if(!(e==="constructor"&&typeof t[e]=="function")&&e!="__proto__")return t[e]}function tw(t){return $a(t,Ga(t))}function rw(t,e,r,n,i,s,a){var o=Al(t,r),d=Al(e,r),h=a.get(d);if(h){Rl(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&&os(d),I=!g&&!v&&sd(d);p=d,g||v||I?On(o)?p=o:ew(o)?p=jf(o):v?(m=!1,p=Bf(d,!0)):I?(m=!1,p=Gf(d,!0)):p=[]:gb(d)||bc(d)?(p=o,bc(o)?p=tw(o):(!pr(o)||fu(o))&&(p=qf(d))):m=!1}m&&(a.set(d,p),i(p,d,n,s,a),a.delete(d)),Rl(t,r,p)}function sg(t,e,r,n,i){t!==e&&Kb(e,function(s,a){if(i||(i=new kr),pr(s))rw(t,e,a,r,sg,n,i);else{var o=n?n(Al(t,a),s,a+"",t,e,i):void 0;o===void 0&&(o=s),Rl(t,a,o)}},Ga)}var nw="[object Map]",iw="[object Set]",sw=Object.prototype,aw=sw.hasOwnProperty;function ow(t){if(t==null)return!0;if(Ja(t)&&(On(t)||typeof t=="string"||typeof t.splice=="function"||os(t)||sd(t)||bc(t)))return!t.length;var e=ds(t);if(e==nw||e==iw)return!t.size;if(ad(t))return!Vf(t).length;for(var r in t)if(aw.call(t,r))return!1;return!0}function cw(t,e){return ig(t,e)}var dw=lb(function(t,e,r){sg(t,e,r)});const gn=dw;var Ml=(t=>(t.PARTICIPANT="PARTICIPANT",t.PEER="PEER",t.CLIENT="CLIENT",t))(Ml||{});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 jo(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 ag(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 lw(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 og(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"?og(t[n],s,r):["number","string","boolean"].includes(typeof t[n])&&(r[s]=t[n])}),r}function yp(t,e,r={},n=""){const i={};try{const s=JSON.stringify(r),a=JSON.parse(s),o=og(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 ag(t)&&console.error(h,{log:r,flattened:d}),new Error(h)}return JSON.parse(d)}catch(s){const a=jo(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 Ua="chrome",cg="opera",dg="firefox",lg="iexplorer",ug="safari",hg="nwjs",pg="electron",mg="react-native",bu="unknown",Cc={Chrome:Ua,Chromium:Ua,Opera:cg,Firefox:dg,"Internet Explorer":lg,Safari:ug};function uw(){const{userAgent:t}=navigator,e={name:bu,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=Ua,e.version=r)}else e.name=Ua,e.version=t.match(/Chrome\/([\d.]+)/)[1];return e}function hw(){const{userAgent:t}=navigator;if(t.match(/Electron/)){const e=t.match(/Electron\/([\d.]+)/)[1];return{name:pg,version:e}}return null}function pw(){const{userAgent:t}=navigator;if(t.match(/JitsiMeetNW/)){const e=t.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:hg,version:e}}}function mw(){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:mg,version:e}}function fw(t){let e;const r=[mw,hw,pw];for(let i=0;i<r.length;i+=1)if(e=r[i](),e)return e;const n=t.getBrowserName();return n in Cc?{name:Cc[n],version:t.getBrowserVersion()}:(e=uw(),e||{name:bu,version:void 0})}class gw{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=Mm.getParser(navigator.userAgent),typeof e=="undefined"){const i=fw(this._bowser);r=i.name,n=i.version}else e.name in Cc?(r=Cc[e.name],n=e.version):(r=bu,n=void 0);this._name=r,this._version=n}getName(){return this._name}isChrome(){return this._name===Ua}isOpera(){return this._name===cg}isFirefox(){return this._name===dg}isIExplorer(){return this._name===lg}isSafari(){return this._name===ug}isNWJS(){return this._name===hg}isElectron(){return this._name===pg}isReactNative(){return this._name===mg||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 vw extends gw{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{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 Ee=new vw,yw={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},xs={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"},Sw={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 Pc(t,e){const r=t.getValue("overrides");return r&&r[e]?r[e]:!1}function Ew({baseURI:t}){return t!=null&&t.includes("preprod.dyte")?Da.PREPROD:t!=null&&t.includes("devel.dyte")?Da.DEVEL:Da.PROD}function ns({servicePrefix:t,baseURI:e}){return`${t}.${e}`}function fg(t){const e=t.getValue("baseURI");return{location:ns({servicePrefix:"location",baseURI:e}),locationLegacy:ns({servicePrefix:"location-legacy",baseURI:e}),daCollector:ns({servicePrefix:"da-collector",baseURI:e})}}const Tw='<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>',kw='<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>',so=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 _w(t){const e=B({},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 bw{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,_w(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 hi=new bw,ge=class{static get logsEndpoint(){const t=hi.getContext(ge.meetingMetadata.peerId);return`https://${ns({servicePrefix:"api-silos",baseURI:t.getValue("baseURI")})}/otel/logs`}static resetPeerId(t){ge.meetingMetadata.peerId=t}static init(t,e){const r=t.getValue("peerId");ge.tracingEnabled=e,ge.meetingMetadata.peerId=r,ge.meetingMetadata.sdkVersion=t.getValue("sdkVersion"),ge.meetingMetadata.deviceInfo=Ee.getDeviceInfo(),ge.meetingMetadata.visitedUrl=!navigator.isReactNative&&typeof window!="undefined"&&window.location.href,navigator.isReactNative||document.addEventListener("visibilitychange",ge.processCachedLogs),ge.logsProcessorTimer=setInterval(ge.processCachedLogs,ge.logsProcessingInterval),e&&(ge.initialized=!0)}static trace(t,e=void 0){return(r,n,i)=>{const s=i.value;return i.value=function(...a){if(!ge.initialized||navigator.isReactNative||!ge.tracingEnabled||Q.hasFeature(ie.SKIP_OTEL_TRACES))return s.apply(this,a);ge.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&&ge.addLogInCurrentSpan("info",`${t}_timing`,{execTime:h-o,country:ge.location.country})}).catch(()=>{const h=performance.now();ge.addLogInCurrentSpan("info",`${t}_timing`,{execTime:h-o})}),d},i}}static injectContext(t){var e;const r=Ei().replace(/-/g,"").substring(0,16),n=(e=ge.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:jo(r.error)});const i=hi.getContext(ge.meetingMetadata.peerId);if(ag(i)&&(ow(r)?console[t]("DyteInternalLogs:: ",t,e):console[t]("DyteInternalLogs:: ",t,e,r)),!!lw(t))try{const s=yp(i,e,r,"metadata"),a=new Date,o=Z(B({message:e,level:t},s),{loggedAt:a.toISOString(),loggedAtTzOffset:a.getTimezoneOffset()});n?ge.sendOtelLogsToNewRelic([o]):ge.logsCache.push(o)}catch(s){ge.addLogInCurrentSpan("error","opentelemetry::addLogInCurrentSpan_failed",{error:jo(s)})}}static sendOtelLogsToNewRelic(t){const e=hi.getContext(ge.meetingMetadata.peerId);kc.post(ge.logsEndpoint,{meetingMetadata:yp(e,"sendOtelLogsToNewRelic",ge.meetingMetadata,"meetingMetadata"),serviceName:e.getValue("sdkName"),logs:t}).catch(r=>{ge.addLogInCurrentSpan("error","opentelemetry::sendOtelLogToNewRelic_failed",{error:jo(r)}),ge.logsCache.push(...t)})}static processCachedLogs(){const t=ge.logsCache.splice(0,25);t!=null&&t.length&&ge.sendOtelLogsToNewRelic(t)}static destruct(){clearInterval(ge.logsProcessorTimer),ge.processCachedLogs(),navigator.isReactNative||document.removeEventListener("visibilitychange",ge.processCachedLogs)}};let y=ge;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 ww=()=>{!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")}))},Iw={"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"},Ho={"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(Ho).forEach(t=>{Ho[t]=`{${Iw[t.slice(0,2)]}} ${Ho[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}]: ${Ho[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=hi.getContext(hi.getMostRecentPeerId());if(s){const a=s.getValue("onError");try{a(this)}catch{}}}catch{}}}function ao(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 Sp(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){ao(this,e,r,a)}}),s&&(t.set=function(a){try{return s.apply(this,[a])}catch(o){ao(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=>{ao(this,e,r,a)}):s}catch(s){ao(this,e,r,s)}},t}function Cw(t,e){return(r,n,i)=>{if(i)return Sp(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,Sp(a,t,e))}}}const yt=t=>Cw(Error,t);function Pw(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 vn,yn;const gg=class extends mt.EventEmitter{constructor(){super(),T(this,vn,void 0),T(this,yn,void 0),f(this,"asyncPromiseTimeout"),S(this,vn,new Map),S(this,yn,new Map),this.asyncPromiseTimeout=8e3}emitAsync(t,...e){return u(this,null,function*(){c(this,vn).set(t,[]);const r=c(this,yn).get(t).map(()=>new Promise(n=>{c(this,vn).get(t).push(n)}));cS(gg.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,vn).delete(t)})}onAsync(t,e){const r=c(this,vn),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,yn).get(t)||c(this,yn).set(t,[]),c(this,yn).get(t).push(n),super.on(t,n)}reset(){S(this,vn,new Map),S(this,yn,new Map),super.removeAllListeners()}};let Rw=gg;vn=new WeakMap,yn=new WeakMap;const w=new Rw;function Aw(){Ee.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 b=(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))(b||{});class ps extends mt.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{}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{}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 zt extends mt.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{}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{}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 Mw(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 Ep=1080,Tp=1920,Dw=(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 ar,ua,wt,or,Je,Sr,Sn,Nt,rt,ha,pa,En,ma;const vg=class extends zt{constructor(t,e,r,n){super(),T(this,ar,void 0),T(this,ua,void 0),T(this,wt,void 0),T(this,or,void 0),T(this,Je,{height:Ep,width:Tp}),T(this,Sr,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"}),T(this,Sn,void 0),T(this,Nt,{}),T(this,rt,void 0),T(this,ha,void 0),T(this,pa,void 0),T(this,En,void 0),T(this,ma,!1),f(this,"cleanupEventListeners",()=>{c(this,ua).unsubscribe("stageStatus",this.handlePipMediaControls),c(this,rt).removeListener("videoUpdate",this.onSelfVideoUpdateListener),c(this,rt).removeListener("audioUpdate",this.onSelfAudioUpdateListener),c(this,rt).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,rt).videoEnabled?c(this,rt).disableVideo():c(this,rt).enableVideo(),this.emit("cameraToggled")),i==="MIC"&&(c(this,rt).audioEnabled?c(this,rt).disableAudio():c(this,rt).enableAudio(),this.emit("micToggled")),i==="END"&&(w.emit(b.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,En)==="active"){this.disable(!0);return}c(this,Nt)!==void 0&&this.paintCanvas(),c(this,Sn)!==void 0&&S(this,Sn,requestAnimationFrame(()=>this.animate()))}),f(this,"disable",(i=!1)=>{S(this,En,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(c(this,Sn)),i!==!0&&document.body.removeChild(c(this,wt)),S(this,Sn,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()}),S(this,ua,t),S(this,En,"idle"),S(this,rt,e),S(this,Sr,{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 so(Tw),n=yield so(kw)}catch{}return new vg(t,e,r,n)})}setupIcon(t,e){return u(this,null,function*(){switch(t){case"handRaise":S(this,pa,e);break;case"pin":S(this,ha,e);break}})}overrideIcon(t,e){return u(this,null,function*(){switch(t){case"handRaise":S(this,pa,yield so(e));break;case"pin":S(this,ha,yield so(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,wt,document.createElement("div")),c(this,wt).style.width="0.1px",c(this,wt).style.height="0.1px",c(this,wt).style.overflow="hidden",c(this,wt).style.position="absolute",c(this,wt).style.bottom="0",c(this,wt).style.right="0",c(this,wt).style.opacity="0",c(this,wt).appendChild(c(this,or))}setupEventListeners(){c(this,ua).subscribe("stageStatus",this.handlePipMediaControls),c(this,rt).addListener("videoUpdate",this.onSelfVideoUpdateListener),c(this,rt).addListener("audioUpdate",this.onSelfAudioUpdateListener),c(this,rt).addListener("roomLeft",()=>this.disable())}createCanvas(){const t=document.createElement("canvas");t.height=c(this,Je).height,t.width=c(this,Je).width,S(this,ar,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,rt).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||c(this,rt).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,ar)===void 0)return;const i=c(this,ar).getContext("2d"),s=c(this,ar).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,Sr).videoBackground:c(this,Sr).background,i.strokeStyle=c(this,Sr).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,Sr).brand,i.fill(),A?(i.clip(),i.drawImage(A,D-P,N-P,P*2,P*2),i.restore()):I&&(i.fillStyle=c(this,Sr).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,ar).getContext("2d");m.save(),m.fillStyle=c(this,Sr).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,Sr).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,ha)),t.handRaised&&h(c(this,pa))}drawTile(t,e,r){var n,i;if(c(this,ar)===void 0)return;const s=c(this,ar).getContext("2d"),a=this.getSources();let o=0,d=0;for(;o<c(this,Je).height-5;){let h=0;for(;h<c(this,Je).width-5&&d<r;){if((n=a[d])!=null&&n.enabled){const p=a[d].element,[m,g,v,I,A,P,D,N]=Dw(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,Je).width,c(this,Je).height];case 2:return[Math.floor(c(this,Je).width/2),c(this,Je).height];case 3:case 4:return[Math.floor(c(this,Je).width/2),Math.floor(c(this,Je).height/2)];case 5:case 6:return[Math.floor(c(this,Je).width/3),Math.floor(c(this,Je).height/2)];case 7:case 8:case 9:return[Math.floor(c(this,Je).width/3),Math.floor(c(this,Je).height/3)];default:return[Math.floor(c(this,Je).width/3),Math.floor(c(this,Je).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,ma,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),c(this,wt))try{document.body.removeChild(c(this,wt))}catch{}this.removeAllSources(),S(this,ar,void 0),S(this,or,void 0),S(this,Sn,void 0)}init({height:t,width:e}={}){if(c(this,ma))return;S(this,ma,!0),this.createCanvas(),this.setupMediaSessionEvents();const r=document.createElement("video");S(this,Je,{height:t!=null?t:Ep,width:e!=null?e:Tp}),r.height=c(this,Je).height,r.width=c(this,Je).width,r.autoplay=!0,r.muted=!0,r.srcObject=c(this,ar).captureStream(24),S(this,or,r),c(this,or).onloadedmetadata=()=>{try{this.emit("pipStarted"),c(this,or).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch{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?Mw(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]=B(B({},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,En,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",c(this,rt).videoEnabled),this.updateMediaSession("MIC",c(this,rt).audioEnabled),document.body.appendChild(c(this,wt)),S(this,Sn,requestAnimationFrame(()=>this.animate())),c(this,or).onloadedmetadata=()=>{c(this,or).requestPictureInPicture().then(()=>{S(this,En,"active")})},c(this,or).readyState===4&&c(this,or).requestPictureInPicture().then(()=>{S(this,En,"active")})}};let Ow=vg;ar=new WeakMap,ua=new WeakMap,wt=new WeakMap,or=new WeakMap,Je=new WeakMap,Sr=new WeakMap,Sn=new WeakMap,Nt=new WeakMap,rt=new WeakMap,ha=new WeakMap,pa=new WeakMap,En=new WeakMap,ma=new WeakMap;var Gt;(function(t){t[t.PUBLISHER=0]="PUBLISHER",t[t.SUBSCRIBER=1]="SUBSCRIBER"})(Gt||(Gt={}));var xt;(function(t){t[t.AUDIO=0]="AUDIO",t[t.VIDEO=1]="VIDEO"})(xt||(xt={}));class Nw 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 Lw=new Nw;class xw 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 Fw=new xw;class Vw extends E{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new Vw;class Uw extends E{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",Gt]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const fr=new Uw;class Bw 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:()=>fr},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8}])}}const yg=new Bw;class jw extends E{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>fr},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8}])}}const wu=new jw;class Hw extends E{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>fr}])}}const Sg=new Hw;class Ww extends E{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>fr}])}}new Ww;class $w 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 Jw=new $w;class Gw 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 qw=new Gw;class zw 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 zw;class Kw 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 Kw;class Yw extends E{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",xt]},{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 qa=new Yw;class Qw extends E{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>qa},{no:3,name:"producer_track",kind:"message",T:()=>qw}])}}const Xw=new Qw;class Zw extends E{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>Xw}}])}}const Eg=new Zw;class eI extends E{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>_p},{no:2,name:"receiver",kind:"message",T:()=>_p}])}}const Tg=new eI;class tI extends E{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>Lw},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>Fw}])}}const kp=new tI;class rI extends E{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>kp},{no:2,name:"video",kind:"message",T:()=>kp}])}}const _p=new rI;class nI 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 iI=new nI;class sI 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 aI=new sI;class oI 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:()=>aI},{no:9,name:"capabilities",kind:"message",T:()=>Tg}])}}const kg=new oI;class cI extends E{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const _g=new cI;class dI extends E{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const bg=new dI;class lI 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 lI;class uI 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:()=>iI}])}}const Iu=new uI;class hI extends E{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>Iu}])}}new hI;class pI 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:()=>fr},{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 wg=new pI;class mI extends E{constructor(){super("media.edge.SelectedPeersRequest",[])}}new mI;class fI extends E{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Ig=new fI;class gI 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 Cn=new gI;class vI 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 Rc=new vI;class yI extends E{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>fr}])}}const Cg=new yI;class SI 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:()=>fr}])}}const Pg=new SI;class EI extends E{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Rg=new EI;class TI extends E{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const Cu=new TI;class kI 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 Ag=new kI;class _I 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 Mg=new _I;class bI 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 Dg=new bI;class wI 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 II=new wI;class CI 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 PI=new CI;class RI extends E{constructor(){super("media.edge.EmptyResponse",[])}}new RI;class AI 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:()=>qa},{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:()=>Tg}])}}const Og=new AI;class MI 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 Dl=new MI;class DI 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 OI=new DI;class NI extends E{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>OI}])}}const bp=new NI;class LI extends E{constructor(){super("media.edge.PeerJoinResponse",[])}}new LI;class xI extends E{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>II},{no:2,name:"participants",kind:"message",repeat:1,T:()=>Og},{no:3,name:"selected_peers",kind:"message",T:()=>Dl},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const Ac=new xI;class FI extends E{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const Ng=new FI;class VI extends E{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Eg}])}}new VI;class UI extends E{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Eg},{no:3,name:"description",kind:"message",T:()=>fr}])}}const Lg=new UI;class BI 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:()=>fr}])}}const xg=new BI;class jI extends E{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>Jw}])}}new jI;class HI 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 HI;class WI extends E{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new WI;class $I extends E{constructor(){super("media.edge.ProducerToggleResponse",[])}}new $I;class JI extends E{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new JI;class GI extends E{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>fr}])}}const Fg=new GI;class qI extends E{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>fr}])}}new qI;class zI extends E{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new zI;class KI extends E{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Vg=new KI;class YI extends E{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Ug=new YI;class QI extends E{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Bg=new QI;class XI extends E{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const jg=new XI;class ZI extends E{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Hg=new ZI;class eC extends E{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>Og}])}}const wp=new eC;class tC extends E{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const Ip=new tC;class rC extends E{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>Ip},{no:3,name:"screenshare",kind:"message",T:()=>Ip}])}}const nC=new rC;class iC extends E{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>wu},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>nC}])}}new iC;class sC extends E{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>qa}])}}const Wg=new sC;class aC extends E{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>qa},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const Ol=new aC;class oC extends E{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>qa}])}}const $g=new oC;class cC extends E{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Mc=new cC;class dC extends E{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Cp=new dC;class lC extends E{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new lC;class uC extends E{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new uC;class hC extends E{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new hC;class pC 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 pC;class mC extends E{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new mC;class fC extends E{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new fC;class gC 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 Wd=new gC;class vC 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 vC;class yC 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 SC=new yC;var pi;(function(t){t[t.BROWSER=0]="BROWSER",t[t.TRACK=1]="TRACK",t[t.COMPOSITE=2]="COMPOSITE"})(pi||(pi={}));var Jr;(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"})(Jr||(Jr={}));var Nl;(function(t){t[t.NONE=0]="NONE",t[t.RECORDER=1]="RECORDER",t[t.LIVESTREAMER=2]="LIVESTREAMER"})(Nl||(Nl={}));var Ll;(function(t){t[t.PEERS=0]="PEERS",t[t.ROOMS=1]="ROOMS"})(Ll||(Ll={}));var Dc;(function(t){t[t.HIVE=0]="HIVE",t[t.CHAT=1]="CHAT",t[t.PING=2]="PING"})(Dc||(Dc={}));class EC 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 TC=new EC;class kC 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",Jr,"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:()=>TC}])}}const od=new kC;class _C extends E{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>od}])}}const $i=new _C;class bC 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",Jr,"STAGE_TYPE_"]}])}}const Pp=new bC;class wC 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 IC=new wC;class CC extends E{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>od}])}}const $d=new CC;class PC extends E{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const Rp=new PC;class RC 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:()=>MC},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const Jg=new RC;class AC 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",pi]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const MC=new AC;class DC extends E{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>Jg}])}}const Ap=new DC;class OC extends E{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const Gg=new OC;class NC 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 NC;class LC extends E{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>od},{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",Dc,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const xC=new LC;class FC extends E{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>od},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const VC=new FC;class UC extends E{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>Jg}])}}new UC;class BC extends E{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new BC;class jC 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 Pu=new jC;class HC 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 WC=new HC;class $C 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:()=>WC}])}}const Mp=new $C;class JC extends E{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>Mp},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>Mp}])}}const GC=new JC;class qC extends E{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const zC=new qC;class KC extends E{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>zC}])}}const YC=new KC;class QC 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:()=>Pu}])}}const XC=new QC;class ZC extends E{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>XC}])}}const Dp=new ZC;class eP 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 tP=new eP;class rP extends E{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>tP}])}}new rP;class nP extends E{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const iP=new nP;class sP extends E{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>iP}])}}const aP=new sP;class oP extends E{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>lP}])}}const cP=new oP;class dP 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:()=>Pu}])}}const lP=new dP;class uP 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 hP=new uP;class pP 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:()=>hP}])}}const mP=new pP;class fP 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:()=>Pu}])}}const qg=new fP;class gP extends E{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>qg}])}}new gP;class vP 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 yP=new vP;class SP extends E{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>kP}])}}const EP=new SP;class TP 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 kP=new TP;class _P extends E{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const bP=new _P;class wP 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",Ll,"BROADCAST_TYPE_"]}])}}const Fs=new wP;class IP extends E{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const CP=new IP;class PP extends E{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const RP=new PP;class AP 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 MP=new AP;class DP extends E{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>MP}])}}const Op=new DP;class OP 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 Np=new OP;var xl;(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"})(xl||(xl={}));var Pn;(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"})(Pn||(Pn={}));class NP 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 LP=new NP;class xP 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 FP=new xP;class VP 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 UP=new VP;class BP 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 jP=new BP;class HP extends E{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>UP},{no:2,name:"private",kind:"message",T:()=>jP}])}}const WP=new HP;class $P 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 JP=new $P;class GP extends E{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Pn,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Pn,"STREAM_PERMISSION_TYPE_"]}])}}const Jd=new GP;class qP extends E{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>Jd},{no:2,name:"audio",kind:"message",T:()=>Jd},{no:3,name:"screenshare",kind:"message",T:()=>Jd}])}}const zP=new qP;class KP extends E{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>LP},{no:2,name:"plugins",kind:"message",T:()=>FP},{no:3,name:"chat",kind:"message",T:()=>WP},{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",xl,"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",Nl,"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:()=>JP},{no:23,name:"media",kind:"message",T:()=>zP}])}}const Ru=new KP;class YP extends E{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const QP=new YP;class XP 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 ZP=new XP;class eR extends E{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>ZP}])}}const tR=new eR;class rR extends E{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>Ru}])}}const zg=new rR;class nR extends E{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>zg}])}}const iR=new nR;class sR extends E{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>zg}])}}const Lp=new sR;class aR 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 oR=new aR;class cR extends E{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>oR},{no:2,name:"patch",kind:"message",T:()=>Ru}])}}new cR;class dR extends E{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>Ru}])}}new dR;class lR 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 Ii=new lR;class uR 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 hR=new uR;class pR extends E{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Ii},{no:2,name:"next",kind:"scalar",T:8}])}}const mR=new pR;class fR extends E{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Ii}])}}const Kg=new fR;class gR 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 vR=new gR;class yR extends E{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>Ii}])}}const Gd=new yR;class SR 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 ER=new SR;class TR extends E{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>Ii}])}}const qd=new TR;class kR 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 _R=new kR;class bR extends E{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>Ii}])}}new bR;class wR 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 IR=new wR;class CR 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 PR=new CR;class RR 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 oo=new RR;class AR extends E{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>Ii}])}}const co=new AR;class MR 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 DR=new MR;class OR 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 lo=new OR;class NR 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 LR=new NR;class xR 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 FR=new xR;class VR extends E{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}const UR=new VR;class BR 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 jR=new BR;class HR 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 WR=new HR;class $R extends E{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new $R;class JR extends E{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}const GR=new JR;class qR extends E{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>Ii},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const zR=new qR;class KR 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:()=>zR},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const YR=new KR;class QR extends E{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>YR}])}}const Lr=new QR;class XR 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 ZR=new XR;class eA extends E{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>ZR}])}}const tA=new eA;class rA 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 nA=new rA;class iA 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 sA=new iA;class aA extends E{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const oA=new aA;class cA extends E{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const dA=new cA;class lA 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 uA=new lA;class hA 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 pA=new hA;class mA 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 fA=new mA;class gA 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 vA=new gA;class yA 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 Au=new yA;class SA 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:()=>Au}])}}const xp=new SA;class EA 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:()=>Au}])}}const TA=new EA;class kA 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:()=>Au}])}}const _A=new kA;class bA 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 wA=new bA;class IA 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 Fl=new IA;class CA extends E{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>Fl}])}}const PA=new CA;class RA 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 Fp=new RA;class AA 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 MA=new AA;class DA 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:()=>MA}])}}const Vp=new DA;class OA 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 Up=new OA;class NA 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 Bp=new NA;class LA extends E{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const jp=new LA;class xA 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 FA=new xA;class VA extends E{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>FA}])}}const zd=new VA;class UA extends E{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const BA=new UA;class jA extends E{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const HA=new jA;class WA extends E{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const Hp=new WA;class $A 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:()=>GA},{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 Yg=new $A;class JA 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:()=>zA}])}}const GA=new JA;class qA 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 zA=new qA;class KA 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 YA=new KA;class QA 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 XA=new QA;class ZA extends E{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>Yg}])}}const Kd=new ZA;class eM extends E{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>Yg}])}}const tM=new eM;class rM 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",pi]}])}}const Wp=new rM;class nM 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=Pe.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}toDate(e){return new Date(Pe.from(e.seconds).toNumber()*1e3+Math.ceil(e.nanos/1e6))}fromDate(e){const r=this.create(),n=e.getTime();return r.seconds=Pe.from(Math.floor(n/1e3)).toBigInt(),r.nanos=n%1e3*1e6,r}internalJsonWrite(e,r){let n=Pe.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 "+su(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=Pe.from(s/1e3).toBigInt(),n.nanos=0,i[7]&&(n.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),n}}new nM;const iM=0,sM=1,aM=2,oM=3,cM=4,dM=5,lM={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},uM={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,sendMessageToChannel:6,searchChannelMessages:7,getAllChatChannels:8,markChannelIndexAsRead:9,pinMessage:10},hM={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},pM={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},Qg={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},mM={createChatChannel:0,getChatChannel:1,deprecatedGetAllChatChannels:2,getChannelMembers:3,updateChatChannel:4},fM={getUserPresets:0,updateUserPreset:1};function ms(t,e){return Object.keys(e).reduce((r,n)=>(r[n]=(t<<16)+e[n],r),{})}function Xg(t,e){return Object.keys(t).reduce((r,n)=>(r[n]=e|t[n],r),{})}const j=ms(iM,lM),xe=ms(sM,uM),z=ms(aM,hM),Hr=ms(oM,pM),di=ms(cM,mM),ce=Xg(Qg,16777216),de=Xg(Qg,50331648),Wo=ms(dM,fM);var gM=Object.defineProperty,vM=Object.getOwnPropertyDescriptor,Mu=(t,e,r,n)=>{for(var i=n>1?void 0:n?vM(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&&gM(e,r,i),i},Un,$p;const Vl=($p=class{constructor(t){T(this,Un,void 0),S(this,Un,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,Un).sendMessagePromise(di.createChatChannel,jR.toBinary(s)),o=Lr.fromBinary(a.payload).chatChannels;return Vl.formatChannel(o[0])})}updateChannel(t,e){return u(this,null,function*(){const r=yield c(this,Un).sendMessagePromise(di.updateChatChannel,WR.toBinary({chatChannelId:t,targetUserIds:e.memberIds,displayName:e.displayName,displayPictureUrl:e.displayPictureUrl,visibility:e.visibility})),n=Lr.fromBinary(r.payload).chatChannels;return Vl.formatChannel(n[0])})}static formatChannel(t){var e;const{latestMessageAndUnreadCount:r}=t,n=Z(B({},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=qr.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,Un).sendMessagePromise(di.getChannelMembers,GR.toBinary({chatChannelId:t}));return tA.fromBinary(e.payload).channelMembers.map(r=>{var n=r,{id:i}=n,s=zc(n,["id"]);return Z(B({},s),{userId:i})})}catch{return[]}})}on(t,e){let r,n;switch(t){case di.createChatChannel:{r=Lr.fromBinary.bind(Lr),n=Lr.create();break}case di.updateChatChannel:{r=Lr.fromBinary.bind(Lr),n=Lr.create();break}}if(!r){l.warn(`ChatChannelSocketHandler::Event ${t} is not recognized`);return}c(this,Un).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)})}},Un=new WeakMap,$p);let gi=Vl;Mu([y.trace("ChatChannelHandler.createChannel")],gi.prototype,"createChannel",1);Mu([y.trace("ChatChannelHandler.updateChannel")],gi.prototype,"updateChannel",1);Mu([y.trace("ChatChannelHandler.getChannelMembers")],gi.prototype,"getChannelMembers",1);var yM=Object.defineProperty,SM=Object.getOwnPropertyDescriptor,gr=(t,e,r,n)=>{for(var i=n>1?void 0:n?SM(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},At=(t=>(t[t.TEXT=0]="TEXT",t[t.IMAGE=1]="IMAGE",t[t.FILE=2]="FILE",t[t.CUSTOM=3]="CUSTOM",t))(At||{}),It;class tr{constructor(e){T(this,It,void 0),S(this,It,e)}getChatMessages(){return c(this,It).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,It).sendMessagePromise(xe.getPaginatedMessages,hR.toBinary(a));return o.payload?mR.fromBinary(o.payload):{messages:[],next:!1}})}sendMessageToRoom(e,r){const n={payloadType:r,payload:e};c(this,It).sendMessage(xe.sendMessageToRoom,vR.toBinary(n))}sendMessageToPeers(e,r,n){const i={payloadType:r,peerIds:n,payload:e};c(this,It).sendMessage(xe.sendMessageToPeers,ER.toBinary(i))}sendMessageToChannel(e,r,n){const i={payloadType:r,channelId:n,payload:e};c(this,It).sendMessage(xe.sendMessageToChannel,_R.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,It).sendMessagePromise(xe.editMessage,IR.toBinary(a));return co.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,It).sendMessagePromise(xe.deleteMessage,DR.toBinary(n)),s=lo.fromBinary(i.payload);return B({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,It).sendMessagePromise(xe.searchChannelMessages,LR.toBinary(a));return Kg.fromBinary(o.payload).messages}catch{return[]}})}getAllChannels(){return u(this,null,function*(){try{const e=yield c(this,It).sendMessagePromise(xe.getAllChatChannels);return Lr.fromBinary(e.payload).chatChannels.map(gi.formatChannel)}catch{return[]}})}markLastReadMessage(e,r){return u(this,null,function*(){const n=yield c(this,It).sendMessagePromise(xe.markChannelIndexAsRead,FR.toBinary({channelId:e,userId:r.userId,channelIndex:r.channelIndex}));return UR.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,It).sendMessagePromise(xe.pinMessage,PR.toBinary(n));return oo.fromBinary(i.payload)})}on(e,r){let n,i;switch(e){case xe.sendMessageToRoom:{n=Gd.fromBinary.bind(Gd),i=Gd.create();break}case xe.sendMessageToPeers:{n=qd.fromBinary.bind(qd),i=qd.create();break}case xe.editMessage:{n=co.fromBinary.bind(co),i=co.create();break}case xe.pinMessage:{n=oo.fromBinary.bind(oo),i=oo.create();break}case xe.deleteMessage:{n=lo.fromBinary.bind(lo),i=lo.create();break}}if(!n){l.warn(`ChatSocketHandler::Event ${e} is not recognized`);return}c(this,It).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)})}}It=new WeakMap;gr([y.trace("SocketService.getChatMessages")],tr.prototype,"getChatMessages",1);gr([y.trace("SocketService.getChatMessagesPaginated")],tr.prototype,"getChatMessagesPaginated",1);gr([y.trace("SocketService.sendMessageToRoom")],tr.prototype,"sendMessageToRoom",1);gr([y.trace("SocketService.sendMessageToPeers")],tr.prototype,"sendMessageToPeers",1);gr([y.trace("SocketService.sendMessageToChannel")],tr.prototype,"sendMessageToChannel",1);gr([y.trace("SocketService.sendMessage")],tr.prototype,"sendMessage",1);gr([y.trace("SocketService.editMessage")],tr.prototype,"editMessage",1);gr([y.trace("SocketService.deleteMessage")],tr.prototype,"deleteMessage",1);gr([y.trace("SocketService.searchMessages")],tr.prototype,"searchMessages",1);gr([y.trace("SocketService.getAllChannels")],tr.prototype,"getAllChannels",1);gr([y.trace("SocketService.markLastReadMessage")],tr.prototype,"markLastReadMessage",1);function EM(t){return t.replace(/([-_]\w)/g,e=>e[1].toUpperCase())}function hr(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>hr(r));const e={};return Object.keys(t).forEach(r=>{const n=iu(r)?r:EM(r);e[n]=hr(t[r])}),e}function TM(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function Zg(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>Zg(r));const e={};return Object.keys(t).forEach(r=>{const n=iu(r)?r:TM(r);e[n]=t[r]}),e}function Oc(t,e={}){return t==null?{}:(Object.getOwnPropertyNames(t).forEach(r=>{if(typeof t[r]!="function"){if(typeof t[r]=="object"){Oc(t[r],e[r]={});return}e[r]=t[r]}}),e)}const kM=3,_M=30,bM=8e3;class wM{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=bM,retry:i=kM,retryDelay:s=_M,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=kc.create({baseURL:a,responseType:"json",timeout:n,retry:i,retryDelay:s}),this.axios=kc,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 IM=Object.defineProperty,CM=Object.getOwnPropertyDescriptor,Du=(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};class cd extends wM{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 uu.getIPDetails({peerId:r,apiHostnames:fg(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(Z(B({},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=Z(B({},xs),{tags:[...xs.tags],baseUrl:`http://localhost:${m.port}`,name:m.name,picture:(g=m.picture)!=null?g:xs.picture,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),id:m.id,organizationId:this.organizationId,description:(v=m.description)!=null?v:xs.description,staggered:(I=m.staggered)!=null?I:xs.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=Pc(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}})})}}Du([y.trace("APIClient.getIPDetails")],cd.prototype,"getIPDetails",1);Du([y.trace("APIClient.getICEServers")],cd.prototype,"getICEServers",1);Du([y.trace("APIClient.getPlugins")],cd.prototype,"getPlugins",1);var PM=Object.defineProperty,RM=Object.getOwnPropertyDescriptor,en=(t,e,r,n)=>{for(var i=n>1?void 0:n?RM(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&&PM(e,r,i),i};class Ir extends cd{startLivestreaming(e){return u(this,arguments,function*({manualIngestion:r}){const n=hr(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=hr((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 hr(e)})}startRecording(e,r){return u(this,null,function*(){return(yield this.requests.post("/v2/recordings",Z(B({},Zg(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{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}=hr((yield this.requests.post("v2/internals/rooms",{ip_information:e})).data.data);return{roomNodeUrl:r,meetingTitle:n,useHiveMedia:i!=null?i:!1,sfu:s}})}}en([y.trace("APIClient.startLivestreaming")],Ir.prototype,"startLivestreaming",1);en([y.trace("APIClient.stopLivestreaming")],Ir.prototype,"stopLivestreaming",1);en([y.trace("APIClient.getActiveLivestream")],Ir.prototype,"getActiveLivestream",1);en([y.trace("APIClient.getUserDetails")],Ir.prototype,"getUserDetails",1);en([y.trace("APIClient.startRecording")],Ir.prototype,"startRecording",1);en([y.trace("APIClient.stopRecording")],Ir.prototype,"updateRecording",1);en([y.trace("APIClient.getActiveRecording")],Ir.prototype,"getActiveRecording",1);en([y.trace("APIClient.getActiveTranscript")],Ir.prototype,"getActiveTranscript",1);en([y.trace("APIClient.getRoomNodeData")],Ir.prototype,"getRoomNodeData",1);let Ul;function AM(t,e){return Ul=new Ir(t,e),Ul}function ze(){return Ul}function MM(t,e){return`<blockquote>${e.replace(/<blockquote>[.\s\S]*<\/blockquote>\n\n/m,"")}</blockquote>
16
16
 
17
- ${t}`}function It(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 JP=Object.defineProperty,qP=Object.getOwnPropertyDescriptor,ht=(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};const KP=["text","image","file","custom","poll"],sa={maxInvocations:180,period:60};var re,yi,ze,Ei,wo,hd,Zh,ep;let rt=(ep=class extends xt{constructor(t,e,r,n,i){super(),_(this,hd),m(this,"messages"),m(this,"channels",[]),_(this,re,void 0),_(this,yi,void 0),_(this,ze,void 0),_(this,Ei,void 0),_(this,wo,void 0),m(this,"maxTextLimit",2e3),T(this,wo,t),T(this,ze,e),T(this,Ei,r),T(this,re,n),T(this,yi,i),this.messages=[]}setMaxTextLimit(t){this.maxTextLimit=t}get roomJoined(){var t;return((t=c(this,hd,Zh))==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"?GP(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,ze).sendMessageToChannel(t,Tt.TEXT,r);return}let h=[];e&&e.length>0&&(e.push(c(this,re).id),h=c(this,yi).joined.toArray().filter(p=>e.includes(p.id)).map(p=>p.userId),h.push(c(this,re).userId)),c(this,ze).sendMessage(t,Tt.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=He(),{getLocation:p,putLocation:f}=yield h.getPresignedUrls(t.name,c(this,re).config.viewType);if(yield h.uploadFile(t,f),r){c(this,ze).sendMessageToChannel(p,Tt.IMAGE,r);return}let g=[];e&&e.length>0&&(e.push(c(this,re).id),g=c(this,yi).joined.toArray().filter(E=>e.includes(E.id)).map(E=>E.userId),g.push(c(this,re).userId)),c(this,ze).sendMessage(p,Tt.IMAGE,e)}catch{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=He(),{getLocation:p,putLocation:f}=yield h.getPresignedUrls(t.name,c(this,re).config.viewType);if(yield h.uploadFile(t,f),r){c(this,ze).sendMessageToChannel(JSON.stringify({link:p,name:t.name,size:"size"in t?t.size:0}),Tt.FILE,r);return}let g=[];e&&e.length>0&&(e.push(c(this,re).id),g=c(this,yi).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,ze).sendMessage(E,Tt.FILE,e)}catch{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=He(),{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{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,ze).sendMessage(JSON.stringify(F),Tt.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,ze).editMessage(t,e,Tt.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=He(),{getLocation:d,putLocation:h}=yield a.getPresignedUrls(e.name,c(this,re).config.viewType);yield a.uploadFile(e,h),c(this,ze).editMessage(t,d,Tt.IMAGE,r)}catch{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=He(),{getLocation:d,putLocation:h}=yield a.getPresignedUrls(e.name,c(this,re).config.viewType);yield a.uploadFile(e,h),c(this,ze).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),Tt.FILE,r)}catch{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,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.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,ze).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,ze).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,ze).getChatMessagesPaginated(t,e,r,n,i);return{messages:s.messages.map(o=>Mr.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,Ei).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,Ei).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,Ei).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,ze).searchMessages(e,r)).map(Mr.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=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,yi=new WeakMap,ze=new WeakMap,Ei=new WeakMap,wo=new WeakMap,hd=new WeakSet,Zh=function(){return c(this,wo).getValue("roomNodeClient")},ep);ht([y.trace("DyteChat.sendTextMessage"),It(sa)],rt.prototype,"sendTextMessage",1);ht([y.trace("DyteChat.sendImageMessage"),It({maxInvocations:20,period:60})],rt.prototype,"sendImageMessage",1);ht([y.trace("DyteChat.sendFileMessage"),It({maxInvocations:20,period:60})],rt.prototype,"sendFileMessage",1);ht([y.trace("DyteChat.sendMessage"),It({maxInvocations:180,period:60})],rt.prototype,"sendMessage",1);ht([y.trace("DyteChat.editTextMessage")],rt.prototype,"editTextMessage",1);ht([y.trace("DyteChat.editImageMessage")],rt.prototype,"editImageMessage",1);ht([y.trace("DyteChat.editFileMessage")],rt.prototype,"editFileMessage",1);ht([y.trace("DyteChat.editMessage")],rt.prototype,"editMessage",1);ht([y.trace("DyteChat.deleteMessage")],rt.prototype,"deleteMessage",1);ht([y.trace("DyteChat.createChannel")],rt.prototype,"createChannel",1);ht([y.trace("DyteChat.updateChannel")],rt.prototype,"updateChannel",1);ht([y.trace("DyteChat.sendMessageToChannel")],rt.prototype,"sendMessageToChannel",1);ht([y.trace("DyteChat.getChannelMembers")],rt.prototype,"getChannelMembers",1);ht([y.trace("DyteChat.searchMessages")],rt.prototype,"searchMessages",1);ht([y.trace("DyteChat.markLastReadMessage")],rt.prototype,"markLastReadMessage",1);rt=ht([ut("0500")],rt);var b=(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))(b||{}),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},pd,tp;const Ln=(tp=class{constructor(t,e,r,n,i){m(this,"chat"),m(this,"chatSocketHandler"),m(this,"chatChannelSocketHandler"),m(this,"self"),_(this,pd,void 0),T(this,pd,t),this.chatSocketHandler=e,this.chatChannelSocketHandler=r,this.chat=new rt(t,e,r,n,i),this.self=n,this.setupEvents()}static init(t,e,r,n,i){return u(this,null,function*(){return new Ln(t,e,r,n,i)})}static formatMessage(t){return ne(V({},t),{time:new Date(t.time),type:KP[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 Tt.TEXT:{r.message=t.payload;break}case Tt.IMAGE:{r.link=t.payload;break}case Tt.FILE:{const{link:n,name:i,size:s}=JSON.parse(t.payload);r.link=n,r.name=i,r.size=s;break}case Tt.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 Ln.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=og.fromBinary(t.payload).messages;this.chat.messages=e.map(r=>Ln.formatSocketServiceMessage(r))})}setupEvents(){w.on(b.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){this.getChatMessages()})),this.chatSocketHandler.on(Ne.sendMessageToRoom,t=>{const e=Ln.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(Ne.sendMessageToPeers,t=>{const e=Ln.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(Ne.editMessage,t=>{const e=Ln.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(Ne.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=ti.formatChannel(e);this.chat.channels.push(r),this.chat.emit("channelCreate",r)}),this.chatSocketHandler.on(Ne.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=ti.formatChannel(e);this.chat.channels=this.chat.channels.map(n=>n.id===r.id?r:n),this.chat.emit("channelUpdate",r)})}},pd=new WeakMap,tp);let Mr=Ln;QP([y.trace("ChatController.setupEvents")],Mr.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},md,rp,Si,hs,Co,np;let Qd=(np=class extends xt{constructor(t,e,r){super(),_(this,md),m(this,"items"),_(this,Si,void 0),_(this,hs,void 0),_(this,Co,void 0),T(this,Co,t),T(this,Si,e),T(this,hs,r),this.items=[]}get roomJoined(){var t;return((t=c(this,md,rp))==null?void 0:t.roomJoined)===!0}create(t,e,r=!1,n=!1){return u(this,null,function*(){if(c(this,Si).config.viewType!=="LIVESTREAM"&&!this.roomJoined)throw new C("Can't create polls without joining room");if(!c(this,Si).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,hs).createPoll(t,e,r,n)})}vote(t,e){return u(this,null,function*(){if(!c(this,Si).permissions.polls.canVote){l.error("DytePolls::vote::permission_denied");return}yield c(this,hs).votePoll(t,e)})}},md=new WeakSet,rp=function(){return c(this,Co).getValue("roomNodeClient")},Si=new WeakMap,hs=new WeakMap,Co=new WeakMap,np);Qd=eA([ut("0700")],Qd);var tA=Object.defineProperty,rA=Object.getOwnPropertyDescriptor,nA=(t,e,r,n)=>{for(var i=n>1?void 0:n?rA(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&&tA(e,r,i),i},Io,En,ip;const Ni=(ip=class{constructor(t,e,r){m(this,"polls"),_(this,Io,void 0),_(this,En,void 0),this.polls=new Qd(t,e,r),T(this,Io,e),T(this,En,r),this.setupEvents()}static init(t,e,r){return u(this,null,function*(){return new Ni(t,e,r)})}canViewPolls(){return c(this,Io).permissions.polls.canView}setupEvents(){w.on(b.UPDATE_PERMISSIONS,t=>{t.polls&&(t.polls.canView?this.getPolls():this.polls.items=[])}),this.canViewPolls()&&(w.on(b.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),c(this,En).on(Cr.createPoll,t=>{t.poll&&this.updatePoll(Ni.formatSocketServicePoll(t.poll))}),c(this,En).on(Cr.updatePoll,t=>{t.poll&&this.updatePoll(Ni.formatSocketServicePoll(t.poll))}),c(this,En).on(Cr.votePoll,t=>{t.poll&&this.updatePoll(Ni.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,En).getPolls();if(!(t!=null&&t.payload))return;const{polls:e}=fP.fromBinary(t.payload);this.polls.items=e.map(r=>Ni.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}}},Io=new WeakMap,En=new WeakMap,ip);let ug=Ni;nA([y.trace("PollController.setupEvents")],ug.prototype,"setupEvents",1);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},hg=(t=>(t[t.User=0]="User",t[t.Meeting=1]="Meeting",t))(hg||{}),Ro,ps,Po,Ti,Ao,sp;let Xd=(sp=class extends xt{constructor(t,e,r,n,i){super(),_(this,ps),m(this,"selfActiveTab"),m(this,"broadcastTabChanges"),_(this,Ro,void 0),_(this,Ti,void 0),_(this,Ao,void 0),m(this,"viewType"),m(this,"meetingStartedTimestamp"),m(this,"meetingTitle"),m(this,"sessionId"),T(this,Ro,t),T(this,Ti,e),this.viewType=r,T(this,Ao,n),this.meetingTitle=i,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){var t;return(t=c(this,ps,Po))==null?void 0:t.socketState}get mediaState(){var t;return(t=c(this,ps,Po))==null?void 0:t.mediaState}get meetingId(){var t;return(t=c(this,ps,Po))==null?void 0:t.roomName}setBroadcastTabChanges(t){if(!c(this,Ti).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,Ti).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){c(this,Ao).broadcastMessage("spotlight",{userId:c(this,Ti).userId,currentTab:this.selfActiveTab})}},Ro=new WeakMap,ps=new WeakSet,Po=function(){return c(this,Ro).getValue("roomNodeClient")},Ti=new WeakMap,Ao=new WeakMap,sp);Xd=oA([ut("0800")],Xd);function aA(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 cA=Object.defineProperty,dA=Object.getOwnPropertyDescriptor,pg=(t,e,r,n)=>{for(var i=n>1?void 0:n?dA(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};let ln=class extends xt{constructor(){super(),m(this,"transcripts"),this.transcripts=[]}static init(t){return u(this,null,function*(){const e=new ln;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]]=aA(t);return{id:si(),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=>ln.parseTranscript(e,!1)).filter(Boolean):[]}getActiveTranscript(){return u(this,null,function*(){try{const t=He(),{transcript:e}=yield t.getActiveTranscript();this.transcripts=ln.parseTranscripts(e)}catch{}})}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)})}};pg([y.trace("DyteAi.getActiveTranscript")],ln.prototype,"getActiveTranscript",1);ln=pg([ut("0000")],ln);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},Sn,ms,fd,op;const mg=(op=class{constructor(t,e,r,n,i,s){m(this,"meta"),m(this,"ai"),_(this,Sn,void 0),_(this,ms,void 0),m(this,"aiSocketHandler"),_(this,fd,void 0),T(this,fd,t),this.meta=new Xd(t,e,e.config.viewType,r,s),this.ai=n,T(this,Sn,e),T(this,ms,r),this.aiSocketHandler=i,e.config.viewType!==Je.Chat&&this.setupEvents()}static init(t,e,r,n,i){return u(this,null,function*(){const s=yield ln.init(e.permissions.transcriptionEnabled);return new mg(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,hg.Meeting),this.meta.emit("activeTabUpdate",t.currentTab))}setupEvents(){w.on(b.TRANSPORT_STATE_UPDATE,t=>{this.meta.emit("mediaConnectionUpdate",t)}),w.on(b.SOCKET_STATE_UPDATE,t=>{this.meta.emit("socketConnectionUpdate",t)}),w.on(b.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})}}),w.on(b.PRODUCER_SCORE_UPDATE,({score:t})=>{t<5&&this.meta.emit("poorConnection",{score:t})}),c(this,Sn).permissions.canSpotlight&&(l.info("DyteMetaController::Asserting Spotlight"),this.meta.selfActiveTab&&c(this,ms).broadcastMessage("spotlight",{userId:c(this,Sn).userId,currentTab:this.meta.selfActiveTab})),w.on(b.PEER_JOINED_INTERNAL,t=>u(this,null,function*(){c(this,Sn).permissions.canSpotlight&&this.meta.selfActiveTab&&c(this,ms).broadcastToPeers("spotlight",[t.id],{userId:c(this,Sn).userId,currentTab:this.meta.selfActiveTab})})),w.on(b.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)}),w.on(b.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=ln.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}`)})}},Sn=new WeakMap,ms=new WeakMap,fd=new WeakMap,op);let fg=mg;hA([y.trace("MetaController.setupEvents")],fg.prototype,"setupEvents",1);var pA=Object.defineProperty,mA=Object.getOwnPropertyDescriptor,hi=(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},sr,Ds,xe,oa,xn,ar,Os,aa;class mn extends xt{constructor(e,r,n,i,s){super(),_(this,Os),_(this,sr,void 0),_(this,Ds,void 0),_(this,xe,void 0),_(this,oa,void 0),_(this,xn,void 0),_(this,ar,void 0),T(this,ar,e),T(this,sr,i),T(this,Ds,s),T(this,xe,r),T(this,oa,n),T(this,xn,[]),this.setupEvents()}get status(){return c(this,ar).getValue("stageStatus")}setupEvents(){w.onAsync(b.GET_STAGE_REQUESTS,e=>u(this,null,function*(){T(this,xn,e)})),w.onAsync(b.UPDATE_STAGE_REQUESTS,e=>u(this,[e],function*({add:r}){const n=c(this,oa).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,xn).length)&&this.emit("newStageRequest",{count:n.length}),T(this,xn,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,xn)}}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,Os,aa).call(this,"ACCEPTED_TO_JOIN_STAGE");return}c(this,sr).requestAccess(),ue(this,Os,aa).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,sr).cancelRequestAccess(),ue(this,Os,aa).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,sr).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,sr).denyAccess(e)}join(){return u(this,null,function*(){const e=c(this,ar).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,sr).joinStage(),e===Je.Livestream){const{name:r,id:n,userId:i}=c(this,xe);yield c(this,Ds).joinRoom(r,n,i,e)}if(c(this,ar).setValue("stageStatus","ON_STAGE",!1),yield w.emitAsync(b.JOIN_MEDIA_ROOM),c(this,ar).notify("stageStatus"),e===Je.Livestream){const{peers:r}=yield c(this,Ds).getStagePeers();w.emit(b.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,sr).leaveStage(c(this,xe).userId),c(this,ar).setValue("stageStatus","OFF_STAGE",!1),yield w.emitAsync(b.LEAVE_MEDIA_ROOM,"stageLeft"),c(this,ar).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,sr).kick(e)})}}sr=new WeakMap,Ds=new WeakMap,xe=new WeakMap,oa=new WeakMap,xn=new WeakMap,ar=new WeakMap,Os=new WeakSet,aa=function(t){return u(this,null,function*(){this.status!==t&&c(this,ar).setValue("stageStatus",t)})};hi([y.trace("DyteStage.getStageRequests")],mn.prototype,"getAccessRequests",1);hi([y.trace("DyteStage.requestAccess")],mn.prototype,"requestAccess",1);hi([y.trace("DyteStage.cancelRequestAccess")],mn.prototype,"cancelRequestAccess",1);hi([y.trace("DyteStage.grantAccess")],mn.prototype,"grantAccess",1);hi([y.trace("DyteStage.denyAccess")],mn.prototype,"denyAccess",1);hi([y.trace("DyteStage.joinStage")],mn.prototype,"join",1);hi([y.trace("DyteStage.leaveStage")],mn.prototype,"leave",1);function fA(t){return!(t.viewType==="LIVESTREAM"||t.viewType==="CHAT")}function Ya(t){switch(t){case Pr.UNSPECIFIED:return"OFF_STAGE";case Pr.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case Pr.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case Pr.OFF_STAGE:return"OFF_STAGE";case Pr.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var gA=Object.defineProperty,vA=Object.getOwnPropertyDescriptor,yA=(t,e,r,n)=>{for(var i=n>1?void 0:n?vA(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&&gA(e,r,i),i},Fn,Li,Un,ca,Xr;class gg{constructor(e,r,n,i,s){m(this,"stage"),_(this,Fn,void 0),_(this,Li,void 0),_(this,Un,void 0),_(this,ca,0),_(this,Xr,void 0),T(this,Xr,e),this.stage=new mn(e,i,s,r,n),T(this,Un,r),T(this,Fn,i),T(this,Li,s),this.setupEvents()}setupEvents(){c(this,Xr).subscribe("stageStatus",e=>{this.stage.emit("stageStatusUpdate",e)}),c(this,Un).on(j.grantStageAccess,()=>{c(this,Fn).permissions.stageAccess!==q.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),c(this,Un).on(j.peerStageStatusUpdate,e=>{e!==void 0&&(e.peerId===c(this,Fn).id?this.selfStageStatusHandler(e):this.peerStageStatusHandler(e))}),c(this,Un).on(j.denyStageAccess,()=>{c(this,Fn).permissions.stageAccess!==q.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),c(this,Un).on(j.getStageRequests,e=>u(this,null,function*(){var r;if(c(this,Fn).permissions.stageAccess!==q.Allowed)return;const n=(r=e==null?void 0:e.stageRequests)!=null?r:[];yield w.emitAsync(b.GET_STAGE_REQUESTS,n),c(this,ca)<n.length&&n.length>0&&this.stage.emit("newStageRequest",{count:n.length}),T(this,ca,n.length),this.stage.emit("stageAccessRequestUpdate",n)}))}getCurrentStageRequests(){return c(this,Li).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,Xr).setValue("stageStatus",e)})}selfStageStatusHandler(e){const r=Ya(e.stageType),n=c(this,Xr).getValue("stageStatus");if(n!==r)switch(e.stageType){case 1:c(this,Xr).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,Xr).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}peerStageStatusHandler(e){return u(this,null,function*(){const r=c(this,Li).joined.get(e.peerId),n=c(this,Li).viewMode==="ACTIVE_GRID";if(!r){l.warn("err::peerStageStatusUpdate: participant not found");return}switch(e.stageType){case 1:r.setStageStatus("ON_STAGE"),n&&w.emit(b.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&&w.emit(b.REFRESH_GRID);break}w.emit(b.UPDATE_PEER_STAGE_STATUS,{id:r.id,status:r.stageStatus})})}}Fn=new WeakMap,Li=new WeakMap,Un=new WeakMap,ca=new WeakMap,Xr=new WeakMap;yA([y.trace("DyteStage.setupEvents")],gg.prototype,"setupEvents",1);var EA=Object.defineProperty,SA=Object.getOwnPropertyDescriptor,Cc=(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&&EA(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 pt,Gt,fs,gs,Vr,vs,ys,ki,Es,ap;let Zi=(ap=class extends ns{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,ki),_(this,pt,void 0),m(this,"baseURL"),m(this,"createdAt"),m(this,"description"),m(this,"id"),m(this,"name"),_(this,Gt,void 0),_(this,fs,void 0),_(this,gs,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,Vr,void 0),m(this,"config"),_(this,vs,void 0),m(this,"active"),m(this,"iframes"),m(this,"enabledBy"),_(this,ys,void 0),T(this,ys,t),this.baseURL=e,this.createdAt=new Date(r),this.description=n,this.id=i,this.name=s,T(this,Gt,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,pt,v),T(this,fs,A),T(this,gs,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,pt).customPluginEventToRoom(this.id,n,i);break}case J.customPluginEventToPeers:{c(this,pt).customPluginEventToPeers(this.id,n.peerIds,n,i);break}case J.enablePluginForRoom:{c(this,pt).enablePluginForRoom(this.id,i);break}case J.enablePluginForPeers:{c(this,pt).enablePluginForPeers(this.id,n.peerIds,i);break}case J.disablePluginForRoom:{c(this,pt).disablePluginForRoom(this.id,i);break}case J.disablePluginForPeers:{c(this,pt).disablePluginForPeers(this.id,n.peerIds,i);break}case J.storeInsertKeys:{c(this,pt).storeInsertKeys(this.id,n.store,n.insertKeys,i);break}case J.storeGetKeys:{c(this,pt).storeGetKeys(this.id,n.store,n.getKeys,i);break}case J.storeDeleteKeys:{c(this,pt).storeDeleteKeys(this.id,n.store,n.deleteKeys,i);break}case J.storeDelete:{c(this,pt).storeDelete(this.id,n.store,i);break}case Fe.chatMessage:{const{messagePayload:o,peerIds:a}=n;if(!c(this,gs)){this.sendIframeEvent({type:Fe.chatMessage,uuid:r.uuid,payload:{error:"Chat is disabled for this room."}});return}try{yield c(this,gs).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,Gt)),{isRecorder:(e=c(this,Gt).permissions)==null?void 0:e.isRecorder,isHidden:c(this,Gt).permissions.hiddenParticipant,stageStatus:c(this,Gt).stageStatus});a?(o=c(this,fs).joined.get(n.peerId),c(this,Gt).id===a&&(o=d)):o=d,this.sendIframeEvent({type:Fe.getPeer,payload:{peer:o&&za(o)},uuid:r.uuid});break}case Fe.getPeers:{const o=c(this,fs).joined.toArray().map(a=>za(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,ki,Es).meetingTitle},uuid:r.uuid});break}case Fe.getRoomName:{this.sendIframeEvent({type:Fe.getRoomName,payload:{roomName:c(this,ki,Es).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,vs))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,vs),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:c(this,ys).getValue("apiBase"),pluginId:this.id,roomName:(r=c(this,ki,Es).roomName)!=null?r:"",displayTitle:c(this,ki,Es).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=He(),e=yield t.authorizePlugin(this.id);T(this,vs,e),T(this,Vr,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,Vr,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,Gt).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(c(this,pt).addPlugin(this.id,this.staggered),T(this,Vr,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,Gt).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==c(this,Gt).id||(c(this,pt).removePlugin(this.id),l.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:c(this,Vr)?new Date().getTime()-c(this,Vr).getTime():0}}),T(this,Vr,void 0)))})}},pt=new WeakMap,Gt=new WeakMap,fs=new WeakMap,gs=new WeakMap,Vr=new WeakMap,vs=new WeakMap,ys=new WeakMap,ki=new WeakSet,Es=function(){return c(this,ys).getValue("roomNodeClient")},ap);Cc([It({maxInvocations:5,period:1})],Zi.prototype,"sendData",1);Cc([y.trace("DytePlugin.activatePlugin")],Zi.prototype,"activate",1);Cc([y.trace("DytePlugin.deactivatePlugin")],Zi.prototype,"deactivate",1);Zi=Cc([ut("0600")],Zi);var Ge,xi;class vg extends Map{constructor(e){const{onAddEvent:r,onDeleteEvent:n,onClearEvent:i}=e;super(),_(this,Ge,void 0),_(this,xi,void 0),m(this,"onAddEvent"),m(this,"onDeleteEvent"),m(this,"onClearEvent"),T(this,Ge,new ns),this.onAddEvent=r,this.onDeleteEvent=n,this.onClearEvent=i,T(this,xi,new Map)}emit(e,...r){return c(this,Ge).emit(e,...r)}on(e,r){return c(this,Ge).on(e,r)}addListener(e,r){return c(this,Ge).addListener(e,r)}off(e,r){return c(this,Ge).off(e,r)}once(e,r){return c(this,Ge).once(e,r)}prependListener(e,r){return c(this,Ge).prependListener(e,r)}prependOnceListener(e,r){return c(this,Ge).prependOnceListener(e,r)}removeListener(e,r){return c(this,Ge).removeListener(e,r)}removeAllListeners(e){return c(this,Ge).removeAllListeners(e)}listeners(e){return c(this,Ge).listeners(e)}listenerCount(e){return c(this,Ge).listenerCount(e)}getMaxListeners(){return c(this,Ge).getMaxListeners()}setMaxListeners(e){return c(this,Ge).setMaxListeners(e)}eventNames(){return c(this,Ge).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,Ge).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,Ge).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,Ge).emit(this.onClearEvent),n}toArray(){return Array.from(this.values())}}Ge=new WeakMap,xi=new WeakMap;class cp extends vg{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 TA=Object.defineProperty,kA=Object.getOwnPropertyDescriptor,_A=(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&&TA(e,r,i),i};let Zd=class{constructor(){m(this,"all"),m(this,"active"),this.all=new cp,this.active=new cp}};Zd=_A([ut("0600")],Zd);var bA=Object.defineProperty,wA=Object.getOwnPropertyDescriptor,Ic=(t,e,r,n)=>{for(var i=n>1?void 0:n?wA(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&&bA(e,r,i),i},Jt,Ss,Mo,dp;const yg=(dp=class{constructor(t,e,r,n){m(this,"plugins"),_(this,Jt,void 0),_(this,Ss,void 0),_(this,Mo,void 0),T(this,Jt,e),T(this,Ss,r),T(this,Mo,t),this.plugins=n,this.setupEvents()}static init(t,e,r,n,i,s,o){return u(this,null,function*(){const a=new Zd;return e.forEach(d=>{const h=new Zi(t,d,r,s,o,i);a.all.add(h)}),new yg(t,r,n,a)})}getRoomPlugins(){return u(this,null,function*(){const{plugins:t}=yield c(this,Jt).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)}),w.onAsync(b.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){yield this.getRoomPlugins(),l.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to fetch plugins.")})),c(this,Jt).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,Jt).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,Jt).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,Jt).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,Jt).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,Jt).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,Jt).on(J.storeDelete,(t,e)=>u(this,null,function*(){this.sendIframeEvent(J.storeDelete,t.pluginId,e,{storeName:t.storeName})})),c(this,Ss).on(Ne.sendMessageToPeers,t=>{const e=Mr==null?void 0:Mr.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(Fe.chatMessage,{message:e})}),c(this,Ss).on(Ne.sendMessageToRoom,t=>{const e=Mr==null?void 0:Mr.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(Fe.chatMessage,{message:e})}),w.on(b.PEER_JOINED_INTERNAL,t=>{const e=za(t);this.broadcastIframeEvent(Fe.peerJoined,e)}),w.on(b.PEER_CLOSED,t=>{this.broadcastIframeEvent(Fe.peerLeft,t)}),w.on(b.UPDATE_PEER_STAGE_STATUS,t=>{this.broadcastIframeEvent(Fe.peerStageStatusUpdate,t)}),c(this,Mo).subscribe("stageStatus",t=>{this.broadcastIframeEvent(Fe.stageStatusUpdate,t)})}},Jt=new WeakMap,Ss=new WeakMap,Mo=new WeakMap,dp);let lo=yg;Ic([y.trace("PluginController.getRoomPlugins")],lo.prototype,"getRoomPlugins",1);Ic([y.trace("PluginController.enableForSelf")],lo.prototype,"enablePlugin",1);Ic([y.trace("PluginController.disableForSelf")],lo.prototype,"disablePlugin",1);Ic([y.trace("PluginController.setupEvents")],lo.prototype,"setupEvents",1);var CA=Object.defineProperty,IA=Object.getOwnPropertyDescriptor,uo=(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},Ts,Do,ks,Oo,lp;let ri=(lp=class extends xt{constructor(t,e){super(),_(this,ks),_(this,Ts,void 0),_(this,Do,void 0),m(this,"recordingPeerIds",[]),m(this,"recordings",[]),T(this,Do,t),T(this,Ts,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,Ts).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=He(),{recording:r={}}=c(this,Do).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,ks,Oo).call(this,"stop",["RECORDING","PAUSED"],t)})}pause(t){return u(this,null,function*(){yield ue(this,ks,Oo).call(this,"pause",["RECORDING"],t)})}resume(t){return u(this,null,function*(){yield ue(this,ks,Oo).call(this,"resume",["PAUSED"],t)})}},Ts=new WeakMap,Do=new WeakMap,ks=new WeakSet,Oo=function(t,e,r){return u(this,null,function*(){if(!c(this,Ts).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 He().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")}}))})},lp);uo([y.trace("DyteRecording.start")],ri.prototype,"start",1);uo([y.trace("DyteRecording.stop")],ri.prototype,"stop",1);uo([y.trace("DyteRecording.stop")],ri.prototype,"pause",1);uo([y.trace("DyteRecording.stop")],ri.prototype,"resume",1);ri=uo([ut("1000")],ri);var RA=Object.defineProperty,PA=Object.getOwnPropertyDescriptor,AA=(t,e,r,n)=>{for(var i=n>1?void 0:n?PA(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},el;class Eg{constructor(e,r,n){m(this,"recording"),m(this,"room"),_(this,el,void 0),T(this,el,e),this.recording=new ri(e,r),this.room=n,this.setupEvents()}setupEvents(){w.on(b.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)})}}el=new WeakMap;AA([y.trace("RecordingController.setupEvents")],Eg.prototype,"setupEvents",1);class MA{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 Gl{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 Gl(l,MA,e)}}class Jl{constructor(e){m(this,"internals"),this.internals=e}static init(){return u(this,null,function*(){const e=Gl.init(B);return new Jl(e)})}}var DA=Object.defineProperty,OA=Object.getOwnPropertyDescriptor,Ft=(t,e,r,n)=>{for(var i=n>1?void 0:n?OA(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&&DA(e,r,i),i},Ze,dt,Qe,br,Yt,da,tl;class Rt extends ns{constructor(e,r,n=hp,i=!0){super(),_(this,Ze,void 0),_(this,dt,void 0),_(this,Qe,void 0),_(this,br,void 0),_(this,Yt,void 0),_(this,da,void 0),_(this,tl,void 0),m(this,"audioUpdateInProgress"),m(this,"videoUpdateInProgress"),T(this,tl,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,T(this,Ze,new Sg(e,r)),T(this,dt,new tM(c(this,Ze),void 0,n)),T(this,Qe,new cM(c(this,Ze),void 0,n)),T(this,Yt,new sM(c(this,Ze))),T(this,br,new nM(c(this,Ze))),T(this,da,i),c(this,dt).on("trackMuted",this.onAudioTrackMuted.bind(this)),c(this,dt).on("trackChanged",this.onAudioTrackChanged.bind(this)),c(this,Qe).on("trackChanged",this.onVideoTrackChanged.bind(this)),c(this,Qe).on("trackEnded",this.onVideoTrackEnded.bind(this)),c(this,Yt).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,Ze).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,Ze).getAudioTrack(!1)}catch(a){l.error("LocalMediaHandler::init::Failed to get audio track",{error:a})}if(!o&&n)try{o=yield c(this,Ze).getVideoTrack()}catch(a){l.error("LocalMediaHandler::init::Failed to get video track",{error:a})}yield c(this,dt).setMediaTrack(s),yield c(this,Qe).setMediaTrack(o);try{yield c(this,br).setupSpeaker()}catch{}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,br).currentDevice)!=null&&i.deviceId&&B.onSafeInitialization(()=>{B.selectedDevice("SPEAKER",c(this,br).currentDevice)}),c(this,Ze).onDeviceChange((a,d,h)=>{this.onDeviceChange(d,h)})})}getCurrentDevices(){return{audio:c(this,dt).currentDevice,video:c(this,Qe).currentDevice,speaker:c(this,br).currentDevice}}get permissions(){return c(this,Ze).permissions}getAllDevices(){return c(this,Ze).getAvailableDevices()}getDeviceById(e,r){return c(this,Ze).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return c(this,dt).mediaTrack}get audioTrack(){return c(this,dt).transformedMediaTrack}get audioEnabled(){return c(this,dt).trackEnabled}enableAudio(){return u(this,null,function*(){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{yield c(this,dt).unmuteTrack()}catch{}finally{this.audioUpdateInProgress=!1}}})}disableAudio(){c(this,dt).muteTrack()}getAudioDevices(e){return c(this,Ze).getAudioInputDevices(e)}setAudioDevice(e){return u(this,null,function*(){yield c(this,dt).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,br).setupSpeaker()}setSpeakerDevice(e){return u(this,null,function*(){yield c(this,br).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,Qe).mediaTrack}get videoTrack(){return c(this,Qe).transformedMediaTrack}get videoEnabled(){return c(this,Qe).trackEnabled}enableVideo(){return u(this,null,function*(){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{yield c(this,Qe).unmuteTrack()}catch{}finally{this.videoUpdateInProgress=!1}}})}disableVideo(){c(this,Qe).disableTrack()}getVideoDevices(e){return c(this,Ze).getVideoInputDevices(e)}setVideoDevice(e){return u(this,null,function*(){yield c(this,Qe).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,Qe).updateConstraints(e)})}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:c(this,Yt).audioMediaTrack,video:c(this,Yt).videoMediaTrack}}get screenShareEnabled(){return c(this,Yt).trackEnabled}enableScreenShare(){return u(this,null,function*(){yield c(this,Yt).enableScreenShare()})}disableScreenShare(){return u(this,null,function*(){c(this,Yt).disableScreenShare()})}updateScreenshareConstraints(e){return u(this,null,function*(){yield c(this,Yt).updateConstraints(e)})}getSpeakerDevices(e){return c(this,Ze).getAudioOutputDevices(e)}addAudioMiddleware(e){return c(this,dt).addMiddleware(e)}removeAudioMiddleware(e){return c(this,dt).removeMiddleware(e)}addVideoMiddleware(e){return c(this,Qe).addMiddleware(e)}removeVideoMiddleware(e){return c(this,Qe).removeMiddleware(e)}setVideoMiddlewareGlobalConfig(e){return c(this,Qe).setVideoMiddlewareGlobalConfig(e)}destruct(){c(this,dt).disableTrack(),c(this,Qe).disableTrack(),c(this,Qe).terminateMiddlewareWebWorker(),c(this,Yt).disableScreenShare(),c(this,Ze).destruct()}onDeviceChange(e,r){return u(this,null,function*(){var n,i;this.emit("DEVICE_LIST_UPDATED",e),!(r||!c(this,da))&&((n=e==null?void 0:e.added)==null||n.forEach(s=>u(this,null,function*(){var o;s&&!hp(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)})}}Ze=new WeakMap,dt=new WeakMap,Qe=new WeakMap,br=new WeakMap,Yt=new WeakMap,da=new WeakMap,tl=new WeakMap;Ft([y.trace("MediaHandler.setupStreams")],Rt.prototype,"setupStreams",1);Ft([y.trace("MediaHandler.enableAudio")],Rt.prototype,"enableAudio",1);Ft([y.trace("MediaHandler.disableAudio")],Rt.prototype,"disableAudio",1);Ft([y.trace("MediaHandler.setAudioDevice")],Rt.prototype,"setAudioDevice",1);Ft([y.trace("MediaHandler.enableVideo")],Rt.prototype,"enableVideo",1);Ft([y.trace("MediaHandler.disableVideo")],Rt.prototype,"disableVideo",1);Ft([y.trace("MediaHandler.setVideoDevice")],Rt.prototype,"setVideoDevice",1);Ft([y.trace("MediaHandler.updateVideoConstraints")],Rt.prototype,"updateVideoConstraints",1);Ft([y.trace("MediaHandler.enableScreenShare")],Rt.prototype,"enableScreenShare",1);Ft([y.trace("MediaHandler.disableScreenShare")],Rt.prototype,"disableScreenShare",1);Ft([y.trace("MediaHandler.updateScreenshareConstraints")],Rt.prototype,"updateScreenshareConstraints",1);Ft([y.trace("MediaHandler.destruct")],Rt.prototype,"destruct",1);Ft([y.trace("MediaHandler.onDeviceChange")],Rt.prototype,"onDeviceChange",1);var rl=(t=>(t.NotAllowedError="NotAllowedError",t.NotReadableError="NotReadableError",t.NO_DEVICES_AVAILABLEError="NO_DEVICES_AVAILABLEError",t.AbortError="AbortError",t))(rl||{});function up(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 NA=["virtual","emulator","krisp","solstice conference","teams","manycam","blackHole"];function hp(t){const e=t.label.toLowerCase();return ye._bowser.getOSName()==="macOS"&&e.includes("iphone")?(l.log("isVirtualDevice::ignore_macos_continuity"),!0):NA.some(r=>e.includes(r))}function LA(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 xA{constructor(){_(this,Fi,void 0)}terminateMiddlewareWebWorker(){if(c(this,Fi))try{Xp(c(this,Fi)),T(this,Fi,void 0)}catch{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:ty})));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{}return o.addEventListener("play",()=>{i.width=o.width||r.getSettings().width,i.height=o.width||r.getSettings().height,T(this,Fi,Zp(h,50))},!1),i.captureStream().getVideoTracks()[0]})}}Fi=new WeakMap;const pp={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}}},mp={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"}]},FA={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"}]},fp={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 Y=(t=>(t.WEBCAM="webcam",t.MIC="mic",t.SCREENSHARE_VIDEO="screenshare_video",t.SCREENSHARE_AUDIO="screenshare_audio",t))(Y||{});const UA=Y_(),_i=hr(UA.config.media);function VA(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 Ui,nl;class BA{constructor(e,r){_(this,Ui,void 0),_(this,nl,void 0),m(this,"getScreenShareConstraints",()=>{var n,i,s,o,a,d,h,p,f;const g=(n=c(this,Ui))==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,Ui))==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,Ui))==null?void 0:i.video;let h=pp.vga;if(typeof d=="string"?h=pp[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,nl,e),T(this,Ui,r)}getUpdatedVideoConstraints(e){return e}}Ui=new WeakMap,nl=new WeakMap;class gp extends Error{constructor(e,r,n){super(r),m(this,"constraints"),m(this,"name"),this.name=e,this.constraints=n}}class jA{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 HA=Object.defineProperty,WA=Object.getOwnPropertyDescriptor,ir=(t,e,r,n)=>{for(var i=n>1?void 0:n?WA(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&&HA(e,r,i),i},_s,vr,gd,vp;let Lt=(vp=class extends jA{constructor(t,e){super(),m(this,"availableDevices"),_(this,_s,void 0),_(this,vr,void 0),_(this,gd,void 0),T(this,gd,t),T(this,vr,new BA(t,e)),T(this,_s,new AbortController),this.availableDevices=[],this.getAvailableDevices()}get constraintsBuilder(){return c(this,vr)}destruct(){return u(this,null,function*(){var t;(t=c(this,_s))==null||t.abort()})}handlePermissionErrors(t,e){const r=up(t,e.name,e.message);return this.permissions[t]=r,w.emit(b.MEDIA_PERMISSION_ERROR,{message:r,constraints:e.constraints,kind:t}),r}getAudioAndVideoTrack(){return u(this,null,function*(){const t={audio:c(this,vr).getAudioConstraints().audio,video:c(this,vr).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 w.emit(b.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),w.emit(b.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",w.emit(b.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,vr).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=up("audio",o.name,o.message),d=new gp(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",w.emit(b.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 gp(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,vr).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===rl.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{yield this.handleGUMError("screenshare",r,t)}else yield this.handleGUMError("screenshare",r,t)}return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",w.emit(b.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,vr).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",w.emit(b.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===rl.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",w.emit(b.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,_s).signal})})}},_s=new WeakMap,vr=new WeakMap,gd=new WeakMap,vp);ir([y.trace("WebMediaInterface.destruct")],Lt.prototype,"destruct",1);ir([y.trace("WebMediaInterface.handlePermissionErrors")],Lt.prototype,"handlePermissionErrors",1);ir([y.trace("WebMediaInterface.getAudioAndVideoTrack")],Lt.prototype,"getAudioAndVideoTrack",1);ir([y.trace("WebMediaInterface.getAudioTrack")],Lt.prototype,"getAudioTrack",1);ir([y.trace("WebMediaInterface.getScreenShareTracks")],Lt.prototype,"getScreenShareTracks",1);ir([y.trace("WebMediaInterface.getVideoTrack")],Lt.prototype,"getVideoTrack",1);ir([y.trace("WebMediaInterface.getAvailableDevices")],Lt.prototype,"getAvailableDevices",1);ir([y.trace("WebMediaInterface.getAvailableDevicesByKind")],Lt.prototype,"getAvailableDevicesByKind",1);ir([y.trace("WebMediaInterface.getDevice")],Lt.prototype,"getDevice",1);ir([y.trace("WebMediaInterface.onDeviceChange")],Lt.prototype,"onDeviceChange",1);Lt=ir([ut("1600")],Lt);const Sg=Lt,vd={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}},$A=(t=0)=>new Promise(e=>setTimeout(e,t)),GA=(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):$A().then(d))}return d().then(h=>(i.disconnect(),h),h=>{throw i.disconnect(),h})},JA=typeof AudioContext!="undefined"?AudioContext:null;class ql{constructor(e){m(this,"_AudioContext"),m(this,"audioContext"),m(this,"_audioContextRefContainers");const r=V({AudioContext:JA},e);Object.defineProperties(this,{_AudioContext:{value:r.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:ql}})}getOrCreate(e){if(!this._audioContextRefContainers.has(e)&&(this._audioContextRefContainers.add(e),this._AudioContext&&!this.audioContext))try{this.audioContext=new this._AudioContext}catch{}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 yp=new ql,qA=3,KA=250;function zA(t){const e={},r=yp.getOrCreate(e);let n=qA;function i(){return n-=1,GA(r,t.srcObject,KA).then(s=>s?n>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{yp.release(e)})}function Ep(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 zA(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 YA=Object.defineProperty,QA=Object.getOwnPropertyDescriptor,XA=(t,e,r,n)=>{for(var i=n>1?void 0:n?QA(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};let il=class extends ns{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))}};il=XA([ut("1600")],il);const Tg=il;var ZA=Object.defineProperty,eM=Object.getOwnPropertyDescriptor,Kl=(t,e,r,n)=>{for(var i=n>1?void 0:n?eM(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&&ZA(e,r,i),i};const yd="[Dyte]nonSilentDeviceLabels";class Rc extends Tg{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 LA(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(vd.getItem(yd));if(o!=null&&o.devices.some(d=>d.label===n.label))return n;if(!(yield Ep(n))){const d=(r=o==null?void 0:o.devices.concat({label:n.label}))!=null?r:[{label:n.label}];return vd.setItem(yd,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 Ep(n))){const h=o.devices.concat({label:n.label});return vd.setItem(yd,JSON.stringify({devices:h})),l.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return l.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1})),n})}}Kl([y.trace("AudioMediaHandler.setTransformedTrack")],Rc.prototype,"setTransformedTrack",1);Kl([y.trace("AudioMediaHandler.onTrackEnded")],Rc.prototype,"onTrackEnded",1);Kl([y.trace("AudioMediaHandler.conditionallyChangeTrack")],Rc.prototype,"conditionallyChangeTrack",1);const tM=Rc;var Ns;class rM{constructor(e){_(this,Ns,void 0),m(this,"currentDevice"),T(this,Ns,e)}setupSpeaker(e){return u(this,null,function*(){var r;if(!(c(this,Ns)instanceof Sg))return;let n=e;if(e||([n]=yield c(this,Ns).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{}})))})}}Ns=new WeakMap;const nM=rM;class iM extends ns{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",w.emit(b.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch{}})}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 sM=iM;var oM=Object.defineProperty,aM=Object.getOwnPropertyDescriptor,Pc=(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},Ls,la;class ho extends Tg{constructor(e,r,n){super(e,r,n),_(this,Ls,void 0),_(this,la,{disablePerFrameCanvasRendering:!1}),T(this,Ls,new xA)}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,Ls).getTransformedVideoTrack(this.middlewares,this.mediaTrack,c(this,la)),this.emit("trackChanged")}catch(n){l.error("VideoMediaHandler.setTransformedTrack",{error:n}),this.transformedMediaTrack=this.mediaTrack}})}setVideoMiddlewareGlobalConfig(e){return u(this,null,function*(){T(this,la,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,Ls).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})}}Ls=new WeakMap,la=new WeakMap;Pc([y.trace("VideoMediaHandler.setTransformedTrack")],ho.prototype,"setTransformedTrack",1);Pc([y.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],ho.prototype,"setVideoMiddlewareGlobalConfig",1);Pc([y.trace("VideoMediaHandler.onTrackEnded")],ho.prototype,"onTrackEnded",1);Pc([y.trace("VideoMediaHandler.conditionallyChangeTrack")],ho.prototype,"conditionallyChangeTrack",1);const cM=ho,Sp=hr(Fl());var Ht,Vi,ua,xs;const Fs=class{constructor(t){if(_(this,Ht,void 0),_(this,Vi,void 0),_(this,ua,void 0),_(this,xs,void 0),!t)throw new C("Could not load preset.");T(this,Ht,t.config),T(this,ua,t.name),T(this,Vi,t.ui||hr(Fl().ui)),T(this,xs,t.permissions.plugins.config)}static fromResponse(t){return new Fs(t)}static default(){return new Fs(Sp)}static init(t,e=!0){return!t||e?new Fs(Sp):new Fs(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,Vi).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return c(this,Ht).viewType}get maxVideoStreams(){return c(this,Ht).maxVideoStreams}get maxScreenShareCount(){return c(this,Ht).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(c(this,xs)).filter(t=>c(this,xs)[t].disabled)}get designTokens(){return c(this,Vi).designTokens}get configDiff(){return c(this,Vi).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,Ht))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?n:_i.audio.enableStereo,enableHighBitrate:(a=(o=(s=(i=c(this,Ht))==null?void 0:i.media)==null?void 0:s.audio)==null?void 0:o.enableHighBitrate)!=null?a:_i.audio.enableHighBitrate},video:{quality:(f=(p=(h=(d=c(this,Ht))==null?void 0:d.media)==null?void 0:h.video)==null?void 0:p.quality)!=null?f:_i.video.quality,frameRate:(R=(v=(E=(g=c(this,Ht))==null?void 0:g.media)==null?void 0:E.video)==null?void 0:v.frameRate)!=null?R:_i.video.frameRate},screenshare:{quality:(W=(F=(L=(A=c(this,Ht))==null?void 0:A.media)==null?void 0:L.screenshare)==null?void 0:F.quality)!=null?W:_i.screenshare.quality,frameRate:(P=(S=(I=(H=c(this,Ht))==null?void 0:H.media)==null?void 0:I.screenshare)==null?void 0:S.frameRate)!=null?P:_i.screenshare.frameRate}}}get name(){return c(this,ua)}};let dM=Fs;Ht=new WeakMap,Vi=new WeakMap,ua=new WeakMap,xs=new WeakMap;var lM=Object.defineProperty,uM=Object.getOwnPropertyDescriptor,kg=(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&&lM(e,r,i),i},Us;class zl extends xt{constructor(e){super(),_(this,Us,void 0),m(this,"state","IDLE"),m(this,"playbackUrl"),m(this,"viewerCount"),T(this,Us,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,Us).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 He().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,Us).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 He().stopLivestreaming()}catch(e){throw l.error("DyteLivestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new C("Error while stopping livestream")}})}}Us=new WeakMap;kg([y.trace("livestream.start")],zl.prototype,"start",1);kg([y.trace("livestream.stop")],zl.prototype,"stop",1);var hM=Object.defineProperty,pM=Object.getOwnPropertyDescriptor,mM=(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},Vs,Vn;class _g{constructor(e,r){m(this,"livestream"),_(this,Vs,void 0),_(this,Vn,void 0),this.livestream=new zl(e),T(this,Vn,r),this.setupEvents()}fetchInitialLivestreamingState(){return u(this,null,function*(){const e=He(),{status:r,playbackUrl:n}=yield e.getActiveLivestream();this.livestream.playbackUrl=n,r==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING")})}setupEvents(){c(this,Vn).on(j.startedLivestream,e=>{this.livestream.playbackUrl=e.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING")}),c(this,Vn).on(j.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),c(this,Vn).on(j.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),c(this,Vn).on(j.roomPeerCount,e=>{this.livestream.viewerCount=e.count,this.livestream.emit("viewerCountUpdate",e.count)}),w.on(b.PEER_JOINED_INTERNAL,e=>u(this,null,function*(){var r;((r=e.flags)==null?void 0:r.hiddenParticipant)===!0&&e.recorderType==="LIVESTREAMER"&&(T(this,Vs,e.id),this.livestream.setLivestreamState("LIVESTREAMING"))})),w.on(b.PEER_CLOSED,e=>{e.id===c(this,Vs)&&(T(this,Vs,void 0),this.livestream.setLivestreamState("IDLE"))}),w.onAsync(b.LEAVE_MEDIA_ROOM,()=>u(this,null,function*(){this.livestream.playbackUrl||(l.info("Fetching livestreaming state on leave stage"),yield this.fetchInitialLivestreamingState())})),w.on(b.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){try{yield this.fetchInitialLivestreamingState()}catch{l.error("Error: LivestreamController.fetchLivestream")}}))}}Vs=new WeakMap,Vn=new WeakMap;mM([y.trace("LivestreamController.setupEvents")],_g.prototype,"setupEvents",1);var fM=Object.defineProperty,gM=Object.getOwnPropertyDescriptor,po=(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&&fM(e,r,i),i};const bg={maxInvocations:1,period:200},Yl={maxInvocations:5,period:1e3};var St,Bn,jn,sl,wg;class ss{constructor({name:e,socketHandler:r,meetingId:n}){_(this,sl),m(this,"name",""),_(this,St,{}),_(this,Bn,""),_(this,jn,void 0),m(this,"volatile"),m(this,"listeners",{}),this.name=e,T(this,jn,r),T(this,Bn,n)}set(e,r,n=!0,i=!1){return u(this,null,function*(){c(this,St)[e]=r,n&&c(this,jn).storeInsertKeys(c(this,Bn),this.name,[{key:e,payload:r}]),i&&(this.listeners[e]&&this.listeners[e].forEach(s=>s({[e]:c(this,St)[e]})),this.listeners["*"]&&this.listeners["*"].forEach(s=>s({[e]:c(this,St)[e]})))})}bulkSet(e){return u(this,null,function*(){e.forEach(({key:r,payload:n})=>{c(this,St)[r]=n}),c(this,jn).storeInsertKeys(c(this,Bn),this.name,e)})}update(e,r,n=!0){return u(this,null,function*(){ue(this,sl,wg).call(this,e,r,n)})}delete(e,r=!0,n=!1){return u(this,null,function*(){if(c(this,St)[e]&&delete c(this,St)[e],r)return c(this,jn).storeDeleteKeys(c(this,Bn),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,St)[r]&&delete c(this,St)[r]}),c(this,jn).storeDeleteKeys(c(this,Bn),this.name,e)})}get(e){if(c(this,St)[e])return c(this,St)[e]}getAll(){return c(this,St)}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,St,e)}}St=new WeakMap,Bn=new WeakMap,jn=new WeakMap,sl=new WeakSet,wg=function(t,e,r=!0){let n;const i=c(this,St)[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)};po([It(Yl)],ss.prototype,"set",1);po([It(bg)],ss.prototype,"bulkSet",1);po([It(Yl)],ss.prototype,"update",1);po([It(Yl)],ss.prototype,"delete",1);po([It(bg)],ss.prototype,"bulkDelete",1);var ji,Hi,ha,Ed,Qa,Qn,ol,Cg;class vM{constructor(e,r){_(this,ha),_(this,ol),m(this,"stores",new Map),_(this,ji,void 0),_(this,Hi,""),_(this,Qa,void 0),_(this,Qn,new Map),T(this,ji,r),T(this,Hi,e.getValue("meetingId")),T(this,Qa,e),ue(this,ol,Cg).call(this)}create(e){const r=new ss({name:e,socketHandler:c(this,ji),meetingId:c(this,Hi)});return c(this,ji).storeGetKeys(c(this,Hi),e,[]),new Promise((n,i)=>{const s=setTimeout(()=>i(Error("Failed")),3e3);c(this,Qn).set(e,{rejectTimeout:s,resolve:n,store:r})})}}ji=new WeakMap,Hi=new WeakMap,ha=new WeakSet,Ed=function(){return c(this,Qa).getValue("peerId")},Qa=new WeakMap,Qn=new WeakMap,ol=new WeakSet,Cg=function(){[J.storeInsertKeys,J.storeGetKeys,J.storeDeleteKeys].forEach(t=>{c(this,ji).on(t,e=>u(this,null,function*(){var r,n;if(e.pluginId!==c(this,Hi))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,Qn).get(e.storeName),a=this.stores.get(e.storeName)||(o==null?void 0:o.store);c(this,Qn).get(e.storeName)&&(this.stores.set(e.storeName,o.store),o.resolve(a),clearTimeout(o.rejectTimeout),c(this,Qn).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,Qn).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,ha,Ed)&&t!==J.storeGetKeys||s.set(o,d,!1,!0)}),t===J.storeDeleteKeys&&i.forEach(({key:o,peerId:a})=>{a!==c(this,ha,Ed)&&s.delete(o,!1,!0)}))}))})};function Xn(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 yM=Object.defineProperty,EM=Object.getOwnPropertyDescriptor,os=(t,e,r,n)=>{for(var i=n>1?void 0:n?EM(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&&yM(e,r,i),i};const SM=.8,TM=1.2;var bs,ws,No,Tn,bi,Br,Lo,kn,jr,Sd,xo,Td,kd,Tp,kp;let Lr=(kp=class extends xt{constructor(t,e,r,n){super(),_(this,Tn),_(this,xo),_(this,kd),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,bs,void 0),m(this,"supportsRemoteControl",!1),_(this,ws,void 0),m(this,"presetName"),_(this,No,void 0),_(this,Br,void 0),_(this,Lo,void 0),_(this,kn,new Map),_(this,jr,1),_(this,Sd,ur(H=>{if(!this.videoTrack)return;const{clientWidth:I,clientHeight:S}=H,{width:P,height:D}=this.videoTrack.getSettings();if(!P||!D)return;const ae=D/S,De=P/I,$=Math.max(ae,De);$>TM&&c(this,jr)===1?(T(this,jr,0),w.emit(b.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:c(this,jr)})):$<SM&&c(this,jr)===0&&(T(this,jr,1),w.emit(b.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:c(this,jr)}))},2e3)),T(this,No,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=$d,T(this,ws,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,bs,!1),T(this,Br,r),T(this,Lo,n),this.setupEvents()}get clientSpecificId(){return this.customParticipantId}get stageStatus(){return c(this,ws)}get roomJoined(){var t;return((t=c(this,Tn,bi))==null?void 0:t.roomJoined)===!0}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(l.info("DyteParticipant::setVideoEnabled::videoUpdate",V({},Xn(this))),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(l.info("DyteParticipant::setAudioEnabled::audioUpdate",V({},Xn(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,kd,Tp))}pin(){return u(this,null,function*(){if(!this.roomJoined)throw new C("Can`t pin participant without joining room");if(!c(this,Br).permissions.pinParticipant)throw new C("You do not have permission to pin participants.");return c(this,Tn,bi).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,Br).permissions.pinParticipant)throw new C("You do not have permission to unpin participants.");return c(this,Tn,bi).pinPeer(null)})}setIsPinned(t,e=!0){T(this,bs,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,Br).permissions.canDisableParticipantAudio)return c(this,Tn,bi).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,Br).permissions.kickParticipant){yield w.emitAsync(b.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,Br).permissions.canDisableParticipantVideo)return c(this,Tn,bi).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,Lo).getUserPermissions(this.userId)})}setStageStatus(t){T(this,ws,t),this.emit("stageStatusUpdate",this)}get isPinned(){return c(this,bs)}registerVideoElement(t){var e,r;let n;(r=(e=c(this,kn).get(t))==null?void 0:e.observer)==null||r.disconnect(),"ResizeObserver"in window&&(n=new ResizeObserver(()=>c(this,Sd).call(this,t)),n.observe(t)),c(this,kn).set(t,{observer:n}),ue(this,xo,Td).call(this,t)}deregisterVideoElement(t){var e,r;t.srcObject=void 0,(r=(e=c(this,kn).get(t))==null?void 0:e.observer)==null||r.disconnect(),c(this,kn).delete(t)}},bs=new WeakMap,ws=new WeakMap,No=new WeakMap,Tn=new WeakSet,bi=function(){return c(this,No).getValue("roomNodeClient")},Br=new WeakMap,Lo=new WeakMap,kn=new WeakMap,jr=new WeakMap,Sd=new WeakMap,xo=new WeakSet,Td=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},kd=new WeakSet,Tp=function(){Array.from(c(this,kn).keys()).forEach(ue(this,xo,Td))},kp);os([y.trace("DyteParticipant.disableAudio")],Lr.prototype,"disableAudio",1);os([y.trace("DyteParticipant.kick")],Lr.prototype,"kick",1);os([y.trace("DyteParticipant.disableVideo")],Lr.prototype,"disableVideo",1);os([y.trace("DyteParticipant.getPermissions")],Lr.prototype,"getPermissions",1);os([y.trace("DyteParticipant.setStageStatus")],Lr.prototype,"setStageStatus",1);Lr=os([ut("1200")],Lr);class Fo extends vg{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 Hn;class kM extends ns{constructor(){super(),_(this,Hn,void 0),T(this,Hn,new Map)}__set(e,r){return c(this,Hn).set(e,r)}__clear(){return c(this,Hn).clear()}get(e){return c(this,Hn).get(e)}toArray(){return Array.from(c(this,Hn).values())}}Hn=new WeakMap;function _M(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 _p=1080,bp=1920,bM=(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 or,Bs,vt,Zr,Oe,en,tn,Qt,Xe;class wM extends xt{constructor(e,r){super(),_(this,or,void 0),_(this,Bs,void 0),_(this,vt,void 0),_(this,Zr,void 0),_(this,Oe,{height:_p,width:bp}),_(this,en,{brand:"#2160FD",background:"#141414",videoBackground:"#191919",textOnBrand:"#EEEEEE"}),_(this,tn,void 0),_(this,Qt,{}),_(this,Xe,void 0),m(this,"cleanupEventListeners",()=>{c(this,Bs).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)}),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,Xe).videoEnabled?c(this,Xe).disableVideo():c(this,Xe).enableVideo(),this.emit("cameraToggled")),n==="MIC"&&(c(this,Xe).audioEnabled?c(this,Xe).disableAudio():c(this,Xe).enableAudio(),this.emit("micToggled")),n==="END"&&(w.emit(b.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,Qt)!==void 0&&this.paintCanvas(),c(this,tn)!==void 0&&T(this,tn,requestAnimationFrame(()=>this.animate()))}),m(this,"disable",()=>{this.cleanupEventListeners(),cancelAnimationFrame(c(this,tn)),document.body.removeChild(c(this,vt)),T(this,tn,void 0),document.exitPictureInPicture()}),T(this,Bs,e),T(this,Xe,r),T(this,en,{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,vt,document.createElement("div")),c(this,vt).style.width="0.1px",c(this,vt).style.height="0.1px",c(this,vt).style.overflow="hidden",c(this,vt).style.position="absolute",c(this,vt).style.bottom="0",c(this,vt).style.right="0",c(this,vt).style.opacity="0",c(this,vt).appendChild(c(this,Zr))}setupEventListeners(){c(this,Bs).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 e=document.createElement("canvas");e.height=c(this,Oe).height,e.width=c(this,Oe).width,T(this,or,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,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 e=Object.values(c(this,Qt)),r=e.filter(n=>n.pinned);return r.length===1?r:e}drawEmptyTile(e,r,n,i,s){if(c(this,or)===void 0)return;const o=c(this,or).getContext("2d"),a=c(this,or).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,en).videoBackground,o.strokeStyle=c(this,en).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,en).brand,o.fill()),i&&(o.fillStyle=c(this,en).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,or)===void 0)return;const i=c(this,or).getContext("2d");i.fillStyle=c(this,en).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]=bM(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,vt))try{document.body.removeChild(c(this,vt))}catch{}this.removeAllSources(),T(this,or,void 0),T(this,Zr,void 0),T(this,tn,void 0)}init({height:e,width:r}={}){this.createCanvas(),this.setupMediaSessionEvents();const n=document.createElement("video");T(this,Oe,{height:e!=null?e:_p,width:r!=null?r:bp}),n.height=c(this,Oe).height,n.width=c(this,Oe).width,n.autoplay=!0,n.muted=!0,n.srcObject=c(this,or).captureStream(24),T(this,Zr,n),c(this,Zr).onloadedmetadata=()=>{try{this.emit("pipStarted"),c(this,Zr).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch{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,Qt)[e]!==void 0&&(c(this,Qt)[e].enabled=!0)}disableSource(e){c(this,Qt)[e]!==void 0&&(c(this,Qt)[e].enabled=!1)}addSource(e,r,n,i=!1,s=void 0){i&&this.removePinnedSource(),c(this,Qt)[e]={id:e,element:r,enabled:n,pinned:i,displayText:s?_M(s):void 0}}removeSource(e){delete c(this,Qt)[e]}removePinnedSource(){const[e]=this.getSources();e&&this.removeSource(e.id)}removeAllSources(){T(this,Qt,{})}enable(){this.setupEventListeners(),this.updateMediaSession("CAMERA",c(this,Xe).videoEnabled),this.updateMediaSession("MIC",c(this,Xe).audioEnabled),document.body.appendChild(c(this,vt)),T(this,tn,requestAnimationFrame(()=>this.animate())),c(this,Zr).requestPictureInPicture()}}or=new WeakMap,Bs=new WeakMap,vt=new WeakMap,Zr=new WeakMap,Oe=new WeakMap,en=new WeakMap,tn=new WeakMap,Qt=new WeakMap,Xe=new WeakMap;var Zn={},Ac={},CM=Su&&Su.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ac,"__esModule",{value:!0});Ac.Logger=void 0;const wi=CM(cr),Ci="awaitqueue";class IM{constructor(e){e?(this._debug=(0,wi.default)(`${Ci}:${e}`),this._warn=(0,wi.default)(`${Ci}:WARN:${e}`),this._error=(0,wi.default)(`${Ci}:ERROR:${e}`)):(this._debug=(0,wi.default)(Ci),this._warn=(0,wi.default)(`${Ci}:WARN`),this._error=(0,wi.default)(`${Ci}: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}}Ac.Logger=IM;Object.defineProperty(Zn,"__esModule",{value:!0});var es=Zn.AwaitQueue=Zn.AwaitQueueRemovedTaskError=Zn.AwaitQueueStoppedError=void 0;const RM=Ac,Hr=new RM.Logger;class Ql extends Error{constructor(e){super(e!=null?e:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Ql)}}Zn.AwaitQueueStoppedError=Ql;class Mc extends Error{constructor(e){super(e!=null?e:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Mc)}}Zn.AwaitQueueRemovedTaskError=Mc;class PM{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,Hr.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{}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),Hr.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),Hr.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(){Hr.debug("stop()"),this.stopping=!0;for(const e of this.pendingTasks.values())Hr.debug(`stop() | stopping task [name:${e.name}]`);this.stopping=!1}remove(e){Hr.debug(`remove() [taskIdx:${e}]`);const r=Array.from(this.pendingTasks.values())[e];if(!r){Hr.debug(`stop() | no task with given idx [taskIdx:${e}]`);return}r.reject(new Mc)}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(Hr.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)}})}}es=Zn.AwaitQueue=PM;var pa;class Ig{constructor(){m(this,"meetingTitle"),m(this,"roomName"),m(this,"roomUUID"),_(this,pa,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,pa)}get socketState(){return{state:void 0,reconnected:!1,reconnectionAttempt:void 0}}get mediaState(){return c(this,pa).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.")})}}pa=new WeakMap;var Dr=(t=>(t.INITIALIZING="INITIALIZING",t.INITIALIZED="INITIALIZED",t.NOT_INITIALIZED="NOT_INITIALIZED",t))(Dr||{});class Rg extends wt.EventEmitter{}class ni extends wt.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 AM(t,e){const r=new Error(e);return r.name=t,r}class ii extends C{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,ii):this.stack=new Error(e).stack}}class ot extends C{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,ot):this.stack=new Error(e).stack}}var ma,fa,ga,va,wr,ya,Ea,dr,Bi,Sa,Ta,ka,_d,al,Pg,cl,Ag;class Mg extends ni{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,ka),_(this,al),_(this,cl),m(this,"rtpReceiver"),m(this,"observer"),_(this,ma,void 0),_(this,fa,void 0),_(this,ga,void 0),_(this,va,void 0),_(this,wr,void 0),_(this,ya,void 0),_(this,Ea,void 0),_(this,dr,void 0),_(this,Bi,void 0),_(this,Sa,void 0),_(this,Ta,void 0),T(this,ma,e),T(this,fa,r),T(this,Ea,o),T(this,Ta,d),T(this,Sa,i),T(this,va,s),T(this,wr,!1),T(this,ga,n),T(this,dr,a),T(this,Bi,h!=null?h:!1),T(this,ya,p),this.observer=new ni,this.rtpReceiver=f,ue(this,al,Pg).call(this)}get id(){return c(this,ma)}get peerId(){return c(this,Sa)}get localId(){return c(this,fa)}get producerId(){return c(this,ga)}get producingTransportId(){return c(this,va)}get closed(){return c(this,wr)}get kind(){return c(this,dr).kind}get track(){return c(this,dr)}get paused(){return c(this,Bi)}get remotelyPaused(){return this.paused}get appData(){return c(this,Ta)}close(e){c(this,wr)||(l.debug("Consumer::close() with reason:",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,closureReason:e,kind:this.kind}}),T(this,wr,!0),c(this,ya)||ue(this,cl,Ag).call(this),this.emit("close",e),this.observer.safeEmit("close",e))}getStats(){return u(this,null,function*(){if(c(this,wr))throw new ot("closed");return c(this,Ea).getReceiverStats(this.localId)})}pause(){if(l.debug("consumer::pause()",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}),c(this,wr)){l.error("consumer::pause() | Consumer closed",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}});return}T(this,Bi,!0),c(this,dr).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,wr)){l.error("Consumer::resume() | Consumer closed",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}});return}T(this,Bi,!1),c(this,dr).enabled=!0,this.observer.safeEmit("resume")}}ma=new WeakMap,fa=new WeakMap,ga=new WeakMap,va=new WeakMap,wr=new WeakMap,ya=new WeakMap,Ea=new WeakMap,dr=new WeakMap,Bi=new WeakMap,Sa=new WeakMap,Ta=new WeakMap,ka=new WeakSet,_d=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")},al=new WeakSet,Pg=function(){c(this,dr).addEventListener("ended",ue(this,ka,_d).bind(this))},cl=new WeakSet,Ag=function(){try{c(this,dr).removeEventListener("ended",ue(this,ka,_d)),c(this,dr).stop()}catch(t){l.error("Consumer::destroyTrack()",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind},error:t})}};let MM=class extends Mg{};const wp=t=>new Promise(e=>setTimeout(e,t));function pr(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 wp(o*(a+1)):i==="exponential"&&(yield wp(o*(a+Math.max(0,a-1))));else break}a+=1}return n(d)}))})}function Xa(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 DM(t,e){return typeof t=="undefined"?e:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(t):JSON.parse(JSON.stringify(t))}function Dg(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function dl(t){return Math.random().toString(36).substring(2,2+t)}const Uo=1;function Cp(t){const e=t;return delete e.payload._bolt,e}function OM(t){return t.payload&&Dg(t.payload)}function Za(t){var e,r;return OM(t)&&(r=(e=t.payload._bolt)==null?void 0:e.id)!=null?r:""}var Wn;const js=class extends wt.EventEmitter{constructor(t,e,r){super(),m(this,"channel"),m(this,"queue"),m(this,"serverProtocolVersion"),_(this,Wn,new Map),m(this,"respond",(n,i,s=!1)=>{let o;s?o=js.createErrorResponse(n,i):o=js.createResponse(n,i),this.channel.send(JSON.stringify(o))}),m(this,"notify",n=>{const i=js.createNotification(n);this.channel.send(JSON.stringify(i))}),m(this,"request",n=>u(this,null,function*(){const i=js.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=si();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,Wn).has(n.id)||c(this,Wn).set(n.id,[]);const s=c(this,Wn).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,Wn).get(n.id),a=o==null?void 0:o.reduce((h,p)=>h+p.chunk,"");c(this,Wn).delete(n.id);const d=JSON.parse(a);if(!d.payload||!Dg(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(Cp(n)):s.resolve(Cp(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:dl(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1}),this.label=e,this.transportId=r,this.channel=t,this.queue=new Map}};let Hs=js;Wn=new WeakMap,m(Hs,"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:dl(8),type:"REQUEST",version:Uo}})}}),m(Hs,"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:Uo}})}}),m(Hs,"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:dl(8),type:"NOTIFY",version:Uo}})}}),m(Hs,"createErrorResponse",(t,e)=>({type:"error",payload:{error:e.message,_bolt:{id:t,type:"RESPONSE",version:Uo}}}));const ll="transport closed";class Og extends ni{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=DM(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 es,this.observer=new ni,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 Hs(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(ll).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(ll)}),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 ot("closed");return this.handler.getTransportStats()})}restartIce(){return u(this,null,function*(){if(l.debug("restartIce()"),this.closed)throw new ot("closed");return this.handler.restartIce()})}updateIceServers(){return u(this,arguments,function*({iceServers:e}={}){if(l.debug("updateIceServers()"),this.closed)throw new ot("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=Tl(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=cy(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 AM("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 Ng extends ni{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 ni,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===ll){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 ot("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 ot("closed")}else if(r&&r.readyState==="ended")throw new ot("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 ot("closed");if(this._kind!=="video")throw new ii("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 ot("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 NM=class extends Ng{},LM=class extends Og{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 ot("closed");if(this.direction!=="recv")throw new ii("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}))}),Xa(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 MM({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 Xa(t.map(e=>u(this,null,function*(){return pr(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 ii("not a sending Transport");if(t.readyState==="ended")throw new ot("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 NM({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 Xl extends ni{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 Zl extends Xl{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 Zl}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 ec extends Xl{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 ec(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 eu extends Xl{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 eu}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 xM(){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=Wp.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 Lg{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=xM(),e)l.debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=Zl.createFactory();break;case"Safari12":this.handlerFactory=eu.createFactory();break;case"Firefox60":this.handlerFactory=ec.createFactory({supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=ec.createFactory({supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}const n=this.handlerFactory();this._handlerName=n.name,n.close(),this._observer=new wt}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 FM=class extends Lg{createTransport({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s,config:o}){const a=si(),d=new LM({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 yt;class UM{constructor(e){_(this,yt,void 0),T(this,yt,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,yt).sendMessagePromiseWithTimeout({event:ie.joinRoom,protobuf:Af.toBinary(s),timeout:5e3})).payload})}connectTransport(e){return u(this,null,function*(){const r=(yield c(this,yt).sendMessagePromise(ie.createWebRTCTransport,If.toBinary(e))).payload,{transportId:n,description:i}=Vl.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,yt).sendMessagePromise(ie.produce,Nf.toBinary(e))).payload,s=Jf.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,yt).sendMessagePromise(ie.consume,Of.toBinary(e))).payload,{consumerIdsMap:{map:n}}=Gf.fromBinary(r);return n})}closeProducer(e){return u(this,null,function*(){const r=(yield c(this,yt).sendMessagePromise(ie.closeProducer,xf.toBinary(e))).payload,{description:n}=qf.fromBinary(r);return n})}closeConsumer(e){return u(this,null,function*(){return(yield c(this,yt).sendMessagePromise(ie.closeConsumer,Ff.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,yt).sendMessagePromise(ie.hostControlPeer,jf.toBinary(n))).payload;if(!i)return!1;const{status:s}=Yf.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,yt).sendMessagePromise(ie.hostControlAllPeers,Hf.toBinary(r))).payload;if(!n)return!1;const{status:i}=Qf.fromBinary(n);return i==="success"})}kickAll(){return u(this,null,function*(){const e={},r=(yield c(this,yt).sendMessagePromise(ie.kickAll,Vf.toBinary(e))).payload;if(!r)return!1;const{status:n}=zf.fromBinary(r);return n==="success"})}kickPeer(e){return u(this,null,function*(){const r=(yield c(this,yt).sendMessagePromise(ie.kickPeer,Uf.toBinary(e))).payload;if(!r)return!1;const{status:n}=Kf.fromBinary(r);return n==="success"})}changeDisplayName(e){return u(this,null,function*(){const r=(yield c(this,yt).sendMessagePromise(ie.changeDisplayName,Bf.toBinary(e))).payload;if(!r)return!1;const{status:n}=Xf.fromBinary(r);return n==="success"})}notifySelfJoinComplete(){return u(this,null,function*(){const e={},r=(yield c(this,yt).sendMessagePromise(ie.selfJoinComplete,Mf.toBinary(e))).payload;return $a.fromBinary(r)})}}yt=new WeakMap;const VM=Error("task execution aborted");class BM{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(VM),this.executor.then(n=>e(n))})})}}let Ip=0;const Vo=new Map;class Gi{static execute(e){const r=Ip;Ip+=1;const n=new BM(r,e);return Vo.set(r,n),{id:r,value:n.execute().finally(()=>Vo.delete(r))}}static stop(e){const r=Vo.get(e);r&&(r.cancel(),Vo.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||{}),ts=(t=>(t[t.HIVE=1]="HIVE",t[t.ROOM_NODE=2]="ROOM_NODE",t[t.CF=3]="CF",t))(ts||{});const jM=2e3;var rn;class HM extends Rg{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,rn,void 0),T(this,rn,e),this._device=new FM({}),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 UM(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 He().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&&Gi.stop(v.id),s){case"send":{const R=Gi.execute(this.createSendTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(o=c(this,rn).getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(h=(d=(a=c(this,rn).getValue("defaults").mediaConfiguration)==null?void 0:a.audio)==null?void 0:d.enableHighBitrate)!=null?h:!1,enableStereo:(g=(f=(p=c(this,rn).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=Gi.execute(this.createRecvTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(E=c(this,rn).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 pr((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 pr((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?Nt.SUBSCRIBER:Nt.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)},jM);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,Za(i),n,e);break}case"handshake":{const a={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,Za(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{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=Tl(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:Nt.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{}g.set(E,{consumerId:v.consumerId,trackId:(R=v.producerTrack)==null?void 0:R.trackId,streamId:v.producerTrack.streamId,kind:v.producerState.kind===bt.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{}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===bt.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)===Dr.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:Dr.INITIALIZING});try{const o=yield this._sendTransport.produce(r);return(i=r.appData)!=null&&i.e2ee&&w.emit(b.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:Nt.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}}),[Y.MIC,Y.WEBCAM].includes(e)||n()}),this._producers.set(e,o),this._producerStatus.set(e,{trackId:r.track.id,status:Dr.INITIALIZED}),this.reconfigureWebcamLayers(),o.track}catch(o){throw this._producerStatus.set(e,{status:Dr.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(Y.WEBCAM);e&&(yield this._switchProducerSpatialLayer(e,this.producers.get(Y.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),w.emit(b.CONSUMER_CLOSED,{id:e.id})})),this._consumers.set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),w.emit(b.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 pr(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&&w.emit(b.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,rn).getValue("modules").e2ee.enabled&&w.emit(b.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,Wa.toBinary(r)),e.pause(),w.emit(b.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,Wa.toBinary(n)),r.resume(),w.emit(b.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:Nt.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,Rf.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(),w.emit(b.CONSUMER_PAUSED,{id:i.id})):(i.resume(),w.emit(b.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{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>20*1e3&&(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),w.emit(b.TRANSPORT_STATE_UPDATE,V({transport:n},this.transportState[n]))}}rn=new WeakMap;var WM=Object.defineProperty,$M=Object.getOwnPropertyDescriptor,de=(t,e,r,n)=>{for(var i=n>1?void 0:n?$M(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&&WM(e,r,i),i};const _n={joinAttempted:!1},GM=3e3;var Ce,he,yr,Ii,bn,wn,Bo,jo,Ho,Wr,Cs,qt,Er,$r,Rp;const xg=(Rp=class extends Ig{constructor(t,e){var r,n;super(),_(this,Er),_(this,Ce,void 0),_(this,he,void 0),_(this,yr,void 0),_(this,Ii,void 0),_(this,bn,void 0),_(this,wn,void 0),_(this,Bo,void 0),_(this,jo,void 0),_(this,Ho,void 0),_(this,Wr,void 0),_(this,Cs,void 0),_(this,qt,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,Ce,a),T(this,yr,!1),T(this,qt,void 0),T(this,he,new HM(t,a)),this.maxPreferredStreams=6,this.activatedProducingPeerIds=new Set,T(this,Wr,new Set),T(this,Ii,!1),T(this,bn,0),T(this,wn,new es),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,Bo,ur(()=>u(this,null,function*(){if(!_n.joinAttempted)return;const{roomJoined:h}=yield this.joinRoom(this.peerDisplayName,this.roomUUID,{},!0,!0);h&&(w.emit(b.RESET_PRODUCER_STATE),w.emit(b.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3})),T(this,jo,ur(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports(["send"]),l.info("send transport reconected!"),w.emit(b.RESET_PRODUCER_STATE)}),1e3)),T(this,Ho,ur(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports(["recv"]),l.info("recv transport reconnected!"),this.activatedProducingPeerIds=new Set,w.emit(b.REFRESH_GRID,!0)}),1e3))}get socketState(){return c(this,Ce).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 xg(t,{legacyMode:r,authToken:i,socketClient:o,roomName:n,meetingTitle:s})})}get sfuHandler(){return c(this,he)}get rejoinRoom(){return c(this,Bo)}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,Wr).clear(),this.activatedProducingPeerIds.clear(),t&&(c(this,wn).stop(),this.sfuHandler.stopAllTransports(),this.sfuHandler.reset(),T(this,wn,new es))}reconnectTransport(t){return u(this,null,function*(){l.info(`HiveNodeClient::Room joining state: ${c(this,yr)}`),!(!t||c(this,yr))&&(t.direction==="send"?yield c(this,jo).call(this,t):yield c(this,Ho).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){_n.joinAttempted=!0,T(this,yr,!0),this.reset(s);const a=He().ipInfo;if(a!=null&&a.loc&&!c(this,Cs)){const h=a.loc.split(",");T(this,Cs,{latitude:parseFloat(h[0]),longitude:parseFloat(h[1])})}let d;try{return d=yield c(this,wn).push(()=>this._joinRoom(r,n,i,o,c(this,Cs)),"joinRoom"),d}catch{d={roomJoined:!1}}return d.roomJoined||w.emit(b.ROOM_NODE_FAILED),d})}_partialJoinRoom(t,e,r=!1,n=void 0){return u(this,null,function*(){const i=He().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 pr((o,a)=>(c(this,Ce).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,wn).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,Ii,!0),T(this,yr,!1),this.maxPreferredStreams=t!=null?t:6,w.emit(b.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,Ii,!1),_n.joinAttempted=!1;const t={closeRoom:!1};c(this,Ce).sendMessagePromise(ie.leaveRoom,Df.toBinary(t)).then(e=>{var r;(r=$f.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(Y.WEBCAM)){const n=c(this,he).producers.get(Y.WEBCAM);if(!n.closed&&!navigator.isReactNative)return yield n.replaceTrack({track:t}),yield this.resumeWebcam(),t;yield c(this,he).removeProducer(Y.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 mp||(n=320),e.encodings=mp[n]}const r=()=>{l.info("Disabling video due to the producer closure"),this.disableWebcam()};return c(this,he).createProducer(Y.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(Y.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(Y.SCREENSHARE_AUDIO,s,i)}B.screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new ot("track undefined");if(c(this,he).producers.has(Y.MIC)){const n=c(this,he).producers.get(Y.MIC);if(!n.closed&&!navigator.isReactNative){yield n.replaceTrack({track:t}),yield this.resumeMic();return}yield c(this,he).removeProducer(Y.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(Y.MIC,e,r)}catch(e){throw new C(e)}})}pauseMic(){const t=c(this,he).producers.get(Y.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,Ce).sendMessage(ie.toggleProducer,cn.toBinary(e))}pauseWebcam(){return u(this,null,function*(){const t=c(this,he).producers.get(Y.WEBCAM);if(!t){l.error("pauseWebcam::could_not_find_webcam_producer");return}t.pause();const e={producerId:t.id,pause:!0};c(this,Ce).sendMessage(ie.toggleProducer,cn.toBinary(e))})}resumeMic(){return u(this,null,function*(){const t=c(this,he).producers.get(Y.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&&w.emit(b.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,Ce).sendMessage(ie.toggleProducer,cn.toBinary(e))})}resumeWebcam(){return u(this,null,function*(){const t=c(this,he).producers.get(Y.WEBCAM);if(!t){l.error("resumeWebcam::could_not_find_webcam_producer");return}t.resume(),t.appData.e2ee&&w.emit(b.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,Ce).sendMessage(ie.toggleProducer,cn.toBinary(e))})}disableWebcam(){return u(this,null,function*(){yield c(this,he).removeProducer(Y.WEBCAM)})}disableMic(){return u(this,null,function*(){yield c(this,he).removeProducer(Y.MIC)})}disableScreenShare(){return u(this,null,function*(){l.info("screen_sharing_stopped"),B.screenShareStop(),yield c(this,he).removeProducer(Y.SCREENSHARE_VIDEO),yield c(this,he).removeProducer(Y.SCREENSHARE_AUDIO),c(this,Wr).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(Y.WEBCAM,!1),this.shareWebcam(t)),e&&(yield c(this,he).removeProducer(Y.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,Ce).sendMessagePromise(ie.globalPinPeer,Lf.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,Wr).add(t.consumerPeerId),c(this,Wr).size}switchConsumersToLayer(t,e){return u(this,null,function*(){this.sfuHandler.switchConsumersToLayer(t,e)})}handleSocketEvents(){return u(this,null,function*(){c(this,Ce).on(ie.peerProducerCreateBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:r}=Zf.fromBinary(t);if(e===this.peerId)return;l.info(`producer created broadcast: ${e}, producer state: ${r}`),w.emit(b.NEW_PRODUCER,{peerId:e,producer:ne(V({},r),{kind:r.kind===bt.AUDIO?"audio":"video"})})}catch(e){l.error("error in peer-producer-create-broadcast",{error:e})}}),c(this,Ce).on(ie.peerProducerToggleBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:{kind:r,pause:n,producerId:i}}=eg.fromBinary(t),s=r===bt.AUDIO?"audio":"video";if(l.info(`producer toggle broadcast: ${e}, producerId: ${i}, kind:${s}, paused:${n}`),e===this.peerId&&n){w.emit(s==="audio"?b.MUTE_ALL:b.MUTE_ALL_VIDEO);return}w.emit(b.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(),w.emit(b.CONSUMER_PAUSED,{id:o.id})):(o.resume(),w.emit(b.CONSUMER_RESUMED,{id:o.id})))})}catch(e){l.error("error in producer toggle broadcast handler",{error:e})}}),c(this,Ce).on(ie.peerLeaveBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e}=Ga.fromBinary(t);if(e===this.peerId)return;l.info(`peer left broadcast:${e}`),c(this,Wr).delete(e),this.sfuHandler.cleanupConsumers(e),w.emit(b.PEER_CLOSED,{id:e})}catch(e){l.error("error in peer left broadcast",{error:e})}}),c(this,Ce).on(ie.peerProducerCloseBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:{producerId:r}}=tg.fromBinary(t);if(e===this.peerId)return;l.info(`producer closed broadcast:${e}`),w.emit(b.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),w.emit(b.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,Ce).on(ie.mediaRoomTerminationBroadcastResponse,()=>{!this.roomJoined&&!c(this,yr)&&!c(this,Ii)||(l.warn("media hub termination broadcast received, rejoining room"),w.emit(b.ROOM_NODE_DISCONNECTED),this.rejoinRoom())})})}handleSocketConnectionEvents(){c(this,Ce).onStateEvent("connected",()=>u(this,null,function*(){l.info("SocketService::Connected to socket-edge"),c(this,qt)&&(clearTimeout(c(this,qt)),T(this,qt,void 0)),ue(this,Er,$r).call(this,"connected")})),c(this,Ce).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?w.emit(b.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:_n.joinAttempted}):T(this,qt,setTimeout(()=>{w.emit(b.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:_n.joinAttempted}),T(this,qt,void 0)},GM)),ue(this,Er,$r).call(this,"disconnected"),this.roomJoined=!1}),c(this,Ce).onStateEvent("reconnecting",()=>u(this,null,function*(){l.info("SocketService::Reconnecting to socket-edge"),ue(this,Er,$r).call(this,"reconnecting")})),c(this,Ce).onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){l.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),ue(this,Er,$r).call(this,"reconnectAttempt",e)})),c(this,Ce).onStateEvent("reconnectFailure",({attempt:t})=>{l.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),ue(this,Er,$r).call(this,"reconnectFailure",t)}),c(this,Ce).onStateEvent("reconnected",()=>u(this,null,function*(){l.info("SocketService::Reconnected to socket-edge",{connectionState:_n}),c(this,qt)&&(clearTimeout(c(this,qt)),T(this,qt,void 0)),w.emit(b.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:_n.joinAttempted}),ue(this,Er,$r).call(this,"reconnected")})),c(this,Ce).onStateEvent("failed",()=>u(this,null,function*(){l.info("SocketService::Failed to connect to socket-edge"),w.emit(b.SOCKET_SERVICE_FAILED),ue(this,Er,$r).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,bn)>3&&!t){l.warn("cannot rejoin more already rejoined 3 times");return}if(c(this,yr)&&!t){l.warn("room joining in progress, cannot start rejoining");return}T(this,bn,c(this,bn)+1),l.warn(`rejoining the room because transports are failing. [rejoinCount: ${c(this,bn)}]`),this.roomJoined=!1,w.emit(b.ROOM_NODE_DISCONNECTED),this.rejoinRoom()})}handleCallstatsEvents(){B.onSafeInitialization(()=>{B.onConsumerScore(t=>{t.forEach((e,r)=>{const n=this.sfuHandler.consumers.get(r);n&&w.emit(b.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&&w.emit(b.PRODUCER_SCORE_UPDATE,{id:r,kind:n.kind,appData:n.appData,score:+(e*10).toFixed()})})})})}},Ce=new WeakMap,he=new WeakMap,yr=new WeakMap,Ii=new WeakMap,bn=new WeakMap,wn=new WeakMap,Bo=new WeakMap,jo=new WeakMap,Ho=new WeakMap,Wr=new WeakMap,Cs=new WeakMap,qt=new WeakMap,Er=new WeakSet,$r=function(t,e){let r;const{reconnected:n}=c(this,Ce).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&&(w.emit(b.SOCKET_STATE_UPDATE,r),c(this,Ce).connectionState=r)},Rp);let oe=xg;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 JM{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 ul{constructor(){m(this,"_activeSpeakerPeers"),m(this,"_compulsoryPeers"),this._activeSpeakerPeers=new JM,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 qM=Object.defineProperty,KM=Object.getOwnPropertyDescriptor,Ut=(t,e,r,n)=>{for(var i=n>1?void 0:n?KM(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&&qM(e,r,i),i};const zM=["ACTIVE_GRID","PAGINATED","MANUAL"];var Ri,Vt,Kt,Cn,Bt,Pp;let kt=(Pp=class extends xt{constructor(t,e,r,n){var i;super(),_(this,Vt),m(this,"waitlisted"),m(this,"joined"),m(this,"active"),m(this,"pinned"),m(this,"all"),m(this,"pip"),_(this,Ri,void 0),_(this,Cn,void 0),_(this,Bt,void 0),m(this,"viewMode"),m(this,"currentPage"),m(this,"lastActiveSpeaker"),m(this,"selectedPeers",new ul),T(this,Ri,t),T(this,Cn,e),T(this,Bt,r),this.waitlisted=new Fo,this.joined=new Fo,this.active=new Fo,this.pinned=new Fo,this.selectedPeers=new ul,this.all=new kM,this.viewMode="ACTIVE_GRID",this.currentPage=0,((i=n==null?void 0:n.pip)==null||i)&&(this.pip=new wM(t,e)),this.setupEvents()}get roomJoined(){var t;return((t=c(this,Vt,Kt))==null?void 0:t.roomJoined)===!0}setupEvents(){w.on(b.E2EE_ACTIVE_CONSUMER,({peerId:t})=>{var e;((e=c(this,Ri).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,Vt,Kt).maxPreferredStreams}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new C("0 <= Max active participants count limit <= 24");c(this,Vt,Kt).maxPreferredStreams=t,c(this,Cn).roomJoined&&w.emit(b.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,Bt).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,Bt).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,Bt).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=>zM.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,Vt,Kt)instanceof oe))throw new C("Manual Subscription is not enabled for your Organization. Please contact support.");this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,w.emit(b.UPDATE_ACTIVE,{page:this.currentPage})):t==="ACTIVE_GRID"&&(this.currentPage=0,w.emit(b.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,Vt,Kt).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,Vt,Kt).deactivatePeers(p,"manual"),this.active.delete(h.id);const f=this.joined.get(h.id);f.manualProducerConfig=$d});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,Vt,Kt).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=$d,yield c(this,Vt,Kt).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,w.emit(b.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,Cn).permissions.canAllowParticipantAudio)return c(this,Vt,Kt).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,Cn).permissions.canAllowParticipantVideo)return c(this,Vt,Kt).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 w.emitAsync(b.KICK_PEER,{peerId:t})})}kickAll(){return u(this,null,function*(){if(l.info("DyteParticipants::kick_all"),c(this,Ri).getValue("viewType")!=="LIVESTREAM"&&!this.roomJoined)throw new C("Can`t kick all without joining room");if(!c(this,Cn).permissions.kickParticipant)throw l.error("DyteParticipants::unauthorized_kick_all"),new C("Unauthorized: User does not have permission to kick peers.");c(this,Bt).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,Bt).broadcastToPeers(t,n,e)}else c(this,Bt).broadcastMessage(t,e)})}getAllJoinedPeers(t,e,r){return u(this,null,function*(){return(yield c(this,Bt).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,Bt).updatePermissions(n,e)})}getParticipantsInMeetingPreJoin(){return u(this,null,function*(){return c(this,Bt).getRoomPeersNonPaginated()})}},Ri=new WeakMap,Vt=new WeakSet,Kt=function(){return c(this,Ri).getValue("roomNodeClient")},Cn=new WeakMap,Bt=new WeakMap,Pp);Ut([y.trace("DyteParticipants.setViewMode")],kt.prototype,"setViewMode",1);Ut([y.trace("DyteParticipants.setPage")],kt.prototype,"setPage",1);Ut([y.trace("DyteParticipants.disableAllAudio")],kt.prototype,"disableAllAudio",1);Ut([y.trace("DyteParticipants.disableAllVideo")],kt.prototype,"disableAllVideo",1);Ut([y.trace("DyteParticipants.disablePeerAudio")],kt.prototype,"disableAudio",1);Ut([y.trace("DyteParticipants.disablePeerVideo")],kt.prototype,"disableVideo",1);Ut([y.trace("DyteParticipants.kickPeer")],kt.prototype,"kick",1);Ut([y.trace("DyteParticipants.kickAll")],kt.prototype,"kickAll",1);Ut([y.trace("DyteParticipants.broadcastMessage"),It({maxInvocations:500,period:60})],kt.prototype,"broadcastMessage",1);Ut([y.trace("DyteParticipants.getAllJoinedPeers"),It({maxInvocations:10,period:60})],kt.prototype,"getAllJoinedPeers",1);Ut([y.trace("DyteParticipant.updatePermissions"),It({maxInvocations:1e3,period:60})],kt.prototype,"updatePermissions",1);Ut([y.trace("DyteParticipants.getParticipantsInMeetingPreJoin")],kt.prototype,"getParticipantsInMeetingPreJoin",1);kt=Ut([ut("1200")],kt);var YM=Object.defineProperty,QM=Object.getOwnPropertyDescriptor,pi=(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&&YM(e,r,i),i};class gr{constructor(e,r,n,i){m(this,"participants"),m(this,"self"),m(this,"selectedPeers",new ul),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",ur(()=>{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",ur((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 kt(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 Lr(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 w.emit(b.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 Lr(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:Ya(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===bt.AUDIO&&!i.screenShare?n.setAudioEnabled(!i.pause):i.kind===bt.VIDEO&&!i.screenShare&&n.setVideoEnabled(!i.pause),n.producers.push(ne(V({},i),{producingTransportId:i.producingTransportId,kind:i.kind===bt.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)}),w.on(b.SOCKET_SERVICE_ROOM_JOINED,()=>{this.self.permissions.acceptWaitingRequests&&this.roomSocketHandler.getWaitingRoomRequests()}),w.on(b.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}),w.on(b.CONSUMER_PAUSED,({id:e})=>{this.processConsumerPaused(e)}),w.on(b.CONSUMER_RESUMED,({id:e})=>{this.processConsumerResumed(e)}),w.on(b.NEW_CONSUMER,({id:e})=>{this.processNewConsumer(e)}),w.on(b.CONSUMER_CLOSED,({id:e})=>{this.processConsumerClosed(e)}),w.on(b.ROOM_MESSAGE,e=>u(this,[e],function*({payload:r,type:n,timestamp:i}){this.participants.emit("broadcastedMessage",{type:n,payload:r,timestamp:i})})),w.on(b.MESSAGE,e=>u(this,[e],function*({payload:r,type:n,timestamp:i}){n!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:n,payload:r,timestamp:i})})),w.on(b.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}))}),w.on(b.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}))}),w.onAsync(b.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})})),w.on(b.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"&&w.emit(b.UPDATE_STAGE_REQUESTS,{request:{displayName:e.name,userId:e.userId,peerId:e.id},add:!0})),w.emit(b.PEER_JOINED_INTERNAL,e),!(this.self.config.viewType===Je.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"&&w.emit(b.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=>{w.emit(b.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&&w.emit(b.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&&w.emit(b.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&&w.emit(b.E2EE_ACTIVE_CONSUMER,{peerId:r,rtpReceiver:d,track:s})}}static formatSocketServiceMessage(e){var r,n,i,s;if(!e)return;const o=Ya(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()}}pi([y.trace("updateActiveParticipantsMapMinReplacement")],gr.prototype,"updateActiveParticipantsMapMinReplacement",1);pi([y.trace("ParticipantController.setupEvents")],gr.prototype,"setupEventsGlobal",1);pi([y.trace("ParticipantController.processMedia")],gr.prototype,"processMedia",1);pi([y.trace("ParticipantController.processConsumerClosed")],gr.prototype,"processConsumerClosed",1);pi([y.trace("ParticipantController.processConsumerResumed")],gr.prototype,"processConsumerResumed",1);pi([y.trace("ParticipantController.processConsumerPaused")],gr.prototype,"processConsumerPaused",1);pi([y.trace("ParticipantController.processNewConsumer")],gr.prototype,"processNewConsumer",1);var XM=Object.defineProperty,ZM=Object.getOwnPropertyDescriptor,eD=(t,e,r,n)=>{for(var i=n>1?void 0:n?ZM(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&&XM(e,r,i),i};class Fg 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)),w.on(b.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),w.emit(b.REFRESH_GRID,!0)}),w.on(b.MAX_SPATIAL_LAYER_CHANGE,({peerId:e,maxSpatialLayer:r})=>{const n=this.videoPeerConsumerMap.get(e);n&&(this.maxSpatialLayerUpdates.set(n,r),this.updateConsumerSpatialLayers())}),w.on(b.REFRESH_GRID,(e=!1)=>{this.participants.viewMode==="ACTIVE_GRID"&&ur(()=>{this.refreshGridParticipants(e)},500,{maxWait:1e3,leading:!0})()}),w.on(b.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}}})}),w.on(b.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)}),w.on(b.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)})}}eD([y.trace("ParticipantController.setupEvents")],Fg.prototype,"setupEvents",1);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,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&tD(e,r,i),i};class Ug 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)),w.on(b.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),w.emit(b.REFRESH_GRID,!0)}),w.on(b.MAX_SPATIAL_LAYER_CHANGE,({peerId:e,maxSpatialLayer:r})=>{const n=this.videoPeerConsumerMap.get(e);n&&(this.maxSpatialLayerUpdates.set(n,r),this.updateConsumerSpatialLayers())}),w.on(b.REFRESH_GRID,(e=!1)=>{this.participants.viewMode==="ACTIVE_GRID"&&this.refreshGridParticipants(e)}),w.on(b.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}}})}),w.on(b.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)}),w.on(b.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)})}}nD([y.trace("ParticipantController.setupEvents")],Ug.prototype,"setupEvents",1);const _e=hr(Fl().permissions);var G,Ws,Ys,hl,_t,Dt;const $s=class extends xt{constructor(t,e,r,n=!1){if(super(),_(this,_t),_(this,G,void 0),_(this,Ws,void 0),_(this,Ys,void 0),_(this,hl,i=>{const s=i,{chat:o,connectedMeetings:a,plugins:d,polls:h,media:p}=s,f=dc(s,["chat","connectedMeetings","plugins","polls","media"]);let g=!1;o&&(i.chat.private&&zr(c(this,G).chat.private,i.chat.private),i.chat.public&&zr(c(this,G).chat.public,i.chat.public),g=!0,this.emit("chatUpdate")),a&&(g=!0,zr(c(this,G).connectedMeetings,i.connectedMeetings)),p&&(g=!0,zr(c(this,G).media,i.media)),d&&(zr(c(this,G).plugins,i.plugins),g=!0,this.emit("pluginsUpdate")),h&&(zr(c(this,G).polls,i.polls),g=!0,this.emit("pollsUpdate")),Object.keys(f).length!==0&&(zr(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,Ys,t),T(this,Ws,r),T(this,G,e),n&&this.setupEvents()}setupEvents(){w.on(b.UPDATE_PERMISSIONS,c(this,hl))}static fromResponse(t,e,r){return new $s(r,t,e,!0)}static default(t,e){return new $s(t,_e,e)}static init(t,e,r){let n;return r?n=new $s(t,r,e,!0):n=new $s(t,_e,e),n}get mediaRoomType(){const{sfu:t}=c(this,Ys).getValue("roomNodeOptions");return t===ts.CF?"CF":"HIVE"}get stageEnabled(){var t;return((t=c(this,G))==null?void 0:t.stageEnabled)||c(this,Ws)===Je.Webinar||c(this,Ws)===Je.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:_e.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:_e.disableParticipantAudio}get canAllowParticipantScreensharing(){var t,e;return(e=(t=c(this,G))==null?void 0:t.canAcceptProductionRequests)!=null?e:_e.canAcceptProductionRequests}get canAllowParticipantVideo(){var t,e;return(e=(t=c(this,G))==null?void 0:t.disableParticipantVideo)!=null?e:_e.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:_e.kickParticipant}get pinParticipant(){var t,e;return(e=(t=c(this,G))==null?void 0:t.pinParticipant)!=null?e:_e.pinParticipant}get canRecord(){var t,e;return(e=(t=c(this,G))==null?void 0:t.canRecord)!=null?e:_e.canRecord}get waitingRoomType(){var t,e;return(e=(t=c(this,G))==null?void 0:t.waitingRoomType)!=null?e:_e.waitingRoomType}get waitingRoomBehaviour(){var t,e;return(e=(t=c(this,G))==null?void 0:t.waitingRoomType)!=null?e:_e.waitingRoomType}get plugins(){var t,e;return(e=(t=c(this,G))==null?void 0:t.plugins)!=null?e:_e.plugins}get polls(){var t,e;return(e=(t=c(this,G))==null?void 0:t.polls)!=null?e:_e.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:_e.media.video.canProduce;return this.stageEnabled&&(c(this,_t,Dt)==="ACCEPTED_TO_JOIN_STAGE"||c(this,_t,Dt)==="ON_STAGE")&&e===q.CanRequest?q.Allowed:this.stageEnabled&&(c(this,_t,Dt)==="OFF_STAGE"||c(this,_t,Dt)==="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:_e.media.screenshare.canProduce;return this.stageEnabled&&(c(this,_t,Dt)==="ACCEPTED_TO_JOIN_STAGE"||c(this,_t,Dt)==="ON_STAGE")&&e===q.CanRequest?q.Allowed:this.stageEnabled&&(c(this,_t,Dt)==="OFF_STAGE"||c(this,_t,Dt)==="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:_e.media.audio.canProduce;return this.stageEnabled&&(c(this,_t,Dt)==="ACCEPTED_TO_JOIN_STAGE"||c(this,_t,Dt)==="ON_STAGE")&&e===q.CanRequest?q.Allowed:this.stageEnabled&&(c(this,_t,Dt)==="OFF_STAGE"||c(this,_t,Dt)==="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:_e.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:_e.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:_e.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:_e.chat.message}get connectedMeetings(){var t,e;return(e=(t=c(this,G))==null?void 0:t.connectedMeetings)!=null?e:_e==null?void 0:_e.connectedMeetings}get hiddenParticipant(){var t,e;return(e=(t=c(this,G))==null?void 0:t.hiddenParticipant)!=null?e:_e.hiddenParticipant}get showParticipantList(){var t;return(t=c(this,G).showParticipantList)!=null?t:_e.showParticipantList}get canChangeParticipantRole(){var t,e;return(e=(t=c(this,G))==null?void 0:t.canChangeParticipantPermissions)!=null?e:_e.canChangeParticipantPermissions}get canChangeParticipantPermissions(){var t,e;return(e=(t=c(this,G))==null?void 0:t.canChangeParticipantPermissions)!=null?e:_e.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 iD=$s;G=new WeakMap,Ws=new WeakMap,Ys=new WeakMap,hl=new WeakMap,_t=new WeakSet,Dt=function(){return c(this,Ys).getValue("stageStatus")};var Vg;class Bg extends xt{constructor(){super(...arguments),m(this,"localMediaHandler"),_(this,Vg,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"?w.emit(b.MEDIA_PERMISSION_ERROR,f):w.emit(b.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 Rt(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(w.on(b.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)})),w.on(b.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{}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{}finally{this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})})}}Vg=new WeakMap;const Is={},fn={executeWithLock({methodName:t,lockName:e,timeout:r}){return(n,i,s)=>{const o=s.value;return s.value=function(...a){if(Is[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}Is[e]=!0;const d=setTimeout(()=>delete Is[e],r),h=o.apply(this,a);return Promise.resolve(h).then(()=>{delete Is[e],clearTimeout(d)}).catch(()=>{delete Is[e],clearTimeout(d)}),h},s}}};var sD=Object.defineProperty,oD=Object.getOwnPropertyDescriptor,Pt=(t,e,r,n)=>{for(var i=n>1?void 0:n?oD(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&&sD(e,r,i),i},Wo,Sr,Rs,Pi,We,Ye,Ps,bd,Ap,Mp;let at=(Mp=class extends Bg{constructor(t,e,r,n,i){var s;super(),_(this,We),_(this,bd),m(this,"name"),m(this,"picture"),m(this,"customParticipantId"),m(this,"waitlistStatus"),_(this,Wo,void 0),_(this,Sr,void 0),_(this,Rs,void 0),m(this,"role"),m(this,"userId"),m(this,"organizationId"),m(this,"supportsRemoteControl",!1),m(this,"device"),_(this,Pi,void 0),m(this,"presetName"),m(this,"roomState","init"),_(this,Ps,new Set),T(this,Pi,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,Sr,r),T(this,Wo,n),T(this,Rs,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=ye.isElectron(),this.device=ye.getDeviceInfo(),this.presetName=i,n.viewType!==Je.Chat&&this.updatePermission(),this.updateVideo=this.updateVideo.bind(this)}get stageStatus(){return c(this,Pi).getValue("stageStatus")}get id(){return c(this,Pi).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 at(t,e,r,n,i);if(n.viewType===Je.Chat)return E;const v=VA(n.mediaConstraints);return zr(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,bd,Ap)),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",()=>u(this,null,function*(){if(l.info("DyteSelf::setupEvents::AUDIO_TRACK_CHANGE",V({},Xn(this))),this.roomJoined&&this.audioEnabled)try{yield c(this,We,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({},Xn(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,We,Ye).shareWebcam(this.videoTrack);t&&t.id!==this.videoTrack.id&&K.hasFeature(X.EXP_RESHARE)&&(yield c(this,We,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,We,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({},Xn(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({},Xn(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,We,Ye).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),B.videoOff()}))}get permissions(){return c(this,Sr)}get config(){return c(this,Wo)}get roomJoined(){var t;return((t=c(this,We,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,We,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,Sr).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,We,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,We,Ye).unmuteSelf()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),B.audioOn()}})}enableVideo(){return u(this,null,function*(){if(c(this,Sr).canProduceVideo!==q.NotAllowed&&!(c(this,Sr).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,We,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({},Xn(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,Sr).canProduceScreenshare!==q.NotAllowed&&!(c(this,Sr).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,We,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,We,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,We,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,We,Ye).disableScreenShare()),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))})}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){T(this,Rs,t);const r=t?"pinned":"unpinned";e&&this.emit(r,this)}get isPinned(){return c(this,Rs)}pin(){return u(this,null,function*(){if(!this.roomJoined)throw new C("Can`t pin participants without joining room");return c(this,We,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,We,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{this.roomJoined&&(yield c(this,We,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{this.roomJoined&&(yield c(this,We,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,Ps).add(t),this.updateVideo(t)}deregisterVideoElement(t){t.srcObject=void 0,c(this,Ps).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}},Wo=new WeakMap,Sr=new WeakMap,Rs=new WeakMap,Pi=new WeakMap,We=new WeakSet,Ye=function(){return c(this,Pi).getValue("roomNodeClient")},Ps=new WeakMap,bd=new WeakSet,Ap=function(){Array.from(c(this,Ps)).forEach(this.updateVideo)},Mp);Pt([y.trace("DyteSelf.setupEvents")],at.prototype,"setupEvents",1);Pt([y.trace("DyteSelf.setupTracks")],at.prototype,"setupTracks",1);Pt([y.trace("DyteSelf.destructMediaHandler")],at.prototype,"destructMediaHandler",1);Pt([y.trace("DyteSelf.removeDocumentEventListeners")],at.prototype,"removeDocumentEventListeners",1);Pt([fn.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),y.trace("DyteSelf.enableAudio")],at.prototype,"enableAudio",1);Pt([fn.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),y.trace("DyteSelf.enableVideo")],at.prototype,"enableVideo",1);Pt([y.trace("DyteSelf.updateVideoConstraints")],at.prototype,"updateVideoConstraints",1);Pt([y.trace("DyteSelf.enableScreenShare"),fn.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3})],at.prototype,"enableScreenShare",1);Pt([y.trace("DyteSelf.updateScreenshareConstraints")],at.prototype,"updateScreenshareConstraints",1);Pt([fn.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),y.trace("DyteSelf.disableAudio")],at.prototype,"disableAudio",1);Pt([fn.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),y.trace("DyteSelf.disableVideo")],at.prototype,"disableVideo",1);Pt([fn.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3}),y.trace("DyteSelf.disableScreenShare")],at.prototype,"disableScreenShare",1);Pt([y.trace("DyteSelf.setDevice")],at.prototype,"setDevice",1);at=Pt([ut("1100")],at);class aD extends Mg{constructor(e){super(e),m(this,"sessionDescription"),this.sessionDescription=e.sessionDescription}}class cD extends Ng{}class dD extends Og{retryFailedConsumerCreationTasks(e){return u(this,null,function*(){return Xa(e.map(r=>u(this,null,function*(){return pr(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 D=new aD({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,D),D.once("close",()=>{this.consumers.delete(D.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",D),clearTimeout(L),R(D)}}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 ot("closed");if(this.direction!=="recv")throw new ii("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}))}),Xa(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 ii("not a sending Transport");if(e.readyState==="ended")throw new ot("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 cD({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 lD extends Lg{createTransport({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,appData:o,config:a}){const d=si(),h=new dD({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 Et;class uD{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:se.joinRoom,protobuf:Af.toBinary(s),timeout:5e3})).payload})}connectTransport(e){return u(this,null,function*(){const r=(yield c(this,Et).sendMessagePromise(se.createWebRTCTransport,If.toBinary(e))).payload,{transportId:n,description:i}=Vl.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(se.produce,Nf.toBinary(e))).payload,s=Jf.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(se.consume,Of.toBinary(e))).payload,{consumerIdsMap:{map:n},description:i}=Gf.fromBinary(r);return{consumerStateMap:n,sessionDescription:i}})}closeProducer(e){return u(this,null,function*(){const r=(yield c(this,Et).sendMessagePromise(se.closeProducer,xf.toBinary(e))).payload,{description:n}=qf.fromBinary(r);return n})}closeConsumer(e){return u(this,null,function*(){return(yield c(this,Et).sendMessagePromise(se.closeConsumer,Ff.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(se.hostControlPeer,jf.toBinary(n))).payload;if(!i)return!1;const{status:s}=Yf.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(se.hostControlAllPeers,Hf.toBinary(r))).payload;if(!n)return!1;const{status:i}=Qf.fromBinary(n);return i==="success"})}kickAll(){return u(this,null,function*(){const e={},r=(yield c(this,Et).sendMessagePromise(se.kickAll,Vf.toBinary(e))).payload;if(!r)return!1;const{status:n}=zf.fromBinary(r);return n==="success"})}kickPeer(e){return u(this,null,function*(){const r=(yield c(this,Et).sendMessagePromise(se.kickPeer,Uf.toBinary(e))).payload;if(!r)return!1;const{status:n}=Kf.fromBinary(r);return n==="success"})}changeDisplayName(e){return u(this,null,function*(){const r=(yield c(this,Et).sendMessagePromise(se.changeDisplayName,Bf.toBinary(e))).payload;if(!r)return!1;const{status:n}=Xf.fromBinary(r);return n==="success"})}notifySelfJoinComplete(){return u(this,null,function*(){const e={},r=(yield c(this,Et).sendMessagePromise(se.selfJoinComplete,Mf.toBinary(e))).payload;return $a.fromBinary(r)})}}Et=new WeakMap;const hD=2e3;var nn;class pD extends Rg{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,nn,void 0),T(this,nn,e),this._device=new lD({}),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 uD(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 He().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&&Gi.stop(v.id),s){case"send":{const R=Gi.execute(this.createSendTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(o=c(this,nn).getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(h=(d=(a=c(this,nn).getValue("defaults").mediaConfiguration)==null?void 0:a.audio)==null?void 0:d.enableHighBitrate)!=null?h:!1,enableStereo:(g=(f=(p=c(this,nn).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=Gi.execute(this.createRecvTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(E=c(this,nn).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 pr((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 pr((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?Nt.SUBSCRIBER:Nt.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)},hD);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,Za(i),n,e);break}case"handshake":{const a={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,Za(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{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=Tl(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:Nt.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.set(g,{consumerId:E.consumerId,trackId:(v=E.producerTrack)==null?void 0:v.trackId,streamId:E.producerTrack.streamId,kind:E.producerState.kind===bt.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{}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===bt.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)===Dr.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:Dr.INITIALIZING});try{const o=yield this._sendTransport.produce(r);return(i=r.appData)!=null&&i.e2ee&&w.emit(b.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:Nt.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}}),[Y.MIC,Y.WEBCAM].includes(e)||n()}),this._producers.set(e,o),this._producerStatus.set(e,{trackId:r.track.id,status:Dr.INITIALIZED}),this.reconfigureWebcamLayers(),o.track}catch(o){throw this._producerStatus.set(e,{status:Dr.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(Y.WEBCAM);e&&(yield this._switchProducerSpatialLayer(e,this.producers.get(Y.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),w.emit(b.CONSUMER_CLOSED,{id:e.id})})),this._consumers.set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),w.emit(b.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 pr(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&&w.emit(b.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,nn).getValue("modules").e2ee.enabled&&w.emit(b.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,Wa.toBinary(r)),e.pause(),w.emit(b.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,Wa.toBinary(n)),r.resume(),w.emit(b.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:Nt.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,Rf.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(),w.emit(b.CONSUMER_PAUSED,{id:i.id})):(i.resume(),w.emit(b.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{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>20*1e3&&(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),w.emit(b.TRANSPORT_STATE_UPDATE,V({transport:n},this.transportState[n]))}}nn=new WeakMap;var mD=Object.defineProperty,fD=Object.getOwnPropertyDescriptor,le=(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};const Ai={joinAttempted:!1},gD=5e3;var Ie,pe,Tr,Mi,In,Rn,$o,Go,Jo,Gr,As,Pn,kr,Jr,Dp;const jg=(Dp=class extends Ig{constructor(t,e){var r,n;super(),_(this,kr),_(this,Ie,void 0),_(this,pe,void 0),_(this,Tr,void 0),_(this,Mi,void 0),_(this,In,void 0),_(this,Rn,void 0),_(this,$o,void 0),_(this,Go,void 0),_(this,Jo,void 0),_(this,Gr,void 0),_(this,As,void 0),_(this,Pn,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,Tr,!1),T(this,Pn,void 0),T(this,pe,new pD(t,a)),this.maxPreferredStreams=6,this.activatedProducingPeerIds=new Set,T(this,Gr,new Set),T(this,Mi,!1),T(this,In,0),T(this,Rn,new es),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,$o,ur(()=>u(this,null,function*(){if(!Ai.joinAttempted)return;const{roomJoined:h}=yield this.joinRoom(this.peerDisplayName,this.roomUUID,{},!0,!0);h&&(w.emit(b.RESET_PRODUCER_STATE),w.emit(b.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3})),T(this,Go,ur(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports(["send"]),l.info("send transport reconected!"),w.emit(b.RESET_PRODUCER_STATE)}),1e3)),T(this,Jo,ur(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports(["recv"]),l.info("recv transport reconnected!"),this.activatedProducingPeerIds=new Set,w.emit(b.REFRESH_GRID,!0)}),1e3))}get socketState(){return c(this,Ie).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 jg(t,{legacyMode:r,authToken:i,socketClient:o,roomName:n,meetingTitle:s})})}get sfuHandler(){return c(this,pe)}get rejoinRoom(){return c(this,$o)}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,Gr).clear(),this.activatedProducingPeerIds.clear(),t&&(c(this,Rn).stop(),this.sfuHandler.stopAllTransports(),this.sfuHandler.reset(),T(this,Rn,new es))}reconnectTransport(t){return u(this,null,function*(){l.info(`CFNodeClient::Room joining state: ${c(this,Tr)}`),!(!t||c(this,Tr))&&(t.direction==="send"?yield c(this,Go).call(this,t):yield c(this,Jo).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){Ai.joinAttempted=!0,T(this,Tr,!0),this.reset(s);const a=He().ipInfo;if(a!=null&&a.loc&&!c(this,As)){const h=a.loc.split(",");T(this,As,{latitude:parseFloat(h[0]),longitude:parseFloat(h[1])})}let d;try{return d=yield c(this,Rn).push(()=>this._joinRoom(r,n,i,o,c(this,As)),"joinRoom"),d}catch{d={roomJoined:!1}}return d.roomJoined||w.emit(b.ROOM_NODE_FAILED),d})}_partialJoinRoom(t,e,r=!1,n=void 0){return u(this,null,function*(){const i=He().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 pr((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.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,Rn).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,Tr,!1),T(this,Mi,!0),this.roomJoined=!0,w.emit(b.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,Mi,!1),Ai.joinAttempted=!1;const t={closeRoom:!1};c(this,Ie).sendMessagePromise(se.leaveRoom,Df.toBinary(t)).then(e=>{var r;(r=$f.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(Y.WEBCAM)){const i=c(this,pe).producers.get(Y.WEBCAM);if(!i.closed&&!navigator.isReactNative)return yield i.replaceTrack({track:t}),yield this.resumeWebcam(),t;yield c(this,pe).removeProducer(Y.WEBCAM)}const e={track:t,codecOptions:{name:"VP8"},appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1};let r=t.getConstraints().width;r in fp||(r=640),e.encodings=FA[r],K.hasFeature(X.ENABLE_CF_SIMULCAST)&&(e.encodings=fp[r]);const n=()=>{l.info("Disabling video due to the producer closure"),this.disableWebcam()};return c(this,pe).createProducer(Y.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(Y.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(Y.SCREENSHARE_AUDIO,s,i)}B.screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new ot("track undefined");if(c(this,pe).producers.has(Y.MIC)){const n=c(this,pe).producers.get(Y.MIC);if(!n.closed&&!navigator.isReactNative){yield n.replaceTrack({track:t}),yield this.resumeMic();return}yield c(this,pe).removeProducer(Y.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(Y.MIC,e,r)}catch(e){throw new C(e)}})}pauseMic(){const t=c(this,pe).producers.get(Y.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(se.toggleProducer,cn.toBinary(e))}pauseWebcam(){return u(this,null,function*(){const t=c(this,pe).producers.get(Y.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(se.toggleProducer,cn.toBinary(e))})}resumeMic(){return u(this,null,function*(){const t=c(this,pe).producers.get(Y.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&&w.emit(b.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,Ie).sendMessage(se.toggleProducer,cn.toBinary(e))})}resumeWebcam(){return u(this,null,function*(){const t=c(this,pe).producers.get(Y.WEBCAM);if(!t){l.error("resumeWebcam::could_not_find_webcam_producer");return}t.resume(),t.appData.e2ee&&w.emit(b.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,Ie).sendMessage(se.toggleProducer,cn.toBinary(e))})}disableWebcam(){return u(this,null,function*(){yield c(this,pe).removeProducer(Y.WEBCAM)})}disableMic(){return u(this,null,function*(){yield c(this,pe).removeProducer(Y.MIC)})}disableScreenShare(){return u(this,null,function*(){l.info("screen_sharing_stopped"),B.screenShareStop(),yield c(this,pe).removeProducer(Y.SCREENSHARE_VIDEO),yield c(this,pe).removeProducer(Y.SCREENSHARE_AUDIO),c(this,Gr).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(Y.WEBCAM,!1),this.shareWebcam(t)),e&&(yield c(this,pe).removeProducer(Y.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,Ie).sendMessagePromise(se.globalPinPeer,Lf.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,Gr).add(t.consumerPeerId),c(this,Gr).size}switchConsumersToLayer(t,e){return u(this,null,function*(){this.sfuHandler.switchConsumersToLayer(t,e)})}handleSocketEvents(){return u(this,null,function*(){c(this,Ie).on(se.peerProducerCreateBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:r}=Zf.fromBinary(t);if(e===this.peerId)return;l.info(`producer created broadcast: ${e}, producer state: ${r}`),w.emit(b.NEW_PRODUCER,{peerId:e,producer:ne(V({},r),{kind:r.kind===bt.AUDIO?"audio":"video"})})}catch(e){l.error("error in peer-producer-create-broadcast",{error:e})}}),c(this,Ie).on(se.peerProducerToggleBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:{kind:r,pause:n,producerId:i}}=eg.fromBinary(t),s=r===bt.AUDIO?"audio":"video";l.info(`producer toggle broadcast: ${e}, producerId: ${i}, kind:${s}, paused:${n}`),w.emit(b.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(),w.emit(b.CONSUMER_PAUSED,{id:o.id})):(o.resume(),w.emit(b.CONSUMER_RESUMED,{id:o.id})))})}catch(e){l.error("error in producer toggle broadcast handler",{error:e})}}),c(this,Ie).on(se.peerLeaveBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e}=Ga.fromBinary(t);if(e===this.peerId)return;l.info(`peer left broadcast:${e}`),c(this,Gr).delete(e),this.sfuHandler.cleanupConsumers(e)}catch(e){l.error("error in peer left broadcast",{error:e})}}),c(this,Ie).on(se.peerProducerCloseBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:{producerId:r}}=tg.fromBinary(t);if(e===this.peerId)return;l.info(`producer closed broadcast:${e}`),w.emit(b.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),w.emit(b.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(se.mediaRoomTerminationBroadcastResponse,()=>{!this.roomJoined&&!c(this,Tr)&&!c(this,Mi)||(l.warn("media hub termination broadcast received, rejoining room"),w.emit(b.ROOM_NODE_DISCONNECTED),this.rejoinRoom())})})}handleSocketConnectionEvents(){c(this,Ie).onStateEvent("connected",()=>u(this,null,function*(){l.info("SocketService::Connected to socket-edge"),clearTimeout(c(this,Pn)),T(this,Pn,void 0),ue(this,kr,Jr).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?w.emit(b.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:Ai.joinAttempted}):T(this,Pn,setTimeout(()=>{w.emit(b.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:Ai.joinAttempted}),T(this,Pn,void 0)},gD)),ue(this,kr,Jr).call(this,"disconnected"),this.roomJoined=!1}),c(this,Ie).onStateEvent("reconnecting",()=>u(this,null,function*(){l.info("SocketService::Reconnecting to socket-edge"),ue(this,kr,Jr).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,kr,Jr).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,kr,Jr).call(this,"reconnectFailure",t)}),c(this,Ie).onStateEvent("reconnected",()=>u(this,null,function*(){l.info("SocketService::Reconnected to socket-edge",{connectionState:Ai}),w.emit(b.SOCKET_SERVICE_RECONNECTED),ue(this,kr,Jr).call(this,"reconnected")})),c(this,Ie).onStateEvent("failed",()=>u(this,null,function*(){l.info("SocketService::Failed to connect to socket-edge"),ue(this,kr,Jr).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,In)>3&&!t){l.warn("cannot rejoin more already rejoined 3 times");return}if(c(this,Tr)&&!t){l.warn("room joining in progress, cannot start rejoining");return}T(this,In,c(this,In)+1),l.warn(`rejoining the room because transports are failing. [rejoinCount: ${c(this,In)}]`),this.roomJoined=!1,w.emit(b.ROOM_NODE_DISCONNECTED),this.rejoinRoom()})}handleCallstatsEvents(){B.onSafeInitialization(()=>{B.onConsumerScore(t=>{t.forEach((e,r)=>{const n=this.sfuHandler.consumers.get(r);n&&w.emit(b.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&&w.emit(b.PRODUCER_SCORE_UPDATE,{id:r,kind:n.kind,appData:n.appData,score:+(e*10).toFixed()})})})})}},Ie=new WeakMap,pe=new WeakMap,Tr=new WeakMap,Mi=new WeakMap,In=new WeakMap,Rn=new WeakMap,$o=new WeakMap,Go=new WeakMap,Jo=new WeakMap,Gr=new WeakMap,As=new WeakMap,Pn=new WeakMap,kr=new WeakSet,Jr=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&&(c(this,Ie).connectionState=r,w.emit(b.SOCKET_STATE_UPDATE,r))},Dp);let ce=jg;le([y.trace("CFNodeClient.reset")],ce.prototype,"reset",1);le([y.trace("CFNodeClient.reconnect")],ce.prototype,"reconnectTransport",1);le([y.trace("CFNodeClient.setupTransport")],ce.prototype,"setupTransports",1);le([y.trace("CFNodeClient.stopAllProducers")],ce.prototype,"stopAllProducers",1);le([y.trace("CFNodeClient.joinRoom")],ce.prototype,"joinRoom",1);le([y.trace("CFNodeClient.completeJoinRoom")],ce.prototype,"completeJoinRoom",1);le([y.trace("CFNodeClient.leaveRoom")],ce.prototype,"leaveRoom",1);le([y.trace("CFNodeClient.activatePeers")],ce.prototype,"activatePeers",1);le([y.trace("CFNodeClient.deactivatePeers")],ce.prototype,"deactivatePeers",1);le([y.trace("CFNodeClient.createConsumer")],ce.prototype,"createConsumer",1);le([y.trace("CFNodeClient.pauseConsumers")],ce.prototype,"pauseConsumers",1);le([y.trace("CFNodeClient.resumeConsumers")],ce.prototype,"resumeConsumers",1);le([y.trace("CFNodeClient.closeConsumers")],ce.prototype,"closeConsumers",1);le([y.trace("CFNodeClient.consumePeer")],ce.prototype,"consumePeer",1);le([y.trace("CFNodeClient.shareWebcam")],ce.prototype,"shareWebcam",1);le([y.trace("CFNodeClient.shareScreen")],ce.prototype,"shareScreen",1);le([y.trace("CFNodeClient.shareMic")],ce.prototype,"shareMic",1);le([y.trace("CFNodeClient.pauseMic")],ce.prototype,"pauseMic",1);le([y.trace("CFNodeClient.pauseWebcam")],ce.prototype,"pauseWebcam",1);le([y.trace("CFNodeClient.resumeMic")],ce.prototype,"resumeMic",1);le([y.trace("CFNodeClient.resumeWebcam")],ce.prototype,"resumeWebcam",1);le([y.trace("CFNodeClient.disableWebcam")],ce.prototype,"disableWebcam",1);le([y.trace("CFClient.disableMic")],ce.prototype,"disableMic",1);le([y.trace("CFClient.disableScreenShare")],ce.prototype,"disableScreenShare",1);le([y.trace("CFNodeClient.muteSelf")],ce.prototype,"muteSelf",1);le([y.trace("CFNodeClient.resetVideoProducers")],ce.prototype,"resetVideoProducers",1);le([y.trace("CFNodeClient.changeDisplayName")],ce.prototype,"changeDisplayName",1);le([y.trace("CFNodeClient.kickPeer")],ce.prototype,"kick",1);le([y.trace("CFNodeClient.kickAllPeers")],ce.prototype,"kickAll",1);le([y.trace("CFNodeClient.muteAll")],ce.prototype,"muteAll",1);le([y.trace("CFNodeClient.muteAllVideo")],ce.prototype,"muteAllVideo",1);le([y.trace("CFNodeClient.disableAudio")],ce.prototype,"disableAudio",1);le([y.trace("CFNodeClient.disableVideo")],ce.prototype,"disableVideo",1);le([y.trace("CFNodeClient.pinPeer")],ce.prototype,"pinPeer",1);le([y.trace("CFNodeClient.validateScreenShare")],ce.prototype,"validateScreenShare",1);le([y.trace("CFNodeClient.init")],ce,"init",1);function vD(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 yD(t,e){return u(this,null,function*(){const r=t.getValue("roomNodeClient");if(r){if(r instanceof ce)return r;throw new Error("Room Node Client already setup")}const n=yield ce.init(t,e);return t.setValue("roomNodeClient",n),n})}function Hg(t,e){return u(this,arguments,function*(r,n,i=ts.HIVE){return i===ts.CF?yD(r,n):vD(r,n)})}function Wg(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch{l.error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var ED=Object.defineProperty,SD=Object.getOwnPropertyDescriptor,TD=(t,e,r,n)=>{for(var i=n>1?void 0:n?SD(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};let Di;const $g=class{constructor(t){m(this,"socket"),this.socket=t,this.handleSocketEvents()}static create(t){return Di||(Di=new $g(t)),Di}static cleanup(){var t;try{(t=Di==null?void 0:Di.socket)==null||t.disconnect()}catch{l.error("roomSocketHandler::cleanup")}Di=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,Y0.toBinary(i));try{const{peer:o}=Oi.fromBinary((yield s).payload);w.emit(b.SOCKET_SERVICE_ROOM_JOINED,{peer:o});const a=this.getRoomState();let d=()=>new Promise(f=>{f({peers:[]})});n!==Je.Livestream&&(d=this.getRoomPeersNonPaginated()),n===Je.Livestream&&o.stageType===1&&(d=this.getStagePeers());const[{room:h},{peers:p}]=yield Promise.all([a,d]);return w.emit(b.ROOM_STATE,h),w.emit(b.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 NC.fromBinary((yield this.socket.sendMessagePromise(j.getAllAddedParticipants)).payload).participants.map(t=>{var e=t,{id:r}=e,n=dc(e,["id"]);return ne(V({},n),{userId:r})})}catch{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,B0.toBinary(i));n=od.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=od.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=od.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,ng.toBinary({peerId:t}));e=Oi.fromBinary(r.payload)}catch(r){l.error("getPeerInfo::binary_decode_error",{error:r})}return e})}getRoomState(){return u(this,null,function*(){let t=Uh.create();try{const e=yield this.socket.sendMessagePromise(j.getRoomInfo);t=Uh.fromBinary(e.payload)}catch(e){l.error("getRoomState::binary_decode_error",{error:e})}return t})}getRoomStageState(){return u(this,null,function*(){let t=Hh.create();try{const e=yield this.socket.sendMessagePromise(j.getRoomStageState);t=Hh.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,To.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,To.toBinary(n))})}leaveRoom(){return u(this,null,function*(){this.socket.sendMessagePromise(j.leaveRoom,X0.toBinary({}))})}kick(t){return u(this,null,function*(){const e={peerIds:[t]};this.socket.sendMessage(j.kick,UC.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,jC.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(j.denyWaitingRoomRequests,WC.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(ia.updateUserPreset,yI.toBinary(r))})}handleSocketEvents(){this.socket.on(j.broadcastMessage,({payload:t})=>{try{const e=To.fromBinary(t);w.emit(b.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=To.fromBinary(t);w.emit(b.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=Oi.fromBinary.bind(Oi),n=Oi.create();break}case j.getWaitingRoomRequests:{r=(i,s)=>i?jh.fromBinary(i,s):{requests:[]},n=jh.create();break}case j.recordingPaused:case j.recordingStarted:case j.recordingStopped:{r=Qh.fromBinary.bind(Qh);break}case ia.updateUserPreset:{r=Wh.fromBinary.bind(Wh);break}case se.peerJoinedBroadcast:case ie.peerJoinedBroadcast:{r=Nh.fromBinary.bind(Nh);break}case se.selfJoinComplete:case ie.selfJoinComplete:{r=$a.fromBinary.bind($a);break}case se.globalPeerPinBroadcast:case ie.globalPeerPinBroadcast:{r=Lh.fromBinary.bind(Lh);break}case se.selectedPeer:case ie.selectedPeer:{r=Gd.fromBinary.bind(Gd);break}case se.selectedPeerDiff:case ie.selectedPeerDiff:{r=Oh.fromBinary.bind(Oh);break}case se.leaveRoom:case ie.leaveRoom:{r=Ga.fromBinary.bind(Ga);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(ia.getUserPresets,uI.toBinary(e)),n=fI.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 tc=$g;TD([y.trace("RoomSocketHandler.joinRoom")],tc.prototype,"joinRoom",1);var kD=Object.defineProperty,_D=Object.getOwnPropertyDescriptor,as=(t,e,r,n)=>{for(var i=n>1?void 0:n?_D(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&&kD(e,r,i),i},An,zt,mt,Mt,jt,Op;const Gg=(Op=class{constructor(t,e,r,n){_(this,Mt),m(this,"self"),m(this,"authToken"),_(this,An,void 0),m(this,"viewType"),_(this,zt,void 0),_(this,mt,void 0);const{socket:i}=r,s=t.getValue("authToken");this.self=e,T(this,mt,t),this.viewType=n,this.authToken=s,T(this,An,i),T(this,zt,r),e.config.viewType!==Je.Chat&&this.setupEvents()}get peerId(){return c(this,mt).getValue("peerId")}static init(t,e,r,n,i){return u(this,null,function*(){const s=He(),o=t.getValue("peerId"),a=!!t.getValue("cachedUserDetails"),d=yield at.__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:wf(t),skipConnectivityChecks:h})}))}return new Gg(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,Mt,jt).shareMic(e)}catch{this.self.disableAudio()}if(n.canProduceVideo&&s)try{const d=yield c(this,Mt,jt).shareWebcam(r);d&&d.id!==r.id&&K.hasFeature(X.EXP_RESHARE)&&(yield c(this,Mt,jt).shareWebcam(d))}catch{this.self.disableVideo()}if(n.canProduceScreenshare&&o)try{yield(t=c(this,Mt,jt))==null?void 0:t.shareScreen({video:a.video,audio:a.audio})}catch{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,Mt,jt).reset();return}yield this.joinRoom(t)})}setupEvents(){w.on(b.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.self.roomJoined&&this.shareMediaTracks()})),w.on(b.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),w.on(b.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),w.on(b.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),w.on(b.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{this.self.roomState="init",this.resetSelf(t)}),w.on(b.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=si()),c(this,An).updateURL(e),y.resetPeerId(e),He().setHeader("dyte-tracing-id",e),zs.remapContext(e,c(this,mt)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),w.on(b.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),c(this,zt).on(j.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),c(this,zt).on(ia.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&w.emit(b.UPDATE_PERMISSIONS,e.patch)})}),c(this,zt).on(j.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),c(this,zt).on(j.kick,()=>{this.kickHandler({kickType:"kick"})}),c(this,zt).on(j.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),w.onAsync(b.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),w.on(b.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})}),w.on(b.MUTE_ALL,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),B.audioOff())})),w.on(b.MUTE_ALL_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),B.videoOff())})),w.onAsync(b.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),w.on(b.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return u(this,null,function*(){try{const{peer:e}=yield c(this,zt).joinRoom(this.self.name,this.self.id,this.self.userId,this.self.config.viewType);c(this,zt).socket.flush();const r=Ya(e.stageType);if(c(this,mt).setValue("stageStatus",r,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),c(this,mt).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,An))==null||e.disconnect()}catch{l.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),yield c(this,zt).leaveRoom(),c(this,mt).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),c(this,mt).notify("stageStatus");try{(r=c(this,An))==null||r.disconnect()}catch{l.error("SelfController::leaveRoom::socketDisconnect")}Wg(c(this,mt)),tc.cleanup(),this.self.roomState=t,this.self.emit("roomLeft",{state:t})})}partialMediaRoom(){var t;(t=c(this,Mt,jt))==null||t.partialJoinRoom(this.self.name,c(this,mt).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,mt).getAllValues(),{sfu:h,roomNodeUrl:p,meetingTitle:f}=d;try{if(i===Je.Livestream){if(a!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}yield Hg(c(this,mt),{socket:c(this,An),peerId:n,meetingId:s,authToken:o,roomNodeUrl:p,meetingTitle:f},h)}const{roomJoined:g}=(r=yield(e=c(this,Mt,jt))==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,mt).getValue("viewType");yield this.cleanupSelf(),!(t==="stageLeft"&&e===Je.Webinar)&&c(this,Mt,jt)&&(c(this,Mt,jt).roomJoined&&t!=="disconnected"&&(yield c(this,Mt,jt).leaveRoom()),!(t==="stageLeft"&&e===Je.Livestream)&&(this.self.roomState="init",c(this,Mt,jt).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()})}},An=new WeakMap,zt=new WeakMap,mt=new WeakMap,Mt=new WeakSet,jt=function(){return c(this,mt).getValue("roomNodeClient")},Op);let mi=Gg;as([y.trace("SelfController.resetSelf")],mi.prototype,"resetSelf",1);as([y.trace("SelfController.setupEvents")],mi.prototype,"setupEvents",1);as([y.trace("SelfController.joinRoom")],mi.prototype,"joinRoom",1);as([y.trace("SelfController.leaveRoom")],mi.prototype,"leaveRoom",1);as([y.trace("SelfController.joinMediaRoom")],mi.prototype,"joinMediaRoom",1);as([y.trace("SelfController.leaveMediaRoom")],mi.prototype,"leaveMediaRoom",1);var _a;class bD{constructor(e){_(this,_a,void 0),T(this,_a,e)}on(e,r){let n;e===j.roomPeerCount?n=Fh.fromBinary.bind(Fh):n=Kh.fromBinary.bind(Kh),c(this,_a).on(e,({payload:i})=>{const s=n(i);return r(s)})}}_a=new WeakMap;var ba;class wD{constructor(e){_(this,ba,void 0),T(this,ba,e)}on(e,r){let n,i;switch(e){case j.transcript:{n=sd.fromBinary.bind(sd),i=sd.create();break}default:{l.debug("AISocketHandler switch case hit default, event not accounted for.");break}}c(this,ba).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)})}}ba=new WeakMap;var CD=Object.defineProperty,ID=Object.getOwnPropertyDescriptor,tu=(t,e,r,n)=>{for(var i=n>1?void 0:n?ID(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&&CD(e,r,i),i},$n;class Dc{constructor(e){_(this,$n,void 0),T(this,$n,e)}getPolls(){return c(this,$n).sendMessagePromise(Cr.getPolls)}createPoll(e,r,n=!1,i=!1){const s={anonymous:n,hideVotes:i,question:e,options:r};return c(this,$n).sendMessage(Cr.createPoll,lP.toBinary(s))}votePoll(e,r){const n={index:r,pollId:e};return c(this,$n).sendMessage(Cr.votePoll,hP.toBinary(n))}on(e,r){let n,i;switch(e){case Cr.updatePoll:case Cr.createPoll:case Cr.votePoll:{n=ud.fromBinary.bind(ud),i=ud.create();break}}c(this,$n).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)})}}$n=new WeakMap;tu([y.trace("PollSocketHandler.getPolls")],Dc.prototype,"getPolls",1);tu([y.trace("PollSocketHandler.createPoll")],Dc.prototype,"createPoll",1);tu([y.trace("PollSocketHandler.votePoll")],Dc.prototype,"votePoll",1);var Ot;class RD{constructor(e){_(this,Ot,void 0),T(this,Ot,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield c(this,Ot).sendMessagePromise(j.getStageRequests);return e?ld.fromBinary(e):{stageRequests:[]}})}requestAccess(){c(this,Ot).sendMessage(j.requestStageAccess)}cancelRequestAccess(){c(this,Ot).sendMessage(j.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const r={userIds:e};c(this,Ot).sendMessage(j.grantStageAccess,eP.toBinary(r))})}denyAccess(e){return u(this,null,function*(){const r={userIds:e};c(this,Ot).sendMessage(j.denyStageAccess,rP.toBinary(r))})}joinStage(){return c(this,Ot).sendMessagePromise(j.joinStage,void 0,void 0,j.peerStageStatusUpdate)}leaveStage(e){const r={userIds:[e]};return c(this,Ot).sendMessagePromise(j.leaveStage,Yh.toBinary(r),void 0,j.peerStageStatusUpdate)}kick(e){const r={userIds:e};return c(this,Ot).sendMessagePromise(j.leaveStage,Yh.toBinary(r))}on(e,r){let n;switch(e){case j.grantStageAccess:case j.denyStageAccess:{n=void 0;break}case j.getStagePeers:{n=zh.fromBinary.bind(zh);break}case j.getStageRequests:case j.requestStageAccess:case j.cancelStageRequest:{n=ld.fromBinary.bind(ld);break}case j.peerStageStatusUpdate:{n=xh.fromBinary.bind(xh);break}}c(this,Ot).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,Ot).sendMessagePromise(j.getPeerInfo,ng.toBinary({peerId:e}));return Oi.fromBinary(r.payload)})}}Ot=new WeakMap;var et;class PD{constructor(e){_(this,et,void 0),T(this,et,e)}addPlugin(e,r){c(this,et).sendMessage(J.addPlugin,vR.toBinary({pluginId:e,staggered:r}))}removePlugin(e){c(this,et).sendMessage(J.removePlugin,ER.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield c(this,et).sendMessagePromise(J.getPlugins);return e?HR.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,r,n){const i={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};c(this,et).sendMessage(J.customPluginEventToRoom,PR.toBinary(i),n)}customPluginEventToPeers(e,r,n,i){const s={pluginId:e,peerIds:r,pluginData:new TextEncoder().encode(JSON.stringify(n))};c(this,et).sendMessage(J.customPluginEventToPeers,MR.toBinary(s),i)}enablePluginForRoom(e,r){c(this,et).sendMessage(J.enablePluginForRoom,TR.toBinary({pluginId:e}),r)}enablePluginForPeers(e,r,n){c(this,et).sendMessage(J.enablePluginForPeers,wR.toBinary({pluginId:e,peerIds:r}),n)}disablePluginForRoom(e,r){c(this,et).sendMessage(J.disablePluginForRoom,_R.toBinary({pluginId:e}),r)}disablePluginForPeers(e,r,n){c(this,et).sendMessage(J.disablePluginForPeers,IR.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,et).sendMessage(J.storeInsertKeys,$h.toBinary(s),i)}storeGetKeys(e,r,n,i){const s={pluginId:e,storeName:r,getKeys:n.map(o=>({storeKey:o.key}))};c(this,et).sendMessage(J.storeGetKeys,LR.toBinary(s),i)}storeDeleteKeys(e,r,n,i){const s={pluginId:e,storeName:r,deleteKeys:n.map(o=>({storeKey:o.key}))};c(this,et).sendMessage(J.storeDeleteKeys,FR.toBinary(s),i)}storeDelete(e,r,n){c(this,et).sendMessage(J.storeDelete,VR.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,et).sendMessage(J.storeInsertKeys,$h.toBinary(i))}on(e,r){let n;switch(e){case J.addPlugin:case J.enablePluginForPeers:case J.enablePluginForRoom:{n=Kd.fromBinary.bind(Kd);break}case J.removePlugin:case J.disablePluginForPeers:case J.disablePluginForRoom:{n=Gh.fromBinary.bind(Gh);break}case J.customPluginEventToPeers:case J.customPluginEventToRoom:{n=qh.fromBinary.bind(qh);break}case J.storeInsertKeys:case J.storeGetKeys:case J.storeDeleteKeys:case J.storeDelete:{n=Jh.fromBinary.bind(Jh);break}}c(this,et).on(e,({payload:i,id:s})=>{const o=n(i);return r(o,s)})}}et=new WeakMap;var AD=Object.defineProperty,MD=(t,e,r)=>e in t?AD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,DD=(t,e,r)=>(MD(t,typeof e!="symbol"?e+"":e,r),r),ru=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},N=(t,e,r)=>(ru(t,e,"read from private field"),r?r.call(t):e.get(t)),Re=(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)=>(ru(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),Me=(t,e,r)=>(ru(t,e,"access private method"),r),sn,Gn,Jn,Ue,qn,Ae,je,on,tt,Ar,dn,Zt,Ji,Ir,pl,Jg,Gs,wa,ml,qg,nu,Kg,rc,iu,fl,zg,ro,nc,Qs,ic,sc,su,qi,no,Xs,oc,ou={exports:{}},Ki=typeof Reflect=="object"?Reflect:null,Np=Ki&&typeof Ki.apply=="function"?Ki.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},Ca;Ki&&typeof Ki.ownKeys=="function"?Ca=Ki.ownKeys:Object.getOwnPropertySymbols?Ca=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Ca=function(t){return Object.getOwnPropertyNames(t)};function OD(t){console&&console.warn&&console.warn(t)}var Yg=Number.isNaN||function(t){return t!==t};function Se(){Se.init.call(this)}ou.exports=Se;ou.exports.once=FD;Se.EventEmitter=Se;Se.prototype._events=void 0;Se.prototype._eventsCount=0;Se.prototype._maxListeners=void 0;var Lp=10;function Oc(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(Se,"defaultMaxListeners",{enumerable:!0,get:function(){return Lp},set:function(t){if(typeof t!="number"||t<0||Yg(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Lp=t}});Se.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};Se.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Yg(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 Qg(t){return t._maxListeners===void 0?Se.defaultMaxListeners:t._maxListeners}Se.prototype.getMaxListeners=function(){return Qg(this)};Se.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")Np(a,this,e);else for(var d=a.length,h=rv(a,d),r=0;r<d;++r)Np(h[r],this,e);return!0};function Xg(t,e,r,n){var i,s,o;if(Oc(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=Qg(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,OD(a)}return t}Se.prototype.addListener=function(t,e){return Xg(this,t,e,!1)};Se.prototype.on=Se.prototype.addListener;Se.prototype.prependListener=function(t,e){return Xg(this,t,e,!0)};function ND(){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 Zg(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=ND.bind(n);return i.listener=r,n.wrapFn=i,i}Se.prototype.once=function(t,e){return Oc(e),this.on(t,Zg(this,t,e)),this};Se.prototype.prependOnceListener=function(t,e){return Oc(e),this.prependListener(t,Zg(this,t,e)),this};Se.prototype.removeListener=function(t,e){var r,n,i,s,o;if(Oc(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():LD(r,i),r.length===1&&(n[t]=r[0]),n.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this};Se.prototype.off=Se.prototype.removeListener;Se.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 ev(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?xD(i):rv(i,i.length)}Se.prototype.listeners=function(t){return ev(this,t,!0)};Se.prototype.rawListeners=function(t){return ev(this,t,!1)};Se.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):tv.call(t,e)};Se.prototype.listenerCount=tv;function tv(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}Se.prototype.eventNames=function(){return this._eventsCount>0?Ca(this._events):[]};function rv(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function LD(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function xD(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function FD(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))}nv(t,e,s,{once:!0}),e!=="error"&&UD(t,i,{once:!0})})}function UD(t,e,r){typeof t.on=="function"&&nv(t,"error",e,r)}function nv(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 VD=ou.exports;class BD 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 xp=new BD;class iv{static encode(e){return xp.toBinary(e)}static decode(e){return xp.fromBinary(new Uint8Array(e))}}function jD(t,e){return Math.floor(Math.random()*(e-t+1)+t)}class HD{constructor(e={}){DD(this,"opts"),Re(this,sn,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},ge(this,sn,0)}wait(){return u(this,null,function*(){ge(this,sn,N(this,sn)+1);const e=jD(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*my(2,N(this,sn))));yield new Promise(r=>{setTimeout(r,e)})})}getAttempts(){return N(this,sn)}reset(){ge(this,sn,0)}}sn=new WeakMap;const qr={debug:0,info:1,warn:2,error:3};class WD{constructor(e){Re(this,Gn,void 0),Re(this,Jn,void 0),ge(this,Gn,console),ge(this,Jn,e)}debug(...e){qr[N(this,Jn)]>qr.debug||N(this,Gn).debug("[Sockrates]:",...e)}info(...e){qr[N(this,Jn)]>qr.info||N(this,Gn).info("[Sockrates]:",...e)}warn(...e){qr[N(this,Jn)]>qr.warn||N(this,Gn).warn("[Sockrates]:",...e)}error(...e){qr[N(this,Jn)]>qr.error||N(this,Gn).error("[Sockrates]:",...e)}}Gn=new WeakMap;Jn=new WeakMap;var sv=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(sv||{});const $D="2",GD="3";class JD{constructor(e,r){Re(this,pl),Re(this,Gs),Re(this,ml),Re(this,nu),Re(this,rc),Re(this,fl),Re(this,ro),Re(this,Qs),Re(this,sc),Re(this,qi),Re(this,Xs),Re(this,Ue,void 0),Re(this,qn,void 0),Re(this,Ae,void 0),Re(this,je,void 0),Re(this,on,void 0),Re(this,tt,void 0),Re(this,Ar,void 0),Re(this,dn,void 0),Re(this,Zt,void 0),Re(this,Ji,void 0),Re(this,Ir,void 0);var n,i,s,o,a,d,h,p,f,g;ge(this,qn,e),ge(this,on,[]),ge(this,tt,new VD),ge(this,Ar,!0),ge(this,Zt,!1),ge(this,Ae,r!=null?r:{}),(n=N(this,Ae)).autoReconnect!=null||(n.autoReconnect=!0),(i=N(this,Ae)).retryConnectionInterval!=null||(i.retryConnectionInterval=1e3),(s=N(this,Ae)).pingTimeout!=null||(s.pingTimeout=3e4),(o=N(this,Ae)).connectionTimeout!=null||(o.connectionTimeout=5e3),(a=N(this,Ae)).debug!=null||(a.debug=!0),(d=N(this,Ae)).maxReconnectionAttempts!=null||(d.maxReconnectionAttempts=10),(h=N(this,Ae)).disconnectOnPingTimeout!=null||(h.disconnectOnPingTimeout=!0),(p=N(this,Ae)).queueOnDisconnect!=null||(p.queueOnDisconnect=!1),(f=N(this,Ae)).flushOnReconnect!=null||(f.flushOnReconnect=!1),ge(this,dn,{code:void 0,reason:void 0}),ge(this,je,(g=N(this,Ae).logger)!=null?g:new WD(N(this,Ae).debug?"debug":"info")),ge(this,Ir,new HD)}get readyState(){var e;return(e=N(this,Ue))==null?void 0:e.readyState}get url(){return N(this,qn)}updateURL(e){ge(this,qn,e),Me(this,fl,zg).call(this)}get config(){return N(this,Ae)}get sendQueue(){return N(this,on)}flush(){if(!N(this,Ae).queueOnDisconnect)return!1;const e=[];return N(this,on).forEach(r=>{this.send(r.event,r.id,r.payload,r.metadata)||e.push(r)}),ge(this,on,e),N(this,on)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){N(this,je).debug("Websocket was already connecting or connected.");return}if(N(this,Ar)!==!1)return new Promise((r,n)=>{Me(this,qi,no).call(this),Me(this,Xs,oc).call(this);try{ge(this,Ue,new WebSocket(Me(this,pl,Jg).call(this,N(this,qn)))),N(this,Ue).binaryType="arraybuffer",N(this,je).debug("Connecting to",N(this,qn));const i=setTimeout(()=>{N(this,je).debug("Connection timeout. Closing socket"),ge(this,Ar,!0),Me(this,Xs,oc).call(this),N(this,Ue).close(3001,"Connection Timeout"),N(this,Ae).autoReconnect&&!N(this,Zt)&&(N(this,tt).emit("reconnecting"),Me(this,ro,nc).call(this)),n(new Error("Connection timed out!"))},N(this,Ae).connectionTimeout);N(this,Ue).onopen=()=>{N(this,je).debug(`Ready State: ${sv[N(this,Ue).readyState]}`),i&&clearTimeout(i),Me(this,sc,su).call(this),ge(this,dn,{code:void 0,reason:void 0}),N(this,tt).emit("connected"),N(this,Ae).flushOnReconnect&&this.flush(),r()},N(this,Ue).onclose=s=>{try{i&&clearTimeout(i);const{code:o,reason:a}=s;n(a),N(this,je).debug("Socket closed. Close event:",s),N(this,je).debug("Connection closed code:",o),N(this,je).debug("Connection closed reason:",a),N(this,Zt)||Me(this,rc,iu).call(this,o,a)}catch(o){Me(this,Gs,wa).call(this,o)}},N(this,Ue).onerror=s=>{Me(this,Gs,wa).call(this,s)},N(this,Ue).onmessage=s=>Me(this,ml,qg).call(this,s)}catch(i){Me(this,Gs,wa).call(this,i,n)}})})}send(e,r,n,i){const s={event:e,id:r,payload:n,metadata:i};if(N(this,Ae).queueOnDisconnect&&(!N(this,Ue)||N(this,Ue).readyState!==1))return N(this,je).debug("Queuing message since socket is not connected!",s),N(this,on).push(s),!1;const o=iv.encode(s);return Me(this,Qs,ic).call(this,o)}emit(e,r,n,i){return this.send(e,r,n,i)}sendRaw(e){return Me(this,Qs,ic).call(this,e)}receive(e,r){return N(this,tt).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")){N(this,tt).on(e,r);return}this.receive(e,r)}removeAllListeners(){N(this,tt).removeAllListeners()}removeReceiver(e,r){this.removeListener(e,r)}removeListener(e,r){N(this,tt).removeListener(e.toString(),r)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){N(this,tt).listeners(e.toString()).map(r=>this.removeListener(e,r))}disconnect(){ge(this,Ar,!1),Me(this,qi,no).call(this),this.removeAllListeners(),ge(this,dn,{code:1e3,reason:"Sockrates disconnect method called"}),N(this,Ue).close(1e3,"Sockrates disconnect method called.")}}Ue=new WeakMap;qn=new WeakMap;Ae=new WeakMap;je=new WeakMap;on=new WeakMap;tt=new WeakMap;Ar=new WeakMap;dn=new WeakMap;Zt=new WeakMap;Ji=new WeakMap;Ir=new WeakMap;pl=new WeakSet;Jg=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)://.")};Gs=new WeakSet;wa=function(t,e){N(this,je).error("Error:",{error:t}),N(this,tt).emit("errored",{error:t}),e==null||e(t)};ml=new WeakSet;qg=function(t){if(Me(this,sc,su).call(this),t.data===$D){N(this,je).debug("Received ping from server"),Me(this,Qs,ic).call(this,GD);return}N(this,je).debug("Received data:",t.data);const e=iv.decode(t.data),{id:r,payload:n}=e;N(this,tt).emit(e.event.toString(),{id:r,payload:n})};nu=new WeakSet;Kg=function(){return N(this,Ue).readyState===1};rc=new WeakSet;iu=function(t,e){ge(this,dn,{reason:e,code:t}),N(this,tt).emit("disconnected",{code:t,reason:e})};fl=new WeakSet;zg=function(){const{reason:t,code:e}=N(this,dn);e&&e!==1e3&&N(this,Ar)&&N(this,Ae).autoReconnect&&!N(this,Zt)&&(N(this,je).debug(`Triggering reconnection due to ${t}.`),N(this,tt).emit("reconnecting"),Me(this,ro,nc).call(this))};ro=new WeakSet;nc=function(t=!0){return u(this,null,function*(){if(t&&N(this,Zt)){N(this,je).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(N(this,Zt)||N(this,Ir).reset(),N(this,Ae).maxReconnectionAttempts!==null&&N(this,Ir).getAttempts()>=N(this,Ae).maxReconnectionAttempts){N(this,tt).emit("failed"),ge(this,Zt,!1);return}ge(this,Zt,!0),Me(this,Xs,oc).call(this),Me(this,qi,no).call(this);try{if(yield N(this,Ir).wait(),N(this,Ar)===!1)return;if(N(this,je).debug(`Reconnection attempt ${N(this,Ir).getAttempts()}`),N(this,tt).emit("reconnectAttempt",{attempt:N(this,Ir).getAttempts()}),yield this.connect(),!Me(this,nu,Kg).call(this))throw Error("Reconnect Failed");ge(this,Zt,!1),ge(this,dn,{code:void 0,reason:void 0}),N(this,tt).emit("reconnected")}catch{N(this,je).debug("Failed to reconnect."),N(this,tt).emit("reconnectFailure",{attempt:N(this,Ir).getAttempts()}),Me(this,ro,nc).call(this,!1)}})};Qs=new WeakSet;ic=function(t){try{return N(this,Ue).send(t),!0}catch(e){return N(this,je).error(e.message),!1}};sc=new WeakSet;su=function(){this.config.disconnectOnPingTimeout&&(N(this,je).debug("Resetting ping timeout"),Me(this,qi,no).call(this),ge(this,Ji,setTimeout(()=>{var t;N(this,je).debug("Disconnecting the socket due to ping timeout"),ge(this,Ar,!0);const e=3002,r="Ping timeout";(t=N(this,Ue))==null||t.close(e,r),Me(this,rc,iu).call(this,e,r)},N(this,Ae).pingTimeout)))};qi=new WeakSet;no=function(){N(this,Ji)&&(clearTimeout(N(this,Ji)),ge(this,Ji,void 0))};Xs=new WeakSet;oc=function(){N(this,Ue)&&(N(this,Ue).onopen=void 0,N(this,Ue).onerror=void 0,N(this,Ue).onmessage=void 0,N(this,Ue).onclose=void 0)};var qD=Object.defineProperty,KD=Object.getOwnPropertyDescriptor,Nc=(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&&qD(e,r,i),i};const Fp=65535;var Mn,$e,Dn,qo,wd,Ko,Cd,Up;const ov=(Up=class{constructor(t,{peerId:e,meetingId:r,authToken:n,capabilities:i}){_(this,qo),_(this,Ko),_(this,Mn,void 0),_(this,$e,void 0),m(this,"roomName"),m(this,"authToken"),m(this,"capabilities"),m(this,"connectionState"),_(this,Dn,void 0);var s;if(!e||!r||!n)throw new C("peerId, roomName, or authToken can not be empty");T(this,Dn,t),this.capabilities=i,this.roomName=r,this.authToken=n,this.connectionState={state:void 0,reconnected:!1,reconnectionAttempt:void 0},T(this,Mn,ue(this,qo,wd).call(this,e)),T(this,$e,new JD(c(this,Mn),{autoReconnect:!0,disconnectOnPingTimeout:(s=i.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:l}))}get peerId(){return c(this,Dn).getValue("peerId")}updateURL(t){t!==this.peerId&&(T(this,Mn,ue(this,qo,wd).call(this,t)),l.debug("SocketService:: Connection URL updated.")),c(this,$e).updateURL(c(this,Mn))}static getSocketEdgeDomain(t){return $i({servicePrefix:"socket-edge",baseURI:t})}get url(){return c(this,Mn)}connect(){return u(this,null,function*(){yield c(this,$e).connect()})}disconnect(){return c(this,$e).disconnect()}get isConnected(){try{return c(this,$e).readyState===1}catch{return!1}}sendMessage(t,e,r){const n={};return y.injectContext(n),c(this,$e).send(t,r!=null?r:ue(this,Ko,Cd).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,$e).removeListener(s,E),c(this,$e).removeListener(Fp,v),c(this,$e).removeListener(ie.errorResponse,v),c(this,$e).removeListener(se.errorResponse,v)},h=n!=null?n:ue(this,Ko,Cd).call(this),p={};y.injectContext(p);const f=({id:E,payload:v})=>{if(h===E){let R;try{const A=Gw.fromBinary(v);R=new Error(A.errorMessage)}catch(A){R=new Error("failed to parse error message",{cause:A});try{const L=O0.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,$e).on(s,g),c(this,$e).on(Fp,f),c(this,$e).on(ie.errorResponse,f),c(this,$e).on(se.errorResponse,f),setTimeout(()=>{d(g,f),a(new Error(`request timeout for callback eventId:${t}`))},e),c(this,$e).send(t,h,r,new TextEncoder().encode(JSON.stringify(p)))})}on(t,e){c(this,$e).on(t,e)}onStateEvent(t,e){c(this,$e).on(t,e)}flush(){return c(this,$e).flush()}},Mn=new WeakMap,$e=new WeakMap,Dn=new WeakMap,qo=new WeakSet,wd=function(t){let e=ov.getSocketEdgeDomain(c(this,Dn).getValue("baseURI"));typeof Mh(c(this,Dn),"socket_server_base")=="string"&&(e=Mh(c(this,Dn),"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=>qa[o]).join(" ")});return Object.entries(s).forEach(([o,a])=>{n.searchParams.append(o,a.toString())}),n.href},Ko=new WeakSet,Cd=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Up);let mo=ov;Nc([y.trace("SocketService.connect")],mo.prototype,"connect",1);Nc([y.trace("SocketService.disconnect")],mo.prototype,"disconnect",1);Nc([y.trace("SocketService.sendMessagePromise")],mo.prototype,"sendMessagePromise",1);Nc([y.trace("SocketService.sendMessagePromiseWithTimeout")],mo.prototype,"sendMessagePromiseWithTimeout",1);const Kn=class{static handleConnectedRoomsDumpRaw({payload:t}){var e;const r=oC.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=DC.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}static handleMovedPeerRaw({payload:t}){const e=ig.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}static handleConnectedRoomsUpdatedRaw({payload:t}){return Bh.fromBinary(t).payloads.map(e=>({id:e.id,title:e.title}))}static handleConnectedRoomsDeletedRaw({payload:t}){return kC.fromBinary(t).payloads}static getConnectedRoomsDump(){return u(this,null,function*(){const t=yield Kn.socketService.sendMessagePromise(j.getConnectedRoomsDump);return Kn.handleConnectedRoomsDumpRaw(t)})}static createConnectedRooms(t){return u(this,null,function*(){const{payload:e}=yield Kn.socketService.sendMessagePromise(j.createConnectedRooms,lC.toBinary({payloads:t}));return Bh.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 Kn.socketService.sendMessagePromise(j.deleteConnectedRooms,SC.toBinary({payloads:e}));return Kn.handleConnectedRoomsDeletedRaw(r)})}static movePeersBetweenRooms(t){return u(this,null,function*(){try{const e=yield Kn.socketService.sendMessagePromise(j.movePeers,RC.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 Le=Kn;m(Le,"socketService"),m(Le,"currentMeetingId");var zD=Object.defineProperty,YD=Object.getOwnPropertyDescriptor,Lc=(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};const zn=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(w.reset(),tc.cleanup(),Wg(t),ye.isSupported()===!1)throw new C("Browser not supported","0010",!0);const a=$P(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=zn.createSocketService(t),h=d.connect(),p=a.getPlugins(),[{sfu:f,userResponse:g,meetingTitle:E,roomNodeUrl:v}]=yield Promise.all([zn.getRoomMetadata(),zn.setupFlagsmith(t)]);t.setValue("roomNodeOptions",{sfu:f,meetingTitle:E,roomNodeUrl:v});const{theme:R,controllers:A}=yield zn.setupControllers(d,t,g,p);fA(R)&&zn.createRoomNodeClient(t,d),sw();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 zn(r,A)})}static getRoomMetadata(){return u(this,null,function*(){const t=He(),[{roomNodeUrl:e,meetingTitle:r,sfu:n=ts.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=nw(i),a=ne(V({entity:Wd.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?$i({servicePrefix:"flags",baseURI:r}):"edge.api.flagsmith.com";yield K.identify(`${Wd.PEER}_${e}`,JSON.parse(JSON.stringify(a)),!1,5e3,d),l.info("flagsmith::allFlags",{flags:JSON.stringify(K.getAllFlags())},!0)}catch{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=dM.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=iD.init(e,v,d.permissions);let L,F,W,H,I,S,P,D;const ae=new wD(t);Le.socketService=t;const De=new Dc(t),$=new $t(t),x=new RD(t),ve=tc.create(t),Ur=new PD(t),gn=new bD(t),vn=new ti(t),ct=yield mi.init(e,ve,h,A,E),qe=yield fg.init(e,ct.self,ve,ae,g);if(a.participant&&(f===ts.CF&&(D=new Fg(e,ct.self,ve,a)),D=new Ug(e,ct.self,ve,a)),(o=a.e2ee)!=null&&o.enabled&&a.e2ee.manager.init(l,w),a.chat&&(F=yield Mr.init(e,$,vn,ct.self,D.participants)),a.internals&&(I=yield Jl.init()),a.livestream&&E.viewType===Je.Livestream&&K.hasFeature(X.LIVESTREAM)&&(P=new _g(ct.self,gn)),E.viewType!==Je.Chat&&(a.poll&&(L=yield ug.init(e,ct.self,De)),a.recording&&(S=new Eg(e,ct.self,ve)),a.stage&&(W=new gg(e,x,ve,ct.self,D.participants)),a.plugin)){if(!D)throw new C("The plugin module cannot be initialized without the `participant` module");const cs=yield n;H=yield lo.init(e,cs,Ur,$,F==null?void 0:F.chat,ct.self,D.participants)}const Ke={storesManager:new vM(e,Ur),pollController:L,selfController:ct,metaController:qe,chatController:F,stageController:W,pluginController:H,recordingController:S,internalsController:I,livestreamController:P,participantController:D};return{theme:E,permissions:A,controllers:Ke}})}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 Hg(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 mo(t,{peerId:e,meetingId:r,authToken:n,capabilities:i})}};let fo=zn;Lc([y.trace("Controller.init")],fo,"init",1);Lc([y.trace("setupFlagsmith")],fo,"setupFlagsmith",1);Lc([y.trace("Controller.createSocketServiceAndRoomNodeClient")],fo,"createRoomNodeClient",1);Lc([y.trace("Controller.createSocketService")],fo,"createSocketService",1);var QD=Object.defineProperty,XD=Object.getOwnPropertyDescriptor,ZD=(t,e,r,n)=>{for(var i=n>1?void 0:n?XD(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&&QD(e,r,i),i},Ia,gl;class av extends xt{constructor(e,r){super(),_(this,Ia,void 0),m(this,"meetings",[]),m(this,"parentMeeting",null),_(this,gl,void 0),T(this,gl,e),T(this,Ia,r.self)}get supportsConnectedMeetings(){return c(this,Ia).id!==""&&K.hasFeature(X.CONNECTED_MEETINGS)}get isActive(){return this.meetings.length!==0}get currentMeetingId(){return Le.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 Le.getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield Le.createConnectedRooms(e)).map(r=>({id:r.id,title:r.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield Le.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 Le.disableConnectedRooms(e)})}moveParticipants(e,r,n){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=yield Le.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 Le.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})}}Ia=new WeakMap,gl=new WeakMap;ZD([It({maxInvocations:60,period:60})],av.prototype,"getConnectedMeetings",1);var eO=Object.defineProperty,tO=Object.getOwnPropertyDescriptor,au=(t,e,r,n)=>{for(var i=n>1?void 0:n?tO(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&&eO(e,r,i),i},Ms,On,Id,Rd;const an=(Id=class{constructor(t,e,r){m(this,"connectedMeetings"),_(this,Ms,void 0),_(this,On,void 0),_(this,Rd,void 0),T(this,Rd,t),T(this,Ms,r),this.connectedMeetings=new av(t,e),this.setCurrentMeeting(e)}static init(t,e,r){return an.instance||(an.instance=new an(t,e,r)),an.instance.connectedMeetings.supportsConnectedMeetings&&(an.instance.setupEvents(),e.self.once("roomJoined",()=>an.instance.getConnectedMeetings())),an.instance}setCurrentMeeting(t){T(this,On,t),Le.currentMeetingId=t.meta.roomName}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){Le.socketService&&(Le.socketService.on(j.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),Le.socketService.on(j.transferPeer,this.handleTransferPeer.bind(this)),Le.socketService.on(j.movedPeer,this.handleMovedPeer.bind(this)),Le.socketService.on(j.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),Le.socketService.on(j.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this)))}handleTransferPeer(t){const e=Le.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,On).leave("connected-meeting"),Le.socketService=void 0;const n=yield cv.init(ne(V({},c(this,Ms)),{cachedUserDetails:null,defaults:ne(V({},c(this,Ms).defaults),{video:c(this,On).self.videoEnabled,audio:c(this,On).self.audioEnabled}),authToken:e}));n.self.setName(c(this,On).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=Le.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 Le.handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=Le.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=Le.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})}},Ms=new WeakMap,On=new WeakMap,Rd=new WeakMap,m(Id,"instance"),Id);let xc=an;au([y.trace("ConnectedMeetingsController.getConnectedMeetings")],xc.prototype,"getConnectedMeetings",1);au([y.trace("ConnectedMeetingsController.setupEvents")],xc.prototype,"setupEvents",1);au([y.trace("ConnectedMeetingsController.switchMeeting")],xc.prototype,"switchMeeting",1);class rO{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 Vp=new rO;function nO(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 iO=Object.defineProperty,sO=Object.getOwnPropertyDescriptor,Fc=(t,e,r,n)=>{for(var i=n>1?void 0:n?sO(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&&iO(e,r,i),i},nt,zo,Yo,Pd,Bp,jp;let un=(jp=class{constructor(t,e){_(this,Pd),_(this,nt,void 0),_(this,zo,void 0),_(this,Yo,void 0),T(this,Yo,t),T(this,nt,e)}static init(t){return u(this,null,function*(){var e,r,n,i,s;ew(),ye.init();const o=si();Vp.init();const{authToken:a,baseURI:d}=t,h=nO(a,d),{meetingId:p}=h,f=dc(h,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const g=un.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 fo.init(g),v=new un(g,E);return ue(s=v,Pd,Bp).call(s,t),v})}static setupContext(t,e,r,n){var i;const s=zs.createContext(t,e),o=V(V({},Yb),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",Qb({baseURI:n.baseURI})),s.setValue("defaults",e.defaults||{audio:!0,video:!0}),s.setValue("cachedUserDetails",hr(e.cachedUserDetails)),s.setValue("sdkVersion","2.0.0-staging.50"),s}join(){return u(this,null,function*(){const{selfController:t}=c(this,nt);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){Vp.cleanup();const{selfController:e}=c(this,nt);return e.leaveRoom(t)})}get participants(){var t;return(t=c(this,nt).participantController)==null?void 0:t.participants}get self(){var t;return(t=c(this,nt).selfController)==null?void 0:t.self}get meta(){var t;return(t=c(this,nt).metaController)==null?void 0:t.meta}get ai(){var t;return(t=c(this,nt).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=c(this,nt).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=c(this,nt).chatController)==null?void 0:t.chat}get polls(){var t;return(t=c(this,nt).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=c(this,zo))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=c(this,nt).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=c(this,nt).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=c(this,nt).stageController)==null?void 0:t.stage}get stores(){return c(this,nt).storesManager}get __internals__(){var t;return(t=c(this,nt).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)})}},nt=new WeakMap,zo=new WeakMap,Yo=new WeakMap,Pd=new WeakSet,Bp=function(t){T(this,zo,xc.init(c(this,Yo),this,t))},jp);Fc([ut("0002"),fn.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],un.prototype,"join",1);Fc([ut("0003")],un.prototype,"leave",1);Fc([ut("0001"),fn.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],un,"init",1);un=Fc([ut("0000")],un);const cv=un;exports.DyteSelfMedia=Bg;exports.default=cv;
17
+ ${t}`}const fs={maxInvocations:5,period:1};function Vt(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 DM=Object.defineProperty,OM=Object.getOwnPropertyDescriptor,St=(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};const NM=["text","image","file","custom","poll"],$o={maxInvocations:180,period:60};var ae,Mi,et,Di,uo,Yd,Jp,Gp;let dt=(Gp=class extends zt{constructor(t,e,r,n,i){super(),T(this,Yd),f(this,"messages"),f(this,"channels",[]),T(this,ae,void 0),T(this,Mi,void 0),T(this,et,void 0),T(this,Di,void 0),T(this,uo,void 0),f(this,"maxTextLimit",2e3),S(this,uo,t),S(this,et,e),S(this,Di,r),S(this,ae,n),S(this,Mi,i),this.messages=[]}setMaxTextLimit(t){this.maxTextLimit=t}get socketJoined(){return c(this,Yd,Jp).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"?MM(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,ae).permissions)!=null&&n.chatPrivate.canSend)||!((i=c(this,ae).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,ae).permissions)==null?void 0:s.chatPublic)!=null&&a.canSend)||!((d=(o=c(this,ae).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,et).sendMessageToChannel(t,At.TEXT,r);return}let h=[];e&&e.length>0&&(e.push(c(this,ae).id),h=c(this,Mi).joined.toArray().filter(p=>e.includes(p.id)).map(p=>p.userId),h.push(c(this,ae).userId)),c(this,et).sendMessage(t,At.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,ae).permissions)!=null&&n.chatPrivate.canSend)||!((i=c(this,ae).permissions)!=null&&i.chatPrivate.files)){l.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((a=(s=c(this,ae).permissions)==null?void 0:s.chatPublic)!=null&&a.canSend)||!((d=(o=c(this,ae).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=ze(),{getLocation:p,putLocation:m}=yield h.getPresignedUrls(t.name,c(this,ae).config.viewType);if(yield h.uploadFile(t,m),r){c(this,et).sendMessageToChannel(p,At.IMAGE,r);return}let g=[];e&&e.length>0&&(e.push(c(this,ae).id),g=c(this,Mi).joined.toArray().filter(v=>e.includes(v.id)).map(v=>v.userId),g.push(c(this,ae).userId)),c(this,et).sendMessage(p,At.IMAGE,e)}catch{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,ae).permissions)!=null&&n.chatPrivate.canSend)||!((i=c(this,ae).permissions)!=null&&i.chatPrivate.files)){l.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((a=(s=c(this,ae).permissions)==null?void 0:s.chatPublic)!=null&&a.canSend)||!((d=(o=c(this,ae).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=ze(),{getLocation:p,putLocation:m}=yield h.getPresignedUrls(t.name,c(this,ae).config.viewType);if(yield h.uploadFile(t,m),r){c(this,et).sendMessageToChannel(JSON.stringify({link:p,name:t.name,size:"size"in t?t.size:0}),At.FILE,r);return}let g=[];e&&e.length>0&&(e.push(c(this,ae).id),g=c(this,Mi).joined.toArray().filter(I=>e.includes(I.id)).map(I=>I.userId),g.push(c(this,ae).userId));const v=JSON.stringify({link:p,name:t.name,size:"size"in t?t.size:0});c(this,et).sendMessage(v,At.FILE,e)}catch{throw new _("Error sending file message.","0500")}})}get rateLimits(){return $o}updateRateLimits(t,e){$o.maxInvocations=t,$o.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,ae).permissions)!=null&&r.chatPrivate.canSend)||!((n=c(this,ae).permissions)!=null&&n.chatPrivate.files)||!((i=c(this,ae).permissions)!=null&&i.chatPrivate.text)){l.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((a=(s=c(this,ae).permissions)==null?void 0:s.chatPublic)!=null&&a.canSend)||!((d=(o=c(this,ae).permissions)==null?void 0:o.chatPublic)!=null&&d.files)||!((p=(h=c(this,ae).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=ze(),{getLocation:G,putLocation:W}=yield C.getPresignedUrls(J.name,c(this,ae).config.viewType);return yield C.uploadFile(J,W),{link:G,type:J.type,name:J.name,size:J.size}}catch{throw new _("Error sending image message.","0500")}}),N=Z(B({},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,et).sendMessage(JSON.stringify(N),At.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,ae).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,ae).permissions)==null?void 0:s.chatPublic)!=null&&a.canSend)||!((d=(o=c(this,ae).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,et).editMessage(t,e,At.TEXT,r)})}editImageMessage(t,e,r){return u(this,null,function*(){var n,i,s,a;if(!((i=(n=c(this,ae).permissions)==null?void 0:n.chatPublic)!=null&&i.canSend)||!((a=(s=c(this,ae).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=ze(),{getLocation:d,putLocation:h}=yield o.getPresignedUrls(e.name,c(this,ae).config.viewType);yield o.uploadFile(e,h),c(this,et).editMessage(t,d,At.IMAGE,r)}catch{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,ae).permissions)==null?void 0:n.chatPublic)!=null&&i.canSend)||!((a=(s=c(this,ae).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=ze(),{getLocation:d,putLocation:h}=yield o.getPresignedUrls(e.name,c(this,ae).config.viewType);yield o.uploadFile(e,h),c(this,et).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),At.FILE,r)}catch{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,ae).permissions)==null?void 0:r.chatMessage)==null?void 0:n.canDelete)==="NONE")throw new _("Not permitted to delete messages","0501");c(this,et).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,ae).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,et).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,ae).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,et).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,et).getChatMessagesPaginated(t,e,r,n,i);return{messages:s.messages.map(a=>qr.formatSocketServiceMessage(a)),next:s.next}})}createChannel(t,e){return u(this,arguments,function*(r,n,i={}){var s;const a=(s=c(this,ae).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,ae).userId])];return yield c(this,Di).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,ae).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,Di).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,Di).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,et).searchMessages(e,r)).map(qr.formatSocketServiceMessage)})}markLastReadMessage(t,e){return u(this,null,function*(){yield c(this,et).markLastReadMessage(t,e);const r=this.channels.find(n=>n.id===t);if(r){const n=Z(B({},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)}},ae=new WeakMap,Mi=new WeakMap,et=new WeakMap,Di=new WeakMap,uo=new WeakMap,Yd=new WeakSet,Jp=function(){return c(this,uo).getValue("connectionHandler")},Gp);St([y.trace("DyteChat.sendTextMessage"),Vt($o)],dt.prototype,"sendTextMessage",1);St([y.trace("DyteChat.sendImageMessage"),Vt({maxInvocations:20,period:60})],dt.prototype,"sendImageMessage",1);St([y.trace("DyteChat.sendFileMessage"),Vt({maxInvocations:20,period:60})],dt.prototype,"sendFileMessage",1);St([y.trace("DyteChat.sendMessage"),Vt({maxInvocations:180,period:60})],dt.prototype,"sendMessage",1);St([y.trace("DyteChat.editTextMessage")],dt.prototype,"editTextMessage",1);St([y.trace("DyteChat.editImageMessage")],dt.prototype,"editImageMessage",1);St([y.trace("DyteChat.editFileMessage")],dt.prototype,"editFileMessage",1);St([y.trace("DyteChat.editMessage")],dt.prototype,"editMessage",1);St([y.trace("DyteChat.deleteMessage")],dt.prototype,"deleteMessage",1);St([y.trace("DyteChat.createChannel")],dt.prototype,"createChannel",1);St([y.trace("DyteChat.updateChannel")],dt.prototype,"updateChannel",1);St([y.trace("DyteChat.sendMessageToChannel")],dt.prototype,"sendMessageToChannel",1);St([y.trace("DyteChat.getChannelMembers")],dt.prototype,"getChannelMembers",1);St([y.trace("DyteChat.searchMessages")],dt.prototype,"searchMessages",1);St([y.trace("DyteChat.markLastReadMessage")],dt.prototype,"markLastReadMessage",1);dt=St([yt("0500")],dt);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},Qd,qp;const Qn=(qp=class{constructor(t,e,r,n,i){f(this,"chat"),f(this,"chatSocketHandler"),f(this,"chatChannelSocketHandler"),f(this,"self"),T(this,Qd,void 0),S(this,Qd,t),this.chatSocketHandler=e,this.chatChannelSocketHandler=r,this.chat=new dt(t,e,r,n,i),this.self=n,this.setupEvents()}static init(t,e,r,n,i){return u(this,null,function*(){return new Qn(t,e,r,n,i)})}static formatMessage(t){return Z(B({},t),{time:new Date(t.time),type:NM[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 At.TEXT:{r.message=t.payload;break}case At.IMAGE:{r.link=t.payload;break}case At.FILE:{const{link:n,name:i,size:s}=JSON.parse(t.payload);r.link=n,r.name=i,r.size=s;break}case At.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 Qn.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=Kg.fromBinary(t.payload).messages;this.chat.messages=e.map(r=>Qn.formatSocketServiceMessage(r))})}setupEvents(){w.on(b.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){this.getChatMessages()})),this.chatSocketHandler.on(xe.sendMessageToRoom,t=>{const e=Qn.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=Qn.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=Qn.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(di.createChatChannel,t=>{const[e]=t.chatChannels,r=gi.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(di.updateChatChannel,t=>{const[e]=t.chatChannels,r=gi.formatChannel(e);this.chat.channels=this.chat.channels.map(n=>n.id===r.id?r:n),this.chat.emit("channelUpdate",r)})}},Qd=new WeakMap,qp);let qr=Qn;FM([y.trace("ChatController.setupEvents")],qr.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},Xd,zp,Vs,Us,ho,Kp;let Bl=(Kp=class extends zt{constructor(t,e,r){super(),T(this,Xd),f(this,"items"),T(this,Vs,void 0),T(this,Us,void 0),T(this,ho,void 0),S(this,ho,t),S(this,Vs,e),S(this,Us,r),this.items=[]}get socketJoined(){var t;return((t=c(this,Xd,zp))==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,Vs).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,Us).createPoll(t,e,r,n)})}vote(t,e){return u(this,null,function*(){if(!c(this,Vs).permissions.polls.canVote){l.error("DytePolls::vote::permission_denied");return}yield c(this,Us).votePoll(t,e)})}},Xd=new WeakSet,zp=function(){return c(this,ho).getValue("connectionHandler")},Vs=new WeakMap,Us=new WeakMap,ho=new WeakMap,Kp);Bl=BM([yt("0700")],Bl);var jM=Object.defineProperty,HM=Object.getOwnPropertyDescriptor,WM=(t,e,r,n)=>{for(var i=n>1?void 0:n?HM(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&&jM(e,r,i),i},Bs,Oi,Yp;const Ji=(Yp=class{constructor(t,e,r){f(this,"polls"),T(this,Bs,void 0),T(this,Oi,void 0),this.polls=new Bl(t,e,r),S(this,Bs,e),S(this,Oi,r),this.setupEvents()}static init(t,e,r){return u(this,null,function*(){return new Ji(t,e,r)})}canViewPolls(){return c(this,Bs).permissions.polls.canView}setupEvents(){const t={[Hr.createPoll]:n=>{n.poll&&this.updatePoll(Ji.formatSocketServicePoll(n.poll))},[Hr.updatePoll]:n=>{n.poll&&this.updatePoll(Ji.formatSocketServicePoll(n.poll))},[Hr.votePoll]:n=>{n.poll&&this.updatePoll(Ji.formatSocketServicePoll(n.poll))}},e=()=>{w.on(b.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(t).map(Number).forEach(n=>{c(this,Oi).on(n,t[n])})},r=()=>{w.on(b.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(t).map(Number).forEach(n=>{c(this,Oi).removeListeners(n)})};c(this,Bs).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,Oi).getPolls();if(!(t!=null&&t.payload))return;const{polls:e}=tM.fromBinary(t.payload);this.polls.items=e.map(r=>Ji.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}}},Bs=new WeakMap,Oi=new WeakMap,Yp);let ev=Ji;WM([y.trace("PollController.setupEvents")],ev.prototype,"setupEvents",1);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},tv=(t=>(t[t.User=0]="User",t[t.Meeting=1]="Meeting",t))(tv||{}),js,Zd,Qp,po,el,Ni,mo,Xp;let jl=(Xp=class extends zt{constructor(t,e,r,n,i){super(),T(this,Zd),T(this,po),f(this,"selfActiveTab"),f(this,"broadcastTabChanges"),T(this,js,void 0),T(this,Ni,void 0),T(this,mo,void 0),f(this,"viewType"),f(this,"meetingStartedTimestamp"),f(this,"meetingTitle"),f(this,"sessionId"),S(this,js,t),S(this,Ni,e),this.viewType=r,S(this,mo,n),this.meetingTitle=i,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return c(this,po,el).socketState}get mediaState(){return c(this,po,el).mediaState}get meetingId(){var t;return(t=c(this,Zd,Qp))==null?void 0:t.roomName}setBroadcastTabChanges(t){if(!c(this,Ni).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,Ni).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){c(this,mo).broadcastMessage("spotlight",{userId:c(this,Ni).userId,currentTab:this.selfActiveTab})}},js=new WeakMap,Zd=new WeakSet,Qp=function(){return c(this,js).getValue("roomNodeClient")},po=new WeakSet,el=function(){return c(this,js).getValue("connectionHandler")},Ni=new WeakMap,mo=new WeakMap,Xp);jl=GM([yt("0800")],jl);function qM(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 zM=Object.defineProperty,KM=Object.getOwnPropertyDescriptor,rv=(t,e,r,n)=>{for(var i=n>1?void 0:n?KM(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};let Mn=class extends zt{constructor(){super(),f(this,"transcripts"),this.transcripts=[]}static init(t){return u(this,null,function*(){const e=new Mn;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]]=qM(t);return{id:Ei(),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=>Mn.parseTranscript(e,!1)).filter(Boolean):[]}getActiveTranscript(){return u(this,null,function*(){try{const t=ze(),{transcript:e}=yield t.getActiveTranscript();this.transcripts=Mn.parseTranscripts(e)}catch{}})}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)})}};rv([y.trace("DyteAi.getActiveTranscript")],Mn.prototype,"getActiveTranscript",1);Mn=rv([yt("0000")],Mn);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},Bn,Hs,tl,Zp;const nv=(Zp=class{constructor(t,e,r,n,i,s){f(this,"meta"),f(this,"ai"),T(this,Bn,void 0),T(this,Hs,void 0),f(this,"aiSocketHandler"),T(this,tl,void 0),S(this,tl,t),this.meta=new jl(t,e,e.config.viewType,r,s),this.ai=n,S(this,Bn,e),S(this,Hs,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 Mn.init(e.permissions.transcriptionEnabled);return new nv(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,tv.Meeting),this.meta.emit("activeTabUpdate",t.currentTab))}setupEvents(){w.on(b.TRANSPORT_STATE_UPDATE,t=>{this.meta.emit("mediaConnectionUpdate",t)}),w.on(b.SOCKET_STATE_UPDATE,t=>{this.meta.emit("socketConnectionUpdate",t)}),w.on(b.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})}}),w.on(b.PRODUCER_SCORE_UPDATE,({score:t})=>{t<5&&this.meta.emit("poorConnection",{score:t})}),c(this,Bn).permissions.canSpotlight&&(l.info("DyteMetaController::Asserting Spotlight"),this.meta.selfActiveTab&&c(this,Hs).broadcastMessage("spotlight",{userId:c(this,Bn).userId,currentTab:this.meta.selfActiveTab})),w.on(b.PEER_JOINED_INTERNAL,t=>u(this,null,function*(){c(this,Bn).permissions.canSpotlight&&this.meta.selfActiveTab&&c(this,Hs).broadcastToPeers("spotlight",[t.id],{userId:c(this,Bn).userId,currentTab:this.meta.selfActiveTab})})),w.on(b.ROOM_MESSAGE,t=>{var e,r;let n;if("type"in t){if(t.type!=="spotlight")return;n=B(B({},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)}),w.on(b.MESSAGE,t=>{var e,r;let n;if("type"in t){if(t.type!=="spotlight")return;n=B(B({},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=Mn.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}`)})}},Bn=new WeakMap,Hs=new WeakMap,tl=new WeakMap,Zp);let iv=nv;XM([y.trace("MetaController.setupEvents")],iv.prototype,"setupEvents",1);var ZM=Object.defineProperty,eD=Object.getOwnPropertyDescriptor,Ci=(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},cr,fa,Ae,Jo,xr,Ur,ga,Go;class xn extends zt{constructor(e,r,n,i,s){super(),T(this,ga),T(this,cr,void 0),T(this,fa,void 0),T(this,Ae,void 0),T(this,Jo,void 0),T(this,xr,void 0),T(this,Ur,void 0),S(this,Ur,e),S(this,cr,i),S(this,fa,s),S(this,Ae,r),S(this,Jo,n),S(this,xr,[]),this.setupEvents()}get status(){return c(this,Ur).getValue("stageStatus")}setupEvents(){const e={[b.GET_STAGE_REQUESTS]:i=>u(this,null,function*(){S(this,xr,i)}),[b.UPDATE_STAGE_REQUESTS]:i=>u(this,[i],function*({add:s}){const a=c(this,xr).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])=>{w.onAsync(i,s)})},n=()=>{Object.entries(e).forEach(([i,s])=>{w.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,cr).getStageRequests()):(n(),S(this,xr,[]),this.emit("stageAccessRequestUpdate",c(this,xr))))}),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,Jo).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return S(this,xr,e),{stageRequests:c(this,xr)}}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){Ke(this,ga,Go).call(this,"ACCEPTED_TO_JOIN_STAGE");return}c(this,cr).requestAccess(),Ke(this,ga,Go).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,cr).cancelRequestAccess(),Ke(this,ga,Go).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,cr).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,cr).denyAccess(e)}join(){return u(this,null,function*(){const e=c(this,Ur).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,cr).joinStage(),e===gt.Livestream?yield c(this,fa).joinRoom(c(this,Ae),e):w.emit(b.RESET_PRODUCER_STATE),c(this,Ur).setValue("stageStatus","ON_STAGE"),e===gt.Livestream){const{peers:r}=yield c(this,fa).getStagePeers();w.emit(b.SOCKET_PEERS,r),w.emit(b.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,cr).leaveStage(c(this,Ae).userId),c(this,Ur).setValue("stageStatus","OFF_STAGE",!1),yield w.emitAsync(b.LEAVE_MEDIA_ROOM,"stageLeft"),c(this,Ur).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,cr).kick(e)})}}cr=new WeakMap,fa=new WeakMap,Ae=new WeakMap,Jo=new WeakMap,xr=new WeakMap,Ur=new WeakMap,ga=new WeakSet,Go=function(t){return u(this,null,function*(){this.status!==t&&c(this,Ur).setValue("stageStatus",t)})};Ci([y.trace("DyteStage.getStageRequests")],xn.prototype,"getAccessRequests",1);Ci([y.trace("DyteStage.requestAccess")],xn.prototype,"requestAccess",1);Ci([y.trace("DyteStage.cancelRequestAccess")],xn.prototype,"cancelRequestAccess",1);Ci([y.trace("DyteStage.grantAccess")],xn.prototype,"grantAccess",1);Ci([y.trace("DyteStage.denyAccess")],xn.prototype,"denyAccess",1);Ci([y.trace("DyteStage.joinStage")],xn.prototype,"join",1);Ci([y.trace("DyteStage.leaveStage")],xn.prototype,"leave",1);function tD(t){return!(t.viewType==="LIVESTREAM"||t.viewType==="CHAT")}function Ou(t){switch(t){case Jr.UNSPECIFIED:return"OFF_STAGE";case Jr.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case Jr.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case Jr.OFF_STAGE:return"OFF_STAGE";case Jr.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var rD=Object.defineProperty,nD=Object.getOwnPropertyDescriptor,iD=(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&&rD(e,r,i),i},Xn,Gi,Zn,qo,Tn;class sv{constructor(e,r,n,i,s){f(this,"stage"),T(this,Xn,void 0),T(this,Gi,void 0),T(this,Zn,void 0),T(this,qo,0),T(this,Tn,void 0),S(this,Tn,e),this.stage=new xn(e,i,s,r,n),S(this,Zn,r),S(this,Xn,i),S(this,Gi,s),this.setupEvents()}setupEvents(){c(this,Tn).subscribe("stageStatus",e=>{this.stage.emit("stageStatusUpdate",e)}),c(this,Zn).on(j.grantStageAccess,()=>{c(this,Xn).permissions.stageAccess!==K.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),c(this,Zn).on(j.peerStageStatusUpdate,e=>{e!==void 0&&(e.peerId===c(this,Xn).id?this.selfStageStatusHandler(e):this.peerStageStatusHandler(e))}),c(this,Zn).on(j.denyStageAccess,()=>{c(this,Xn).permissions.stageAccess!==K.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),c(this,Zn).on(j.getStageRequests,e=>u(this,null,function*(){var r;if(c(this,Xn).permissions.stageAccess!==K.Allowed)return;const n=(r=e==null?void 0:e.stageRequests)!=null?r:[];yield w.emitAsync(b.GET_STAGE_REQUESTS,n),c(this,qo)<n.length&&n.length>0&&this.stage.emit("newStageRequest",{count:n.length}),S(this,qo,n.length),this.stage.emit("stageAccessRequestUpdate",n)}))}getCurrentStageRequests(){return c(this,Gi).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,Tn).setValue("stageStatus",e)})}selfStageStatusHandler(e){const r=Ou(e.stageType),n=c(this,Tn).getValue("stageStatus");if(n!==r)switch(e.stageType){case 1:c(this,Tn).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,Tn).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}peerStageStatusHandler(e){return u(this,null,function*(){const r=c(this,Gi).joined.get(e.peerId),n=c(this,Gi).viewMode==="ACTIVE_GRID";if(!r){l.warn("err::peerStageStatusUpdate: participant not found");return}switch(e.stageType){case 1:r.setStageStatus("ON_STAGE"),n&&w.emit(b.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&&w.emit(b.UPDATE_ACTIVE);break}w.emit(b.UPDATE_PEER_STAGE_STATUS,{id:r.id,status:r.stageStatus})})}}Xn=new WeakMap,Gi=new WeakMap,Zn=new WeakMap,qo=new WeakMap,Tn=new WeakMap;iD([y.trace("DyteStage.setupEvents")],sv.prototype,"setupEvents",1);var sD=Object.defineProperty,aD=Object.getOwnPropertyDescriptor,dd=(t,e,r,n)=>{for(var i=n>1?void 0:n?aD(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&&sD(e,r,i),i};const je={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 Tt,Qt,Ws,$s,rn,Js,Gs,Li,qs,em;let ls=(em=class extends ps{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,Li),T(this,Tt,void 0),f(this,"baseURL"),f(this,"createdAt"),f(this,"description"),f(this,"id"),f(this,"name"),T(this,Qt,void 0),T(this,Ws,void 0),T(this,$s,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,rn,void 0),f(this,"config"),T(this,Js,void 0),f(this,"active"),f(this,"iframes"),f(this,"enabledBy"),T(this,Gs,void 0),S(this,Gs,t),this.baseURL=e,this.createdAt=new Date(r),this.description=n,this.id=i,this.name=s,S(this,Qt,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,Tt,I),S(this,Ws,P),S(this,$s,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,Tt).customPluginEventToRoom(this.id,n,i);break}case z.customPluginEventToPeers:{c(this,Tt).customPluginEventToPeers(this.id,n.peerIds,n,i);break}case z.enablePluginForRoom:{c(this,Tt).enablePluginForRoom(this.id,i);break}case z.enablePluginForPeers:{c(this,Tt).enablePluginForPeers(this.id,n.peerIds,i);break}case z.disablePluginForRoom:{c(this,Tt).disablePluginForRoom(this.id,i);break}case z.disablePluginForPeers:{c(this,Tt).disablePluginForPeers(this.id,n.peerIds,i);break}case z.storeInsertKeys:{c(this,Tt).storeInsertKeys(this.id,n.store,n.insertKeys,i);break}case z.storeGetKeys:{c(this,Tt).storeGetKeys(this.id,n.store,n.getKeys,i);break}case z.storeDeleteKeys:{c(this,Tt).storeDeleteKeys(this.id,n.store,n.deleteKeys,i);break}case z.storeDelete:{c(this,Tt).storeDelete(this.id,n.store,i);break}case je.chatMessage:{const{messagePayload:a,peerIds:o}=n;if(!c(this,$s)){this.sendIframeEvent({type:je.chatMessage,uuid:r.uuid,payload:{error:"Chat is disabled for this room."}});return}try{yield c(this,$s).sendMessage(a,o),this.sendIframeEvent({type:je.chatMessage,uuid:r.uuid,payload:{success:!0}})}catch(d){this.sendIframeEvent({type:je.chatMessage,uuid:r.uuid,payload:{error:d}})}break}case je.getPeer:{let a;const{peerId:o}=n,d=Z(B({},c(this,Qt)),{id:c(this,Qt).id,isRecorder:(e=c(this,Qt).permissions)==null?void 0:e.isRecorder,isHidden:c(this,Qt).permissions.hiddenParticipant,stageStatus:c(this,Qt).stageStatus});o?(a=c(this,Ws).joined.get(n.peerId),c(this,Qt).id===o&&(a=d)):a=d,this.sendIframeEvent({type:je.getPeer,payload:{peer:a&&Oc(a)},uuid:r.uuid});break}case je.getPeers:{const a=c(this,Ws).joined.toArray().map(o=>Oc(o));this.sendIframeEvent({type:je.getPeers,payload:{peers:a},uuid:r.uuid});break}case je.getPluginInitiator:{this.sendIframeEvent({type:je.getPluginInitiator,payload:{enabledBy:this.enabledBy},uuid:r.uuid});break}case je.getDisplayTitle:{this.sendIframeEvent({type:je.getDisplayTitle,payload:{displayTitle:c(this,Li,qs).meetingTitle},uuid:r.uuid});break}case je.getRoomName:{this.sendIframeEvent({type:je.getRoomName,payload:{roomName:c(this,Li,qs).roomName},uuid:r.uuid});break}case je.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:je.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,Js))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,Js),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:c(this,Gs).getValue("apiBase"),pluginId:this.id,roomName:(r=c(this,Li,qs).roomName)!=null?r:"",displayTitle:c(this,Li,qs).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=ze(),e=yield t.authorizePlugin(this.id);S(this,Js,e),S(this,rn,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,rn,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,Qt).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(c(this,Tt).addPlugin(this.id,this.staggered),S(this,rn,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,Qt).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==c(this,Qt).id||(c(this,Tt).removePlugin(this.id),l.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:c(this,rn)?new Date().getTime()-c(this,rn).getTime():0}}),S(this,rn,void 0)))})}},Tt=new WeakMap,Qt=new WeakMap,Ws=new WeakMap,$s=new WeakMap,rn=new WeakMap,Js=new WeakMap,Gs=new WeakMap,Li=new WeakSet,qs=function(){return c(this,Gs).getValue("roomNodeClient")},em);dd([Vt({maxInvocations:5,period:1})],ls.prototype,"sendData",1);dd([y.trace("DytePlugin.activatePlugin")],ls.prototype,"activate",1);dd([y.trace("DytePlugin.deactivatePlugin")],ls.prototype,"deactivate",1);ls=dd([yt("0600")],ls);var Qe,qi;class av extends Map{constructor(e){const{onAddEvent:r,onDeleteEvent:n,onClearEvent:i}=e;super(),T(this,Qe,void 0),T(this,qi,void 0),f(this,"onAddEvent"),f(this,"onDeleteEvent"),f(this,"onClearEvent"),S(this,Qe,new ps),this.onAddEvent=r,this.onDeleteEvent=n,this.onClearEvent=i,S(this,qi,new Map)}emit(e,...r){return c(this,Qe).emit(e,...r)}on(e,r){return c(this,Qe).on(e,r)}addListener(e,r){return c(this,Qe).addListener(e,r)}off(e,r){return c(this,Qe).off(e,r)}once(e,r){return c(this,Qe).once(e,r)}prependListener(e,r){return c(this,Qe).prependListener(e,r)}prependOnceListener(e,r){return c(this,Qe).prependOnceListener(e,r)}removeListener(e,r){return c(this,Qe).removeListener(e,r)}removeAllListeners(e){return c(this,Qe).removeAllListeners(e)}listeners(e){return c(this,Qe).listeners(e)}listenerCount(e){return c(this,Qe).listenerCount(e)}getMaxListeners(){return c(this,Qe).getMaxListeners()}setMaxListeners(e){return c(this,Qe).setMaxListeners(e)}eventNames(){return c(this,Qe).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,qi).set(e,s),r.on("*",s),n&&c(this,Qe).emit(this.onAddEvent,r),i}delete(e,r=!0,n=!1){const i=this.get(e);if(!i)return!1;i.removeListener("*",c(this,qi).get(e));const s=super.delete(e);return n&&i.removeAllListeners(),r&&c(this,Qe).emit(this.onDeleteEvent,i),s}clear(e=!0,r=!1){this.forEach(i=>{i.removeListener("*",c(this,qi).get(i.id)),r&&i.removeAllListeners()});const n=super.clear();return e&&c(this,Qe).emit(this.onClearEvent),n}toArray(){return Array.from(this.values())}}Qe=new WeakMap,qi=new WeakMap;class tm extends av{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 oD=Object.defineProperty,cD=Object.getOwnPropertyDescriptor,dD=(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};let Hl=class{constructor(){f(this,"all"),f(this,"active"),this.all=new tm,this.active=new tm}};Hl=dD([yt("0600")],Hl);var lD=Object.defineProperty,uD=Object.getOwnPropertyDescriptor,ld=(t,e,r,n)=>{for(var i=n>1?void 0:n?uD(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&&lD(e,r,i),i},rr,zs,fo,rm;const ov=(rm=class{constructor(t,e,r,n){f(this,"plugins"),T(this,rr,void 0),T(this,zs,void 0),T(this,fo,void 0),S(this,rr,e),S(this,zs,r),S(this,fo,t),this.plugins=n,this.setupEvents()}static init(t,e,r,n,i,s,a){return u(this,null,function*(){const o=new Hl;return e.forEach(d=>{const h=new ls(t,d,r,s,a,i);o.all.add(h)}),new ov(t,r,n,o)})}getRoomPlugins(){return u(this,null,function*(){var t;const{plugins:e}=yield c(this,rr).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)}),w.onAsync(b.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){yield this.getRoomPlugins(),l.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to fetch plugins.")})),c(this,rr).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,rr).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,rr).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,rr).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,rr).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,rr).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,rr).on(z.storeDelete,(t,e)=>u(this,null,function*(){this.sendIframeEvent(z.storeDelete,t.pluginId,e,{storeName:t.storeName})})),c(this,zs).on(xe.sendMessageToPeers,t=>{const e=qr==null?void 0:qr.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(je.chatMessage,{message:e})}),c(this,zs).on(xe.sendMessageToRoom,t=>{const e=qr==null?void 0:qr.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(je.chatMessage,{message:e})}),w.on(b.PEER_JOINED_INTERNAL,t=>{const e=Oc(t);this.broadcastIframeEvent(je.peerJoined,e)}),w.on(b.PEER_CLOSED,t=>{this.broadcastIframeEvent(je.peerLeft,t)}),w.on(b.UPDATE_PEER_STAGE_STATUS,t=>{this.broadcastIframeEvent(je.peerStageStatusUpdate,t)}),c(this,fo).subscribe("stageStatus",t=>{this.broadcastIframeEvent(je.stageStatusUpdate,t)})}},rr=new WeakMap,zs=new WeakMap,fo=new WeakMap,rm);let za=ov;ld([y.trace("PluginController.getRoomPlugins")],za.prototype,"getRoomPlugins",1);ld([y.trace("PluginController.enableForSelf")],za.prototype,"enablePlugin",1);ld([y.trace("PluginController.disableForSelf")],za.prototype,"disablePlugin",1);ld([y.trace("PluginController.setupEvents")],za.prototype,"setupEvents",1);class hD{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&&(w.emit(b.SOCKET_STATE_UPDATE,n),this.socketState=n)}}var pD=Object.defineProperty,mD=Object.getOwnPropertyDescriptor,Ka=(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},Ks,go,Ys,vo,nm;let vi=(nm=class extends zt{constructor(t,e){super(),T(this,Ys),T(this,Ks,void 0),T(this,go,void 0),f(this,"recordingPeerIds",[]),f(this,"recordings",[]),S(this,go,t),S(this,Ks,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,Ks).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=ze(),{recording:r={}}=c(this,go).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 Ke(this,Ys,vo).call(this,"stop",["RECORDING","PAUSED"],t)})}pause(t){return u(this,null,function*(){yield Ke(this,Ys,vo).call(this,"pause",["RECORDING"],t)})}resume(t){return u(this,null,function*(){yield Ke(this,Ys,vo).call(this,"resume",["PAUSED"],t)})}},Ks=new WeakMap,go=new WeakMap,Ys=new WeakSet,vo=function(t,e,r){return u(this,null,function*(){if(!c(this,Ks).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 ze().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")}}))})},nm);Ka([y.trace("DyteRecording.start")],vi.prototype,"start",1);Ka([y.trace("DyteRecording.stop")],vi.prototype,"stop",1);Ka([y.trace("DyteRecording.stop")],vi.prototype,"pause",1);Ka([y.trace("DyteRecording.stop")],vi.prototype,"resume",1);vi=Ka([yt("1000")],vi);var fD=Object.defineProperty,gD=Object.getOwnPropertyDescriptor,vD=(t,e,r,n)=>{for(var i=n>1?void 0:n?gD(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&&fD(e,r,i),i},Wl;class cv{constructor(e,r,n){f(this,"recording"),f(this,"room"),T(this,Wl,void 0),S(this,Wl,e),this.recording=new vi(e,r),this.room=n,this.setupEvents()}getRecordingTypeFromProtoType(e){let r;switch(e){case pi.BROWSER:r="BROWSER";break;case pi.COMPOSITE:r="COMPOSITE";break;case pi.TRACK:r="TRACK";break;default:r="BROWSER"}return r}setupEvents(){w.on(b.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)})}}Wl=new WeakMap;vD([y.trace("RecordingController.setupEvents")],cv.prototype,"setupEvents",1);class yD{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=Ee,this.callStats=n}static init(e){return new Nu(l,yD,e)}}class Lu{constructor(e){f(this,"internals"),this.internals=e}static init(){return u(this,null,function*(){const e=Nu.init($);return new Lu(e)})}}var SD=Object.defineProperty,ED=Object.getOwnPropertyDescriptor,Kt=(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&&SD(e,r,i),i},st,at,Be,Fr,dr,zo,$l;class Ut extends ps{constructor(e,r,n=Jl,i=!0){super(),T(this,st,void 0),T(this,at,void 0),T(this,Be,void 0),T(this,Fr,void 0),T(this,dr,void 0),T(this,zo,void 0),T(this,$l,void 0),f(this,"audioUpdateInProgress"),f(this,"videoUpdateInProgress"),S(this,$l,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,S(this,st,new dv(e,r)),S(this,at,new jD(c(this,st),void 0,n)),S(this,Be,new zD(c(this,st),void 0,n)),S(this,dr,new JD(c(this,st))),S(this,Fr,new WD(c(this,st))),S(this,zo,i),c(this,at).on("trackMuted",this.onAudioTrackMuted.bind(this)),c(this,at).on("trackChanged",this.onAudioTrackChanged.bind(this)),c(this,Be).on("trackChanged",this.onVideoTrackChanged.bind(this)),c(this,Be).on("trackEnded",this.onVideoTrackEnded.bind(this)),c(this,dr).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,Be).setMediaTrack(a);try{yield c(this,Fr).setupSpeaker()}catch{}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,Fr).currentDevice)!=null&&i.deviceId&&$.selectedDevice("SPEAKER",c(this,Fr).currentDevice),c(this,st).onDeviceChange((o,d,h)=>{this.onDeviceChange(d,h)})})}getCurrentDevices(){return{audio:c(this,at).currentDevice,video:c(this,Be).currentDevice,speaker:c(this,Fr).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{}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,Fr).setupSpeaker()}setSpeakerDevice(e){return u(this,null,function*(){yield c(this,Fr).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,Be).mediaTrack}get videoTrack(){return c(this,Be).transformedMediaTrack}get videoEnabled(){return c(this,Be).trackEnabled}enableVideo(){return u(this,null,function*(){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{yield c(this,Be).unmuteTrack()}catch{}finally{this.videoUpdateInProgress=!1}}})}disableVideo(){c(this,Be).disableTrack()}getVideoDevices(e){return c(this,st).getVideoInputDevices(e)}setVideoDevice(e){return u(this,null,function*(){yield c(this,Be).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,Be).updateConstraints(e)})}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:c(this,dr).audioMediaTrack,video:c(this,dr).videoMediaTrack}}get screenShareEnabled(){return c(this,dr).trackEnabled}enableScreenShare(){return u(this,null,function*(){yield c(this,dr).enableScreenShare()})}disableScreenShare(){return u(this,null,function*(){c(this,dr).disableScreenShare()})}updateScreenshareConstraints(e){return u(this,null,function*(){yield c(this,dr).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,Be).addMiddleware(e)}removeVideoMiddleware(e){return c(this,Be).removeMiddleware(e)}removeAllVideoMiddlewares(){return c(this,Be).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return c(this,Be).setVideoMiddlewareGlobalConfig(e)}destruct(){c(this,at).disableTrack(),c(this,Be).disableTrack(),c(this,Be).terminateMiddlewareWebWorker(),c(this,dr).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,zo))&&((n=e==null?void 0:e.added)==null||n.forEach(s=>u(this,null,function*(){var a;s&&!Jl(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,Be).disableTrack(),c(this,Be).terminateMiddlewareWebWorker()}removeDocumentEventListeners(){return u(this,null,function*(){document.removeEventListener("visibilitychange",this.onVisibilityChange)})}}st=new WeakMap,at=new WeakMap,Be=new WeakMap,Fr=new WeakMap,dr=new WeakMap,zo=new WeakMap,$l=new WeakMap;Kt([y.trace("MediaHandler.setupStreams")],Ut.prototype,"setupStreams",1);Kt([y.trace("MediaHandler.enableAudio")],Ut.prototype,"enableAudio",1);Kt([y.trace("MediaHandler.disableAudio")],Ut.prototype,"disableAudio",1);Kt([y.trace("MediaHandler.setAudioDevice")],Ut.prototype,"setAudioDevice",1);Kt([y.trace("MediaHandler.enableVideo")],Ut.prototype,"enableVideo",1);Kt([y.trace("MediaHandler.disableVideo")],Ut.prototype,"disableVideo",1);Kt([y.trace("MediaHandler.setVideoDevice")],Ut.prototype,"setVideoDevice",1);Kt([y.trace("MediaHandler.updateVideoConstraints")],Ut.prototype,"updateVideoConstraints",1);Kt([y.trace("MediaHandler.enableScreenShare")],Ut.prototype,"enableScreenShare",1);Kt([y.trace("MediaHandler.disableScreenShare")],Ut.prototype,"disableScreenShare",1);Kt([y.trace("MediaHandler.updateScreenshareConstraints")],Ut.prototype,"updateScreenshareConstraints",1);Kt([y.trace("MediaHandler.destruct")],Ut.prototype,"destruct",1);Kt([y.trace("MediaHandler.onDeviceChange")],Ut.prototype,"onDeviceChange",1);function yo(t,e,r){switch(!0){case Ee.isChromiumBased():switch(e){case"NotAllowedError":return r.includes("by system")?"SYSTEM_DENIED":t==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case Ee.isSafari():switch(e){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case Ee.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 TD=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function Jl(t){var e,r;const n=(e=t.label)==null?void 0:e.toLowerCase();return((r=Ee._bowser)==null?void 0:r.getOSName())==="macOS"&&n.includes("iphone")?(l.log("isVirtualDevice::ignore_macos_continuity"),!0):TD.some(i=>n==null?void 0:n.includes(i))}function kD(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 zi;class _D{constructor(){T(this,zi,void 0)}terminateMiddlewareWebWorker(){if(c(this,zi))try{Bm(c(this,zi)),S(this,zi,void 0)}catch{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:zy})));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{}return a.addEventListener("play",()=>{i.width=a.width||r.getSettings().width,i.height=a.width||r.getSettings().height,S(this,zi,jm(h,50))},!1),i.captureStream().getVideoTracks()[0]})}}zi=new WeakMap;const im={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}}},sm={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"}]},bD={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"}]},am={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 wD=j_(),xi=hr(wD.config.media);function ID(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 Ki,Gl;class CD{constructor(e,r){T(this,Ki,void 0),T(this,Gl,void 0),f(this,"getScreenShareConstraints",()=>{var n,i,s,a,o,d,h,p,m;const g=(n=c(this,Ki))==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=Z(B({},J),{displaySurface:D})),N!==void 0&&(J=Z(B({},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,Ki))==null?void 0:i.audio,I=v!=null&&v.enableStereo?2:1;return Ee.isFirefox()||Ee.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,Ki))==null?void 0:i.video;let h=im.vga;if(typeof d=="string"?h=im[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},Ee.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,Gl,e),S(this,Ki,r)}getUpdatedVideoConstraints(e){return e}}Ki=new WeakMap,Gl=new WeakMap;class rl extends Error{constructor(e,r,n){super(r),f(this,"constraints"),f(this,"name"),this.name=e,this.constraints=n}}class PD{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 RD=Object.defineProperty,AD=Object.getOwnPropertyDescriptor,vr=(t,e,r,n)=>{for(var i=n>1?void 0:n?AD(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&&RD(e,r,i),i},Qs,nr,nl,om;let qt=(om=class extends PD{constructor(t,e){super(),f(this,"availableDevices"),T(this,Qs,void 0),T(this,nr,void 0),T(this,nl,void 0),S(this,nl,t),S(this,nr,new CD(t,e)),S(this,Qs,new AbortController),this.availableDevices=[],this.getAvailableDevices()}get constraintsBuilder(){return c(this,nr)}destruct(){return u(this,null,function*(){var t;(t=c(this,Qs))==null||t.abort()})}handlePermissionErrors(t,e){const r=yo(t,e.name,e.message);return this.permissions[t]=r,w.emit(b.MEDIA_PERMISSION_ERROR,{message:r,constraints:e.constraints,kind:t}),r}getAudioAndVideoTrack(){return u(this,null,function*(){const t={audio:c(this,nr).getAudioConstraints().audio,video:c(this,nr).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 w.emit(b.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),w.emit(b.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",w.emit(b.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,nr).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=yo("audio",a.name,a.message),d=new rl(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,nr).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",w.emit(b.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",w.emit(b.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=yo("video",d.name,d.message),p=new rl(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,nr).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,nr).getVideoConstraints(t),d=yield a(o);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",w.emit(b.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=yo("video",r.name,r.message),i=new rl(r.name,r.message,e),s={video:!0};if(cw(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,nr).getScreenShareConstraints(),r=yield t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",w.emit(b.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*(){Ee.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,Qs).signal})})}},Qs=new WeakMap,nr=new WeakMap,nl=new WeakMap,om);vr([y.trace("WebMediaInterface.destruct")],qt.prototype,"destruct",1);vr([y.trace("WebMediaInterface.handlePermissionErrors")],qt.prototype,"handlePermissionErrors",1);vr([y.trace("WebMediaInterface.getAudioAndVideoTrack")],qt.prototype,"getAudioAndVideoTrack",1);vr([y.trace("WebMediaInterface.getAudioTrack")],qt.prototype,"getAudioTrack",1);vr([y.trace("WebMediaInterface.getVideoTrack")],qt.prototype,"getVideoTrack",1);vr([y.trace("WebMediaInterface.getScreenShareTracks")],qt.prototype,"getScreenShareTracks",1);vr([y.trace("WebMediaInterface.getAvailableDevices")],qt.prototype,"getAvailableDevices",1);vr([y.trace("WebMediaInterface.getAvailableDevicesByKind")],qt.prototype,"getAvailableDevicesByKind",1);vr([y.trace("WebMediaInterface.getDevice")],qt.prototype,"getDevice",1);vr([y.trace("WebMediaInterface.onDeviceChange")],qt.prototype,"onDeviceChange",1);qt=vr([yt("1600")],qt);const dv=qt,il={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}},MD=(t=0)=>new Promise(e=>setTimeout(e,t)),DD=(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):MD().then(d))}return d().then(h=>(i.disconnect(),h),h=>{throw i.disconnect(),h})},OD=typeof AudioContext!="undefined"?AudioContext:null;class xu{constructor(e){f(this,"_AudioContext"),f(this,"audioContext"),f(this,"_audioContextRefContainers");const r=B({AudioContext:OD},e);Object.defineProperties(this,{_AudioContext:{value:r.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:xu}})}getOrCreate(e){if(!this._audioContextRefContainers.has(e)&&(this._audioContextRefContainers.add(e),this._AudioContext&&!this.audioContext))try{this.audioContext=new this._AudioContext}catch{}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 cm=new xu,ND=3,LD=250;function xD(t){const e={},r=cm.getOrCreate(e);let n=ND;function i(){return n-=1,DD(r,t.srcObject,LD).then(s=>s?n>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{cm.release(e)})}function dm(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 xD(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 FD=Object.defineProperty,VD=Object.getOwnPropertyDescriptor,lv=(t,e,r,n)=>{for(var i=n>1?void 0:n?VD(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&&FD(e,r,i),i};let Nc=class extends ps{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(Ee.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))}};lv([y.trace("BaseMediaHandler.unmuteTrack")],Nc.prototype,"unmuteTrack",1);Nc=lv([yt("1600")],Nc);const uv=Nc;var UD=Object.defineProperty,BD=Object.getOwnPropertyDescriptor,Fu=(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&&UD(e,r,i),i};const sl="[Dyte]nonSilentDeviceLabels";class ud extends uv{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 kD(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(il.getItem(sl));if(a!=null&&a.devices.some(d=>d.label===n.label))return n;if(!(yield dm(n))){const d=(r=a==null?void 0:a.devices.concat({label:n.label}))!=null?r:[{label:n.label}];return il.setItem(sl,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 dm(n))){const h=a.devices.concat({label:n.label});return il.setItem(sl,JSON.stringify({devices:h})),l.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return l.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1})),n})}}Fu([y.trace("AudioMediaHandler.setTransformedTrack")],ud.prototype,"setTransformedTrack",1);Fu([y.trace("AudioMediaHandler.onTrackEnded")],ud.prototype,"onTrackEnded",1);Fu([y.trace("AudioMediaHandler.conditionallyChangeTrack")],ud.prototype,"conditionallyChangeTrack",1);const jD=ud;var va;class HD{constructor(e){T(this,va,void 0),f(this,"currentDevice"),S(this,va,e)}setupSpeaker(e){return u(this,null,function*(){var r;if(!(c(this,va)instanceof dv))return;let n=e;if(e||([n]=(yield c(this,va).getAvailableDevicesByKind("audiooutput")).filter(i=>!Jl(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{}})))})}}va=new WeakMap;const WD=HD;class $D extends ps{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",w.emit(b.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch{}})}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)),Ee.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 JD=$D;var GD=Object.defineProperty,qD=Object.getOwnPropertyDescriptor,hd=(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},ya,Ko;class Ya extends uv{constructor(e,r,n){super(e,r,n),T(this,ya,void 0),T(this,Ko,{disablePerFrameCanvasRendering:!1}),S(this,ya,new _D)}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,ya).getTransformedVideoTrack(this.middlewares,this.mediaTrack,c(this,Ko)),this.emit("trackChanged")}catch(n){l.error("VideoMediaHandler.setTransformedTrack",{error:n}),this.transformedMediaTrack=this.mediaTrack}})}setVideoMiddlewareGlobalConfig(e){return u(this,null,function*(){S(this,Ko,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,ya).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})}}ya=new WeakMap,Ko=new WeakMap;hd([y.trace("VideoMediaHandler.setTransformedTrack")],Ya.prototype,"setTransformedTrack",1);hd([y.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],Ya.prototype,"setVideoMiddlewareGlobalConfig",1);hd([y.trace("VideoMediaHandler.onTrackEnded")],Ya.prototype,"onTrackEnded",1);hd([y.trace("VideoMediaHandler.conditionallyChangeTrack")],Ya.prototype,"conditionallyChangeTrack",1);const zD=Ya,lm=hr(_u());var Wt,Yi,Yo,Sa;const Ea=class{constructor(t){if(T(this,Wt,void 0),T(this,Yi,void 0),T(this,Yo,void 0),T(this,Sa,void 0),!t)throw new _("Could not load preset.","0904");S(this,Wt,t.config),S(this,Yo,t.name),S(this,Yi,t.ui||hr(_u().ui)),S(this,Sa,t.permissions.plugins.config)}static fromResponse(t){return new Ea(t)}static default(){return new Ea(lm)}static init(t,e=!0){return!t||e?new Ea(lm):new Ea(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,Yi).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return c(this,Wt).viewType}get livestreamViewerQualities(){return c(this,Wt).livestreamViewerQualities||[]}get maxVideoStreams(){return c(this,Wt).maxVideoStreams}get maxScreenShareCount(){return c(this,Wt).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(c(this,Sa)).filter(t=>c(this,Sa)[t].disabled)}get designTokens(){return c(this,Yi).designTokens}get configDiff(){return c(this,Yi).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,oe;return{audio:{enableStereo:(n=(r=(e=(t=c(this,Wt))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?n:xi.audio.enableStereo,enableHighBitrate:(o=(a=(s=(i=c(this,Wt))==null?void 0:i.media)==null?void 0:s.audio)==null?void 0:a.enableHighBitrate)!=null?o:xi.audio.enableHighBitrate},video:{quality:(m=(p=(h=(d=c(this,Wt))==null?void 0:d.media)==null?void 0:h.video)==null?void 0:p.quality)!=null?m:xi.video.quality,frameRate:(A=(I=(v=(g=c(this,Wt))==null?void 0:g.media)==null?void 0:v.video)==null?void 0:I.frameRate)!=null?A:xi.video.frameRate},screenshare:{quality:(J=(N=(D=(P=c(this,Wt))==null?void 0:P.media)==null?void 0:D.screenshare)==null?void 0:N.quality)!=null?J:xi.screenshare.quality,frameRate:(oe=(W=(G=(C=c(this,Wt))==null?void 0:C.media)==null?void 0:G.screenshare)==null?void 0:W.frameRate)!=null?oe:xi.screenshare.frameRate}}}get name(){return c(this,Yo)}};let KD=Ea;Wt=new WeakMap,Yi=new WeakMap,Yo=new WeakMap,Sa=new WeakMap;var YD=Object.defineProperty,QD=Object.getOwnPropertyDescriptor,hv=(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&&YD(e,r,i),i},Ta;class Vu extends zt{constructor(e){super(),T(this,Ta,void 0),f(this,"state","IDLE"),f(this,"playbackUrl"),f(this,"ingestionCredentials"),f(this,"viewerCount"),S(this,Ta,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,Ta).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=ze(),{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,Ta).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 ze().stopLivestreaming()}catch(e){throw l.error("DyteLivestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new _("Error while stopping livestream","1900")}})}}Ta=new WeakMap;hv([y.trace("livestream.start")],Vu.prototype,"start",1);hv([y.trace("livestream.stop")],Vu.prototype,"stop",1);var XD=Object.defineProperty,ZD=Object.getOwnPropertyDescriptor,e1=(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},ka,_a,kn;class pv{constructor(e,r){f(this,"livestream"),T(this,ka,void 0),T(this,_a,void 0),T(this,kn,void 0),S(this,_a,e),this.livestream=new Vu(e),S(this,kn,r),this.setupEvents()}fetchInitialLivestreamingState(){return u(this,null,function*(){const e=ze(),{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,kn).on(j.startedLivestream,e=>u(this,null,function*(){this.livestream.playbackUrl=e.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{c(this,_a).permissions.canLivestream&&(yield this.fetchInitialLivestreamingState())}catch{l.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}})),c(this,kn).on(j.livestreamingInvoked,e=>u(this,null,function*(){if(e.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{c(this,_a).permissions.canLivestream&&(yield this.fetchInitialLivestreamingState())}catch{l.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}})),c(this,kn).on(j.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),c(this,kn).on(j.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),c(this,kn).on(j.roomPeerCount,e=>{this.livestream.viewerCount=e.count,this.livestream.emit("viewerCountUpdate",e.count)}),w.on(b.PEER_JOINED_INTERNAL,e=>u(this,null,function*(){var r;((r=e.flags)==null?void 0:r.hiddenParticipant)===!0&&e.recorderType==="LIVESTREAMER"&&(S(this,ka,e.id),this.livestream.setLivestreamState("LIVESTREAMING"))})),w.on(b.PEER_CLOSED,e=>{e.id===c(this,ka)&&(S(this,ka,void 0),this.livestream.setLivestreamState("IDLE"))}),w.onAsync(b.LEAVE_MEDIA_ROOM,()=>u(this,null,function*(){this.livestream.playbackUrl||(l.info("Fetching livestreaming state on leave stage"),yield this.fetchInitialLivestreamingState())})),w.on(b.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){try{yield this.fetchInitialLivestreamingState()}catch{l.error("Error: LivestreamController.fetchLivestream")}}))}}ka=new WeakMap,_a=new WeakMap,kn=new WeakMap;e1([y.trace("LivestreamController.setupEvents")],pv.prototype,"setupEvents",1);var t1=Object.defineProperty,r1=Object.getOwnPropertyDescriptor,Qa=(t,e,r,n)=>{for(var i=n>1?void 0:n?r1(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&&t1(e,r,i),i},Rt,ei,ti,ql,mv;class gs{constructor({name:e,socketHandler:r,meetingId:n}){T(this,ql),f(this,"name",""),T(this,Rt,{}),T(this,ei,""),T(this,ti,void 0),f(this,"rateLimitConfig",{maxInvocations:5,period:1}),f(this,"bulkRateLimitConfig",{maxInvocations:5,period:1}),f(this,"listeners",{}),this.name=e,S(this,ti,r),S(this,ei,n)}set(e,r,n=!0,i=!1){return u(this,null,function*(){c(this,Rt)[e]=r,n&&this.remoteSet(e,r),i&&(this.listeners[e]&&this.listeners[e].forEach(s=>s({[e]:c(this,Rt)[e]})),this.listeners["*"]&&this.listeners["*"].forEach(s=>s({[e]:c(this,Rt)[e]})))})}remoteSet(e,r){c(this,ti).storeInsertKeys(c(this,ei),this.name,[{key:e,payload:r}])}bulkSet(e){return u(this,null,function*(){e.forEach(({key:r,payload:n})=>{c(this,Rt)[r]=n}),c(this,ti).storeInsertKeys(c(this,ei),this.name,e)})}update(e,r,n=!0){return u(this,null,function*(){Ke(this,ql,mv).call(this,e,r,n)})}delete(e,r=!0,n=!1){return u(this,null,function*(){if(c(this,Rt)[e]&&delete c(this,Rt)[e],r)return c(this,ti).storeDeleteKeys(c(this,ei),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,Rt)[r]&&delete c(this,Rt)[r]}),c(this,ti).storeDeleteKeys(c(this,ei),this.name,e)})}get(e){if(c(this,Rt)[e])return c(this,Rt)[e]}getAll(){return c(this,Rt)}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,Rt,e)}}Rt=new WeakMap,ei=new WeakMap,ti=new WeakMap,ql=new WeakSet,mv=function(t,e,r=!0){let n;const i=c(this,Rt)[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=B(B({},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)};Qa([Vt(fs,"rateLimitConfig")],gs.prototype,"remoteSet",1);Qa([Vt(fs,"bulkRateLimitConfig")],gs.prototype,"bulkSet",1);Qa([Vt(fs,"rateLimitConfig")],gs.prototype,"update",1);Qa([Vt(fs,"rateLimitConfig")],gs.prototype,"delete",1);Qa([Vt(fs,"bulkRateLimitConfig")],gs.prototype,"bulkDelete",1);var es,ts,Qo,al,Lc,li,zl,fv;class n1{constructor(e,r){T(this,Qo),T(this,zl),f(this,"stores",new Map),T(this,es,void 0),T(this,ts,""),T(this,Lc,void 0),T(this,li,new Map),S(this,es,r),S(this,ts,e.getValue("meetingId")),S(this,Lc,e),Ke(this,zl,fv).call(this)}create(e){const r=new gs({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,li).set(e,{rejectTimeout:s,resolve:n,store:r})})}}es=new WeakMap,ts=new WeakMap,Qo=new WeakSet,al=function(){return c(this,Lc).getValue("peerId")},Lc=new WeakMap,li=new WeakMap,zl=new WeakSet,fv=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,li).get(e.storeName),o=this.stores.get(e.storeName)||(a==null?void 0:a.store);c(this,li).get(e.storeName)&&(this.stores.set(e.storeName,a.store),a.resolve(o),clearTimeout(a.rejectTimeout),c(this,li).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,li).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,Qo,al)&&t!==z.storeGetKeys||s.set(a,d,!1,!0)}),t===z.storeDeleteKeys&&i.forEach(({key:a,peerId:o})=>{o!==c(this,Qo,al)&&s.delete(a,!1,!0)}))}))})};function ui(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 i1=Object.defineProperty,s1=Object.getOwnPropertyDescriptor,vs=(t,e,r,n)=>{for(var i=n>1?void 0:n?s1(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 a1=.8,o1=1.2;var Xs,Zs,jn,Fi,ea,nn,So,Hn,ta,Eo,sn,ol,To,cl,um;let Xr=(um=class extends zt{constructor(t,e,r,n){super(),T(this,Fi),T(this,ta),T(this,To),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,Xs,void 0),f(this,"supportsRemoteControl",!1),T(this,Zs,void 0),f(this,"presetName"),T(this,jn,void 0),T(this,nn,void 0),T(this,So,void 0),T(this,Hn,new Map),T(this,sn,1),T(this,ol,Yr(C=>{if(!this.videoTrack)return;const{clientWidth:G,clientHeight:W}=C,{width:oe,height:se}=this.videoTrack.getSettings();if(!oe||!se)return;const Oe=se/W,Et=oe/G,O=Math.max(Oe,Et);O>o1&&c(this,sn)===1?(S(this,sn,0),w.emit(b.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:c(this,sn)})):O<a1&&c(this,sn)===0&&(S(this,sn,1),w.emit(b.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:c(this,sn)}))},2e3)),S(this,jn,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=yw,S(this,Zs,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,Xs,!1),S(this,nn,r),S(this,So,n),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),Ke(this,To,cl).call(this)}get clientSpecificId(){return this.customParticipantId}get stageStatus(){return c(this,Zs)}get mediaJoined(){return c(this,jn).getValue("connectionHandler").mediaJoined}get socketJoined(){return c(this,jn).getValue("connectionHandler").socketJoined}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(l.info("DyteParticipant::setVideoEnabled::videoUpdate",B({},ui(this))),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(l.info("DyteParticipant::setAudioEnabled::audioUpdate",B({},ui(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",Ke(this,To,cl))}pin(){return u(this,null,function*(){if(!this.mediaJoined)throw new _("Can`t pin participant without joining room","1205");if(!c(this,nn).permissions.pinParticipant)throw new _("You do not have permission to pin participants.","1201");return c(this,Fi,ea).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,nn).permissions.pinParticipant)throw new _("You do not have permission to unpin participants.","1201");return c(this,Fi,ea).pinPeer(null)})}setIsPinned(t,e=!0){var r;S(this,Xs,t);const n=t?"pinned":"unpinned";(r=c(this,ta,Eo))==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,nn).permissions.canDisableParticipantAudio)return c(this,Fi,ea).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,nn).permissions.kickParticipant){yield w.emitAsync(b.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,nn).permissions.canDisableParticipantVideo)return c(this,Fi,ea).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,So).getUserPermissions(this.userId)})}setStageStatus(t){S(this,Zs,t),this.emit("stageStatusUpdate",this)}get isPinned(){return c(this,Xs)}registerVideoElement(t){var e,r,n,i;let s;(r=(e=c(this,Hn).get(t))==null?void 0:e.observer)==null||r.disconnect(),"ResizeObserver"in window&&(s=new ResizeObserver(()=>c(this,ol).call(this,t)),s.observe(t)),c(this,Hn).set(t,{observer:s}),this.updateVideo(t),(i=c(this,ta,Eo))==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,Hn).get(t))==null?void 0:e.observer)==null||r.disconnect(),c(this,Hn).delete(t),(n=c(this,ta,Eo))==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"}},Xs=new WeakMap,Zs=new WeakMap,jn=new WeakMap,Fi=new WeakSet,ea=function(){return c(this,jn).getValue("roomNodeClient")},nn=new WeakMap,So=new WeakMap,Hn=new WeakMap,ta=new WeakSet,Eo=function(){return c(this,jn).getValue("pip")},sn=new WeakMap,ol=new WeakMap,To=new WeakSet,cl=function(){Array.from(c(this,Hn).keys()).forEach(this.updateVideo)},um);vs([y.trace("DyteParticipant.disableAudio")],Xr.prototype,"disableAudio",1);vs([y.trace("DyteParticipant.kick")],Xr.prototype,"kick",1);vs([y.trace("DyteParticipant.disableVideo")],Xr.prototype,"disableVideo",1);vs([y.trace("DyteParticipant.getPermissions")],Xr.prototype,"getPermissions",1);vs([y.trace("DyteParticipant.setStageStatus")],Xr.prototype,"setStageStatus",1);Xr=vs([yt("1200")],Xr);class ra extends av{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 ri;class c1 extends ps{constructor(){super(),T(this,ri,void 0),S(this,ri,new Map)}__set(e,r){return c(this,ri).set(e,r)}__clear(){return c(this,ri).clear()}get(e){return c(this,ri).get(e)}toArray(){return Array.from(c(this,ri).values())}}ri=new WeakMap;var mi={},pd={},xc={},d1={get exports(){return xc},set exports(t){xc=t}},dl,hm;function l1(){if(hm)return dl;hm=1;var t=1e3,e=t*60,r=e*60,n=r*24,i=n*7,s=n*365.25;dl=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 dl}function u1(t){r.debug=r,r.default=r,r.coerce=d,r.disable=s,r.enable=i,r.enabled=a,r.humanize=l1(),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 oe=r.formatters[W];if(typeof oe=="function"){const se=P[C];G=oe.call(D,se),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 h1=u1;(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{}}function s(){let d;try{d=e.storage.getItem("debug")}catch{}return!d&&typeof process!="undefined"&&"env"in process&&(d={}.DEBUG),d}function a(){try{return localStorage}catch{}}t.exports=h1(e);const{formatters:o}=t.exports;o.j=function(d){try{return JSON.stringify(d)}catch(h){return"[UnexpectedJSONParseError]: "+h.message}}})(d1,xc);var p1=ch&&ch.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(pd,"__esModule",{value:!0});pd.Logger=void 0;const Vi=p1(xc),Ui="awaitqueue";class m1{constructor(e){e?(this._debug=(0,Vi.default)(`${Ui}:${e}`),this._warn=(0,Vi.default)(`${Ui}:WARN:${e}`),this._error=(0,Vi.default)(`${Ui}:ERROR:${e}`)):(this._debug=(0,Vi.default)(Ui),this._warn=(0,Vi.default)(`${Ui}:WARN`),this._error=(0,Vi.default)(`${Ui}: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}}pd.Logger=m1;Object.defineProperty(mi,"__esModule",{value:!0});var us=mi.AwaitQueue=mi.AwaitQueueRemovedTaskError=mi.AwaitQueueStoppedError=void 0;const f1=pd,an=new f1.Logger;class Uu extends Error{constructor(e){super(e!=null?e:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Uu)}}mi.AwaitQueueStoppedError=Uu;class md extends Error{constructor(e){super(e!=null?e:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,md)}}mi.AwaitQueueRemovedTaskError=md;class g1{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,an.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{}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),an.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),an.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(){an.debug("stop()"),this.stopping=!0;for(const e of this.pendingTasks.values())an.debug(`stop() | stopping task [name:${e.name}]`);this.stopping=!1}remove(e){an.debug(`remove() [taskIdx:${e}]`);const r=Array.from(this.pendingTasks.values())[e];if(!r){an.debug(`stop() | no task with given idx [taskIdx:${e}]`);return}r.reject(new md)}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(an.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)}})}}us=mi.AwaitQueue=g1;var Xo;class gv{constructor(){f(this,"meetingTitle"),f(this,"roomName"),f(this,"roomUUID"),T(this,Xo,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,Xo)}get mediaState(){return c(this,Xo).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.")})}}Xo=new WeakMap;var zr=(t=>(t.INITIALIZING="INITIALIZING",t.INITIALIZED="INITIALIZED",t.NOT_INITIALIZED="NOT_INITIALIZED",t))(zr||{});class vv extends mt.EventEmitter{}class yi extends mt.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 v1(t,e){const r=new Error(e);return r.name=t,r}class Si extends _{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Si):this.stack=new Error(e).stack}}class nt extends _{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,nt):this.stack=new Error(e).stack}}class yv extends _{constructor(e){super(e),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,nt):this.stack=new Error(e).stack}}class Sv extends _{constructor(e){super(e),this.name="DataChannelRequestError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,nt):this.stack=new Error(e).stack}}var Zo,ec,tc,rc,Vr,nc,ic,Er,Qi,sc,ac,oc,ll,Kl,Ev,Yl,Tv;class kv extends yi{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,oc),T(this,Kl),T(this,Yl),f(this,"rtpReceiver"),f(this,"observer"),T(this,Zo,void 0),T(this,ec,void 0),T(this,tc,void 0),T(this,rc,void 0),T(this,Vr,void 0),T(this,nc,void 0),T(this,ic,void 0),T(this,Er,void 0),T(this,Qi,void 0),T(this,sc,void 0),T(this,ac,void 0),S(this,Zo,e),S(this,ec,r),S(this,ic,a),S(this,ac,d),S(this,sc,i),S(this,rc,s),S(this,Vr,!1),S(this,tc,n),S(this,Er,o),S(this,Qi,h!=null?h:!1),S(this,nc,p),this.observer=new yi,this.rtpReceiver=m,Ke(this,Kl,Ev).call(this)}get id(){return c(this,Zo)}get peerId(){return c(this,sc)}get localId(){return c(this,ec)}get producerId(){return c(this,tc)}get producingTransportId(){return c(this,rc)}get closed(){return c(this,Vr)}get kind(){return c(this,Er).kind}get track(){return c(this,Er)}get paused(){return c(this,Qi)}get remotelyPaused(){return this.paused}get appData(){return c(this,ac)}close(e){c(this,Vr)||(l.debug("Consumer::close() with reason:",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,closureReason:e,kind:this.kind}}),S(this,Vr,!0),c(this,nc)||Ke(this,Yl,Tv).call(this),this.emit("close",e),this.observer.safeEmit("close",e))}getStats(){return u(this,null,function*(){if(c(this,Vr))throw new nt("closed");return c(this,ic).getReceiverStats(this.localId)})}pause(){if(l.debug("consumer::pause()",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}),c(this,Vr)){l.error("consumer::pause() | Consumer closed",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}});return}S(this,Qi,!0),c(this,Er).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,Vr)){l.error("Consumer::resume() | Consumer closed",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}});return}S(this,Qi,!1),c(this,Er).enabled=!0,this.observer.safeEmit("resume")}}Zo=new WeakMap,ec=new WeakMap,tc=new WeakMap,rc=new WeakMap,Vr=new WeakMap,nc=new WeakMap,ic=new WeakMap,Er=new WeakMap,Qi=new WeakMap,sc=new WeakMap,ac=new WeakMap,oc=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")},Kl=new WeakSet,Ev=function(){c(this,Er).addEventListener("ended",Ke(this,oc,ll).bind(this))},Yl=new WeakSet,Tv=function(){try{c(this,Er).removeEventListener("ended",Ke(this,oc,ll)),c(this,Er).stop()}catch(t){l.error("Consumer::destroyTrack()",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind},error:t})}};let y1=class extends kv{};const pm=t=>new Promise(e=>setTimeout(e,t));function _r(t,e){return u(this,null,function*(){return new Promise((r,n)=>u(this,null,function*(){const{strategy:i,maxRetryCount:s,delayTime:a}=B({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 pm(a*(o+1)):i==="exponential"&&(yield pm(a*(o+Math.max(0,o-1))));else break}o+=1}return n(d)}))})}function Fc(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 S1(t,e){return typeof t=="undefined"?e:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(t):JSON.parse(JSON.stringify(t))}function _v(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function Ql(t){return Math.random().toString(36).substring(2,2+t)}const ko=1;function mm(t){const e=t;return delete e.payload._bolt,e}function E1(t){return t.payload&&_v(t.payload)}function Vc(t){var e,r;return E1(t)&&(r=(e=t.payload._bolt)==null?void 0:e.id)!=null?r:""}var ni;const ba=class extends mt.EventEmitter{constructor(t,e,r){super(),f(this,"channel"),f(this,"queue"),f(this,"serverProtocolVersion"),T(this,ni,new Map),f(this,"respond",(n,i,s=!1)=>{let a;s?a=ba.createErrorResponse(n,i):a=ba.createResponse(n,i),this.channel.send(JSON.stringify(a))}),f(this,"notify",n=>{const i=ba.createNotification(n);this.channel.send(JSON.stringify(i))}),f(this,"request",n=>u(this,null,function*(){const i=ba.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=Ei();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,ni).has(n.id)||c(this,ni).set(n.id,[]);const s=c(this,ni).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,ni).get(n.id),o=a==null?void 0:a.reduce((h,p)=>h+p.chunk,"");c(this,ni).delete(n.id);const d=JSON.parse(o);if(!d.payload||!_v(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(mm(n)):s.resolve(mm(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:Ql(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1}),this.label=e,this.transportId=r,this.channel=t,this.queue=new Map}};let wa=ba;ni=new WeakMap,f(wa,"createRequest",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:Z(B({},t.payload),{_bolt:{id:Ql(8),type:"REQUEST",version:ko}})}}),f(wa,"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:Z(B({},e.payload),{_bolt:{id:t,type:"RESPONSE",version:ko}})}}),f(wa,"createNotification",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:Z(B({},t.payload),{bolt:{id:Ql(8),type:"NOTIFY",version:ko}})}}),f(wa,"createErrorResponse",(t,e)=>({type:"error",payload:{error:e.message,_bolt:{id:t,type:"RESPONSE",version:ko}}}));const Xl="transport closed";class bv extends yi{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=S1(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 us,this.observer=new yi,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 wa(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(Xl).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(Xl)}),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 nt("closed");return this.handler.getTransportStats()})}restartIce(){return u(this,null,function*(){if(l.debug("restartIce()"),this.closed)throw new nt("closed");return this.handler.restartIce()})}updateIceServers(){return u(this,arguments,function*({iceServers:e}={}){if(l.debug("updateIceServers()"),this.closed)throw new nt("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=cu(r.sdp);return n.media=n.media.map(i=>{if(i.type==="audio"){const s=B({},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=tS(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 v1("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 wv extends yi{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 yi,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===Xl){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 nt("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 nt("closed")}else if(r&&r.readyState==="ended")throw new nt("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 nt("closed");if(this._kind!=="video")throw new Si("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 nt("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 T1=class extends wv{},k1=class extends bv{consume(t){return u(this,null,function*(){if(l.debug(`consume() producers: ${JSON.stringify(t)}`),this.closed)throw new nt("closed");if(this.direction!=="recv")throw new Si("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 yv("transport not connected");let e;try{e=yield this.createConsumersOverDataChannel(t)}catch(n){throw new Sv(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}))}),Fc(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 y1({id:e,localId:C.mid,track:G,paused:o,producerId:r,producingPeerId:n,producingTransportId:i,handler:this.handler,appData:Z(B({},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 Fc(t.map(e=>u(this,null,function*(){return _r(r=>u(this,null,function*(){return r>0&&l.warn(`retrying failed consumer creation task: ${JSON.stringify(e)}`),this.consumerCreationTask(B({},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 Si("not a sending Transport");if(t.readyState==="ended")throw new nt("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:Z(B({},a||{}),{mid:I})}),D=yield g(A);return{producerId:P,localId:D,rtpSender:v}}),"producer"),p=new T1({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 Bu extends yi{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 ju extends Bu{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 ju}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(B({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]=B(B({},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 Uc extends Bu{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 Uc(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(B({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,B({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]=B(B({},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 Hu extends Bu{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 Hu}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(B({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]=B(B({},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 _1(){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=Mm.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 Iv{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=_1(),e)l.debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=ju.createFactory();break;case"Safari12":this.handlerFactory=Hu.createFactory();break;case"Firefox60":this.handlerFactory=Uc.createFactory({supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=Uc.createFactory({supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}const n=this.handlerFactory();this._handlerName=n.name,n.close(),this._observer=new mt}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 b1=class extends Iv{createTransport({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s,config:a}){const o=Ei(),d=new k1({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 Ct;class w1{constructor(e){T(this,Ct,void 0),S(this,Ct,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,Ct).sendMessagePromiseWithTimeout({event:ce.joinRoom,protobuf:kg.toBinary(s),timeout:5e3})).payload})}connectTransport(e){return u(this,null,function*(){const r=(yield c(this,Ct).sendMessagePromise(ce.createWebRTCTransport,yg.toBinary(e))).payload,{transportId:n,description:i}=wu.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,Ct).sendMessagePromise(ce.produce,wg.toBinary(e))).payload,s=xg.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,Ct).sendMessagePromise(ce.consume,Iu.toBinary(e))).payload,{consumerIdsMap:{map:n}}=Lg.fromBinary(r);return n})}closeProducer(e){return u(this,null,function*(){const r=(yield c(this,Ct).sendMessagePromise(ce.closeProducer,Cg.toBinary(e))).payload,{description:n}=Fg.fromBinary(r);return n})}closeConsumer(e){return u(this,null,function*(){return(yield c(this,Ct).sendMessagePromise(ce.closeConsumer,Pg.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,Ct).sendMessagePromise(ce.hostControlPeer,Mg.toBinary(n))).payload;if(!i)return!1;const{status:s}=Bg.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,Ct).sendMessagePromise(ce.hostControlAllPeers,Dg.toBinary(r))).payload;if(!n)return!1;const{status:i}=jg.fromBinary(n);return i==="success"})}kickAll(){return u(this,null,function*(){const e={propagateKickAcrossRooms:!1},r=(yield c(this,Ct).sendMessagePromise(ce.kickAll,Cu.toBinary(e))).payload;if(!r)return!1;const{status:n}=Ug.fromBinary(r);return n==="success"})}kickPeer(e){return u(this,null,function*(){const r=(yield c(this,Ct).sendMessagePromise(ce.kickPeer,Rg.toBinary(e))).payload;if(!r)return!1;const{status:n}=Vg.fromBinary(r);return n==="success"})}changeDisplayName(e){return u(this,null,function*(){const r=(yield c(this,Ct).sendMessagePromise(ce.changeDisplayName,Ag.toBinary(e))).payload;if(!r)return!1;const{status:n}=Hg.fromBinary(r);return n==="success"})}notifySelfJoinComplete(){return u(this,null,function*(){const e={},r=(yield c(this,Ct).sendMessagePromise(ce.selfJoinComplete,_g.toBinary(e))).payload;return Ac.fromBinary(r)})}}Ct=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||{}),hs=(t=>(t[t.HIVE=1]="HIVE",t[t.ROOM_NODE=2]="ROOM_NODE",t[t.CF=3]="CF",t))(hs||{});const I1=2e3;var Xi,Ia,Br;class C1 extends vv{constructor(e,r){super(),T(this,Xi),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,Br,void 0),S(this,Br,e),this._device=new b1({}),this._socket=r,c(this,Xi,Ia).mediaState={recv:{state:er.NEW,reconnected:!1},send:{state:er.NEW,reconnected:!1}},this.transportDisconnected={recv:!1,send:!1},this._socketHandler=new w1(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 ze().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,Br).getValue("modules").e2ee)==null?void 0:r.enabled},config:{enableHighBitrate:(s=(i=(n=c(this,Br).getValue("defaults").mediaConfiguration)==null?void 0:n.audio)==null?void 0:i.enableHighBitrate)!=null?s:!1,enableStereo:(d=(o=(a=c(this,Br).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,Br).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 _r((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(Z(B({},e),{additionalSettings:Z(B({},(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 _r((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?Gt.SUBSCRIBER:Gt.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)},I1);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,Vc(a),s,e)}));break}case"handshake":{const h={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(s,Vc(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{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=cu(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:Gt.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{}I.set(A,{consumerId:P.consumerId,trackId:(D=P.producerTrack)==null?void 0:D.trackId,streamId:P.producerTrack.streamId,kind:P.producerState.kind===xt.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 oe={};try{oe=JSON.parse((g=W.producerState)==null?void 0:g.appData)}catch{}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:Z(B({},oe),{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===xt.VIDEO?"video":"audio",paused:(C=W.producerState)==null?void 0:C.pause,appData:oe})}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)===zr.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:zr.INITIALIZING});try{const a=yield this._sendTransport.produce(r);return(i=r.appData)!=null&&i.e2ee&&w.emit(b.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:Gt.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:zr.INITIALIZED}),this.reconfigureWebcamLayers(),a.track}catch(a){throw this._producerStatus.set(e,{status:zr.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),w.emit(b.CONSUMER_CLOSED,{id:e.id})})),this._consumers.set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),w.emit(b.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 Sv){if(this._metrics.consumerCreationFailureCount+=1,s<=r)return n(i,s+1);throw a}throw a instanceof yv&&(this._metrics.recvTransportFailureCount+=1),l.error("Error in consume request",a),a}});try{let i=yield n(e);yield _r(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&&w.emit(b.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,Br).getValue("modules").e2ee.enabled&&w.emit(b.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,Rc.toBinary(r)),e.pause(),w.emit(b.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,Rc.toBinary(n)),r.resume(),w.emit(b.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:Gt.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,Sg.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(),w.emit(b.CONSUMER_PAUSED,{id:i.id})):(i.resume(),w.emit(b.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,Xi,Ia).mediaState[n]={state:r,reconnected:r==="connected"?this.transportDisconnected[n]:c(this,Xi,Ia).mediaState[n].reconnected},r==="connected"&&(this.transportDisconnected[n]=!1),w.emit(b.TRANSPORT_STATE_UPDATE,B({transport:n},c(this,Xi,Ia).mediaState[n]))}}Xi=new WeakSet,Ia=function(){return c(this,Br).getValue("connectionHandler")},Br=new WeakMap;var P1=Object.defineProperty,R1=Object.getOwnPropertyDescriptor,me=(t,e,r,n)=>{for(var i=n>1?void 0:n?R1(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&&P1(e,r,i),i},kt,fe,Pr,Bi,Wn,$n,_o,bo,wo,on,na,Rr,cn,fm;const Cv=(fm=class extends gv{constructor(t,e){var r,n;super(),T(this,Rr),T(this,kt,void 0),T(this,fe,void 0),T(this,Pr,void 0),T(this,Bi,void 0),T(this,Wn,void 0),T(this,$n,void 0),T(this,_o,void 0),T(this,bo,void 0),T(this,wo,void 0),T(this,on,void 0),T(this,na,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,kt,o),S(this,Pr,!1),S(this,fe,new C1(t,o)),this.maxPreferredStreams=6,S(this,on,new Set),S(this,Bi,!1),S(this,Wn,0),S(this,$n,new us),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,_o,Yr(()=>u(this,null,function*(){if(!c(this,Rr,cn).mediaJoinAttempted)return;const{roomJoined:h}=yield this.joinRoom(this.peerDisplayName,this.roomUUID,{},!0,!0);h&&(w.emit(b.RESET_PRODUCER_STATE),w.emit(b.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3})),S(this,bo,Yr(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports({send:!0}),l.info("send transport reconected!"),w.emit(b.RESET_PRODUCER_STATE)}),1e3)),S(this,wo,Yr(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports({recv:!0}),l.info("recv transport reconnected!"),w.emit(b.UPDATE_ACTIVE,{createAllConsumers:!0})}),1e3))}get mediaState(){return c(this,Rr,cn).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 Cv(t,{legacyMode:r,authToken:i,socketClient:a,roomName:n,meetingTitle:s})})}get sfuHandler(){return c(this,fe)}get rejoinRoom(){return c(this,_o)}get mediaJoined(){return c(this,Rr,cn).mediaJoined}set mediaJoined(t){c(this,Rr,cn).mediaJoined=t}reset(t=!0){var e,r,n,i;(r=(e=c(this,fe))==null?void 0:e.cleanupConsumers)==null||r.call(e),(i=(n=c(this,fe))==null?void 0:n.stopAllProducers)==null||i.call(n),c(this,on).clear(),t&&(this.partialJoinRoomPromise=void 0,c(this,$n).stop(),c(this,fe).stopAllTransports(),c(this,fe).reset(),S(this,$n,new us))}reconnectTransport(t){return u(this,null,function*(){l.info(`HiveNodeClient::Room joining state: ${c(this,Pr)}`),!(!t||c(this,Pr))&&(t.direction==="send"?yield c(this,bo).call(this,t):yield c(this,wo).call(this,t))})}setupTransports(){return u(this,null,function*(){yield c(this,fe).setupTransports({send:!0,recv:!0})})}stopAllProducers(){return u(this,null,function*(){yield c(this,fe).stopAllProducers()})}joinRoom(t,e){return u(this,arguments,function*(r,n,i={},s=!1,a=!1){c(this,Rr,cn).mediaJoinAttempted=!0,S(this,Pr,!0),this.reset(s);const o=ze().ipInfo;if(o!=null&&o.loc&&!c(this,na)){const h=o.loc.split(",");S(this,na,{latitude:parseFloat(h[0]),longitude:parseFloat(h[1])})}let d;try{return d=yield c(this,$n).push(()=>this._joinRoom(r,n,i,a,c(this,na)),"joinRoom"),d}catch{d={roomJoined:!1}}return d.roomJoined||w.emit(b.ROOM_NODE_FAILED),d})}_partialJoinRoom(t,e,r=!1,n=void 0){return u(this,null,function*(){const{ipInfo:i}=ze();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 _r((a,o)=>u(this,null,function*(){if(!c(this,kt).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,$n).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:Z(B({},Ee.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,Bi,!0),S(this,Pr,!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,fe).stopAllTransports(),S(this,Bi,!1),c(this,Rr,cn).mediaJoinAttempted=!1;const t={closeRoom:!1};c(this,kt).sendMessagePromise(ce.leaveRoom,bg.toBinary(t)).then(e=>{var r;(r=Ng.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,fe).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,fe).producers.has(ne.WEBCAM)){const i=c(this,fe).producers.get(ne.WEBCAM);if(!i.closed&&!navigator.isReactNative)return yield i.replaceTrack({track:t}),yield this.resumeWebcam(),t;yield c(this,fe).removeProducer(ne.WEBCAM)}const r={track:t,codecOptions:{name:"VP8"},appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1};if(!Pc(this.context,"disableSimulcast")&&Q.hasFeature(ie.ENABLE_HIVE_SIMULCAST)){let i=t.getConstraints().width;i in sm||(i=320),r.encodings=sm[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,fe).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:Ee.isElectron()},stopTracks:!1};let i=()=>{l.info("Disabling screenShare due to the producer closure"),this.disableScreenShare()};if(yield c(this,fe).createProducer(ne.SCREENSHARE_VIDEO,n,i),r){const s={track:r,codecOptions:{name:"opus"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ee.isElectron()},stopTracks:!1,zeroRtpOnPause:!0};i=()=>{},yield c(this,fe).createProducer(ne.SCREENSHARE_AUDIO,s,i)}$.screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new nt("track undefined");if(c(this,fe).producers.has(ne.MIC)){const n=c(this,fe).producers.get(ne.MIC);if(!n.closed&&!navigator.isReactNative){yield n.replaceTrack({track:t}),yield this.resumeMic();return}yield c(this,fe).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,fe).createProducer(ne.MIC,e,r)}catch(e){throw new _(e)}})}pauseMic(){const t=c(this,fe).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,kt).sendMessage(ce.toggleProducer,Cn.toBinary(e))}pauseWebcam(){return u(this,null,function*(){const t=c(this,fe).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,kt).sendMessage(ce.toggleProducer,Cn.toBinary(e))})}resumeMic(){return u(this,null,function*(){const t=c(this,fe).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&&w.emit(b.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,kt).sendMessage(ce.toggleProducer,Cn.toBinary(e))})}resumeWebcam(){return u(this,null,function*(){const t=c(this,fe).producers.get(ne.WEBCAM);if(!t){l.error("resumeWebcam::could_not_find_webcam_producer");return}t.resume(),t.appData.e2ee&&w.emit(b.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,kt).sendMessage(ce.toggleProducer,Cn.toBinary(e))})}disableWebcam(){return u(this,null,function*(){yield c(this,fe).removeProducer(ne.WEBCAM)})}disableMic(){return u(this,null,function*(){yield c(this,fe).removeProducer(ne.MIC)})}disableScreenShare(){return u(this,null,function*(){l.info("screen_sharing_stopped"),$.screenShareStop(),yield c(this,fe).removeProducer(ne.SCREENSHARE_VIDEO),yield c(this,fe).removeProducer(ne.SCREENSHARE_AUDIO),c(this,on).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,fe).removeProducer(ne.WEBCAM,!1),this.shareWebcam(t)),e&&(yield c(this,fe).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,kt).sendMessagePromise(ce.globalPinPeer,Ig.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,on).add(t.consumerPeerId),c(this,on).size}switchConsumersToLayer(t,e){return u(this,null,function*(){this.sfuHandler.switchConsumersToLayer(t,e)})}handleSocketEvents(){return u(this,null,function*(){c(this,kt).on(ce.peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:r}=Wg.fromBinary(t);if(e===this.peerId)return;l.info(`producer created broadcast: ${e}, producer state: ${r}`),w.emit(b.NEW_PRODUCER,{peerId:e,producer:Z(B({},r),{kind:r.kind===xt.AUDIO?"audio":"video",producingPeerId:e})})}catch(e){l.error("error in peer-producer-create-broadcast",{error:e})}}),c(this,kt).on(ce.peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:r,producerState:{kind:n,pause:i,producerId:s}}=Ol.fromBinary(t),a=n===xt.AUDIO?"audio":"video";if(l.info(`producer toggle broadcast: ${e}, producerId: ${s}, kind:${a}, paused:${i}, payload: ${JSON.stringify(Ol.fromBinary(t))}`),e===this.peerId&&r!==this.peerId&&i&&w.emit(a==="audio"?b.MUTE_SELF:b.MUTE_SELF_VIDEO),e===this.peerId)return;w.emit(b.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(),w.emit(b.CONSUMER_PAUSED,{id:o.id})):(o.resume(),w.emit(b.CONSUMER_RESUMED,{id:o.id})))})}catch(e){l.error("error in producer toggle broadcast handler",{error:e})}}),c(this,kt).on(ce.peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=Mc.fromBinary(t);if(e===this.peerId)return;l.info(`peer left broadcast:${e}`),c(this,on).delete(e),this.sfuHandler.cleanupConsumers(e),w.emit(b.PEER_CLOSED,{id:e})}catch(e){l.error("error in peer left broadcast",{error:e})}}),c(this,kt).on(ce.peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=$g.fromBinary(t);if(e===this.peerId)return;l.info(`producer closed broadcast:${e}`),w.emit(b.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),w.emit(b.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,kt).on(ce.mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!c(this,Pr)&&!c(this,Bi)||(l.warn("media hub termination broadcast received, rejoining room"),w.emit(b.ROOM_NODE_DISCONNECTED),this.rejoinRoom())})})}handleSFUEvents(){c(this,fe).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,fe).on("rejoin",t=>{var e;if(((e=c(this,Rr,cn).socketState)==null?void 0:e.state)!=="connected"){l.warn("Ignoring rejoin attempt because socket is not connected");return}if(c(this,Wn)>3&&!t){l.warn("cannot rejoin more already rejoined 3 times");return}if(c(this,Pr)&&!t){l.warn("room joining in progress, cannot start rejoining");return}S(this,Wn,c(this,Wn)+1),l.warn(`rejoining the room because transports are failing. [rejoinCount: ${c(this,Wn)}]`),this.mediaJoined=!1,w.emit(b.ROOM_NODE_DISCONNECTED),this.rejoinRoom()})}handleCallstatsEvents(){$.onConsumerScore(t=>{t.forEach((e,r)=>{const n=this.sfuHandler.consumers.get(r);n&&w.emit(b.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&&w.emit(b.PRODUCER_SCORE_UPDATE,{id:r,kind:n.kind,appData:n.appData,score:e.score,scoreStats:e})})})}},kt=new WeakMap,fe=new WeakMap,Pr=new WeakMap,Bi=new WeakMap,Wn=new WeakMap,$n=new WeakMap,_o=new WeakMap,bo=new WeakMap,wo=new WeakMap,on=new WeakMap,na=new WeakMap,Rr=new WeakSet,cn=function(){return this.context.getValue("connectionHandler")},fm);let le=Cv;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 A1{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 M1{constructor(){f(this,"_activeSpeakerPeers"),f(this,"_compulsoryPeers"),this._activeSpeakerPeers=new A1,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 Pv=new M1;var D1=Object.defineProperty,O1=Object.getOwnPropertyDescriptor,Yt=(t,e,r,n)=>{for(var i=n>1?void 0:n?O1(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&&D1(e,r,i),i};const N1=["ACTIVE_GRID","PAGINATED","MANUAL"];var Ar,Mr,dn,ji,jt,gm;let Mt=(gm=class extends zt{constructor(t,e,r){super(),T(this,Mr),f(this,"waitlisted"),f(this,"joined"),f(this,"active"),f(this,"videoSubscribed"),f(this,"audioSubscribed"),f(this,"pinned"),f(this,"all"),T(this,Ar,void 0),T(this,ji,void 0),T(this,jt,void 0),f(this,"rateLimitConfig",{maxInvocations:5,period:1}),f(this,"viewMode"),f(this,"currentPage"),f(this,"lastActiveSpeaker"),f(this,"selectedPeers",Pv),S(this,Ar,t),S(this,ji,e),S(this,jt,r),this.waitlisted=new ra,this.joined=new ra,this.videoSubscribed=new ra,this.audioSubscribed=new ra,this.active=this.videoSubscribed,this.pinned=new ra,this.all=new c1,this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return c(this,Ar).getValue("pip")}get socketJoined(){var t;return((t=c(this,Ar).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0}get mediaJoined(){var t;return((t=c(this,Ar).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(){w.on(b.E2EE_ACTIVE_CONSUMER,({peerId:t})=>{var e;((e=c(this,Ar).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,Mr,dn).maxPreferredStreams}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new _("0 <= Max active participants count limit <= 24","1203");c(this,Mr,dn).maxPreferredStreams=t,this.mediaJoined&&w.emit(b.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,jt).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,jt).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,jt).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=>N1.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,Mr,dn)instanceof le))throw new _("Manual Subscription is not enabled for your Organization. Please contact support.","1208");this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,w.emit(b.UPDATE_ACTIVE,{page:this.currentPage})):t==="ACTIVE_GRID"&&(this.currentPage=0,w.emit(b.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=Z(B({},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=Z(B({},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=Z(B({},s.manualProducerConfig),{screenshareAudio:!0});const a=s.producers.find(o=>o.kind==="audio"&&o.screenShare);n.push(a)}if(r.includes("screenshareVideo")){s.manualProducerConfig=Z(B({},s.manualProducerConfig),{screenshareVideo:!0});const a=s.producers.find(o=>o.kind==="video"&&o.screenShare);n.push(a)}}}),yield c(this,Mr,dn).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=Z(B({},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=Z(B({},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=Z(B({},s.manualProducerConfig),{screenshareAudio:!1});const a=s.producers.find(o=>o.kind==="audio"&&o.screenShare);n.push(a)}if(r.includes("screenshareVideo")){s.manualProducerConfig=Z(B({},s.manualProducerConfig),{screenshareVideo:!1});const a=s.producers.find(o=>o.kind==="video"&&o.screenShare);n.push(a)}}}),yield c(this,Mr,dn).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,w.emit(b.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,ji).permissions.canAllowParticipantAudio)return c(this,Mr,dn).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,ji).permissions.canAllowParticipantVideo)return c(this,Mr,dn).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 w.emitAsync(b.KICK_PEER,{peerId:t})})}kickAll(){return u(this,null,function*(){if(l.info("DyteParticipants::kick_all"),c(this,Ar).getValue("viewType")!=="LIVESTREAM"&&!this.socketJoined)throw new _("Can`t kick all without joining room","1205");if(!c(this,ji).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,jt).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,jt).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,jt).broadcastToPeers(t,n,e)}else yield c(this,jt).broadcastMessage(t,e)})}getAllJoinedPeers(t,e,r){return u(this,null,function*(){return(yield c(this,jt).getRoomPeers(t,e,r)).peers.map(tn.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,jt).updatePermissions(n,e)})}getParticipantsInMeetingPreJoin(){return u(this,null,function*(){return c(this,jt).getRoomPeersNonPaginated()})}},Ar=new WeakMap,Mr=new WeakSet,dn=function(){return c(this,Ar).getValue("roomNodeClient")},ji=new WeakMap,jt=new WeakMap,gm);Yt([y.trace("DyteParticipants.setViewMode")],Mt.prototype,"setViewMode",1);Yt([y.trace("DyteParticipants.setPage")],Mt.prototype,"setPage",1);Yt([y.trace("DyteParticipants.disableAllAudio")],Mt.prototype,"disableAllAudio",1);Yt([y.trace("DyteParticipants.disableAllVideo")],Mt.prototype,"disableAllVideo",1);Yt([y.trace("DyteParticipants.disablePeerAudio")],Mt.prototype,"disableAudio",1);Yt([y.trace("DyteParticipants.disablePeerVideo")],Mt.prototype,"disableVideo",1);Yt([y.trace("DyteParticipants.kickPeer")],Mt.prototype,"kick",1);Yt([y.trace("DyteParticipants.kickAll")],Mt.prototype,"kickAll",1);Yt([y.trace("DyteParticipants.broadcastMessage"),Vt(fs,"rateLimitConfig")],Mt.prototype,"broadcastMessage",1);Yt([y.trace("DyteParticipants.getAllJoinedPeers"),Vt({maxInvocations:10,period:60})],Mt.prototype,"getAllJoinedPeers",1);Yt([y.trace("DyteParticipant.updatePermissions"),Vt({maxInvocations:1e3,period:60})],Mt.prototype,"updatePermissions",1);Yt([y.trace("DyteParticipants.getParticipantsInMeetingPreJoin")],Mt.prototype,"getParticipantsInMeetingPreJoin",1);Mt=Yt([yt("1200")],Mt);var L1=Object.defineProperty,x1=Object.getOwnPropertyDescriptor,ys=(t,e,r,n)=>{for(var i=n>1?void 0:n?x1(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&&L1(e,r,i),i};const Rv=class{constructor(t,e,r){f(this,"participants"),f(this,"self"),f(this,"selectedPeers",Pv),f(this,"maxSpatialLayerUpdates",new Map),f(this,"consumerPeerMap"),f(this,"roomSocketHandler"),f(this,"context"),f(this,"videoPeerConsumerMap",new Map),f(this,"updateConsumerSpatialLayers",Yr(()=>{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",Yr(this.updateConsumers,200,{trailing:!0})),this.context=t,this.roomSocketHandler=r,this.participants=new Mt(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 Xr(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=Rv.formatSocketServiceMessage(t);return new Xr(this.context,Z(B({},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===xt.AUDIO&&!n.screenShare?r.setAudioEnabled(!n.pause):n.kind===xt.VIDEO&&!n.screenShare&&(r.setVideoEnabled(!n.pause),this.updatePipSource(r.id,!n.pause)),r.producers.push(Z(B({},n),{producingTransportId:n.producingTransportId,kind:n.kind===xt.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)}),w.on(b.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())}),w.on(b.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})}),w.on(b.CONSUMER_PAUSED,({id:t})=>{this.processConsumerPaused(t)}),w.on(b.CONSUMER_RESUMED,({id:t})=>{this.processConsumerResumed(t)}),w.on(b.NEW_CONSUMER,({id:t})=>{this.processNewConsumer(t)}),w.on(b.CONSUMER_CLOSED,({id:t})=>{this.processConsumerClosed(t)}),w.on(b.ROOM_MESSAGE,t=>u(this,[t],function*({payload:e,type:r,timestamp:n}){this.participants.emit("broadcastedMessage",{type:r,payload:e,timestamp:n})})),w.on(b.MESSAGE,t=>u(this,[t],function*({payload:e,type:r,timestamp:n}){r!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:r,payload:e,timestamp:n})})),w.on(b.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}))}),w.on(b.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}))}),w.onAsync(b.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})})),w.on(b.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"&&w.emit(b.UPDATE_STAGE_REQUESTS,{request:{displayName:t.name,userId:t.userId,peerId:t.id},add:!0})),w.emit(b.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"&&w.emit(b.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=>{w.emit(b.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&&w.emit(b.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&&w.emit(b.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&&w.emit(b.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:o,track:i})}}static formatSocketServiceMessage(t){var e,r,n,i,s,a;if(!t)return;const o=Ou(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 tn=Rv;ys([y.trace("ParticipantController.setupEvents")],tn.prototype,"setupEventsGlobal",1);ys([y.trace("ParticipantController.processMedia")],tn.prototype,"processMedia",1);ys([y.trace("ParticipantController.processConsumerClosed")],tn.prototype,"processConsumerClosed",1);ys([y.trace("ParticipantController.processConsumerResumed")],tn.prototype,"processConsumerResumed",1);ys([y.trace("ParticipantController.processConsumerPaused")],tn.prototype,"processConsumerPaused",1);ys([y.trace("ParticipantController.processNewConsumer")],tn.prototype,"processNewConsumer",1);var F1=Object.defineProperty,V1=Object.getOwnPropertyDescriptor,U1=(t,e,r,n)=>{for(var i=n>1?void 0:n?V1(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&&F1(e,r,i),i};class Av extends tn{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)),w.on(b.SOCKET_PEERS,e=>u(this,null,function*(){e==null||e.forEach(r=>this.onParticipantJoined(this.fromSocketService(r)))})),this.roomSocketHandler.on(de.peerJoinedBroadcast,({participant:e})=>this.onMediaJoined(e.peerId,e.producerStates)),this.roomSocketHandler.on(de.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),w.emit(b.UPDATE_ACTIVE,{createAllConsumers:!0})}),w.on(b.MAX_SPATIAL_LAYER_CHANGE,({peerId:e,maxSpatialLayer:r})=>{const n=this.videoPeerConsumerMap.get(e);n&&(this.maxSpatialLayerUpdates.set(n,r),this.updateConsumerSpatialLayers())}),w.on(b.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}}})}),w.on(b.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)}),w.on(b.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(de.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(de.selectedPeer,({audioPeers:e,compulsoryPeers:r})=>{this.mediaJoined&&this.onSelectedPeers(r.concat(e))}),this.roomSocketHandler.on(de.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)})}}U1([y.trace("ParticipantController.setupEvents")],Av.prototype,"setupEvents",1);var B1=Object.defineProperty,j1=Object.getOwnPropertyDescriptor,H1=(t,e,r,n)=>{for(var i=n>1?void 0:n?j1(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&&B1(e,r,i),i};class Mv extends tn{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)),w.on(b.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(ce.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(ce.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),w.emit(b.UPDATE_ACTIVE,{createAllConsumers:!0})}),w.on(b.MAX_SPATIAL_LAYER_CHANGE,({peerId:e,maxSpatialLayer:r})=>{const n=this.videoPeerConsumerMap.get(e);n&&(this.maxSpatialLayerUpdates.set(n,r),this.updateConsumerSpatialLayers())}),w.on(b.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}}})}),w.on(b.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)}),w.on(b.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,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(ce.selectedPeer,({audioPeers:e,compulsoryPeers:r})=>{this.mediaJoined&&this.onSelectedPeers(r.concat(e))}),this.roomSocketHandler.on(ce.selectedPeerDiff,({entries:e})=>{if(!this.mediaJoined)return;const r=e.map(n=>({peerId:n.peerId,priority:n.priority}));this.updateActiveParticipantsWithPriorities(r,!0)})}}H1([y.trace("ParticipantController.setupEvents")],Mv.prototype,"setupEvents",1);const Ie=hr(_u().permissions);var q,Ca,Na,Zl,Lt,$t;const Pa=class extends zt{constructor(t,e,r,n=!1){if(super(),T(this,Lt),T(this,q,void 0),T(this,Ca,void 0),T(this,Na,void 0),T(this,Zl,i=>{var s,a,o;const d=i,{chat:h,connectedMeetings:p,plugins:m,polls:g,media:v}=d,I=zc(d,["chat","connectedMeetings","plugins","polls","media"]);if(h&&(h.private&&gn(c(this,q).chat.private,h.private),h.public&&gn(c(this,q).chat.public,h.public),this.emit("chatUpdate")),p&&gn(c(this,q).connectedMeetings,p),v){const A=D=>{switch(D){case Pn.NONE:return K.Allowed;case Pn.ALLOWED:return K.Allowed;case Pn.NOT_ALLOWED:return K.NotAllowed;case Pn.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)}),gn(c(this,q).media,P)}m&&(gn(c(this,q).plugins,m),this.emit("pluginsUpdate")),g&&(gn(c(this,q).polls,g),this.emit("pollsUpdate")),Object.keys(I).length!==0&&gn(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,Na,t),S(this,Ca,r),S(this,q,e),n&&this.setupEvents()}setupEvents(){w.on(b.UPDATE_PERMISSIONS,c(this,Zl))}static fromResponse(t,e,r){return new Pa(r,t,e,!0)}static default(t,e){return new Pa(t,Ie,e)}static init(t,e,r){let n;return r?n=new Pa(t,r,e,!0):n=new Pa(t,Ie,e),n}get mediaRoomType(){const{sfu:t}=c(this,Na).getValue("roomNodeOptions");return t===hs.CF?"CF":"HIVE"}get stageEnabled(){var t;return((t=c(this,q))==null?void 0:t.stageEnabled)||c(this,Ca)===gt.Webinar||c(this,Ca)===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:Ie.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:Ie.disableParticipantAudio}get canAllowParticipantScreensharing(){var t,e;return(e=(t=c(this,q))==null?void 0:t.canAcceptProductionRequests)!=null?e:Ie.canAcceptProductionRequests}get canAllowParticipantVideo(){var t,e;return(e=(t=c(this,q))==null?void 0:t.disableParticipantVideo)!=null?e:Ie.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:Ie.kickParticipant}get pinParticipant(){var t,e;return(e=(t=c(this,q))==null?void 0:t.pinParticipant)!=null?e:Ie.pinParticipant}get canRecord(){var t,e;return(e=(t=c(this,q))==null?void 0:t.canRecord)!=null?e:Ie.canRecord}get waitingRoomType(){var t,e;return(e=(t=c(this,q))==null?void 0:t.waitingRoomType)!=null?e:Ie.waitingRoomType}get waitingRoomBehaviour(){var t,e;return(e=(t=c(this,q))==null?void 0:t.waitingRoomType)!=null?e:Ie.waitingRoomType}get plugins(){var t,e;return(e=(t=c(this,q))==null?void 0:t.plugins)!=null?e:Ie.plugins}get polls(){var t,e;return(e=(t=c(this,q))==null?void 0:t.polls)!=null?e:Ie.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:Ie.media.video.canProduce;return this.stageEnabled&&(c(this,Lt,$t)==="ACCEPTED_TO_JOIN_STAGE"||c(this,Lt,$t)==="ON_STAGE")&&e===K.CanRequest?K.Allowed:this.stageEnabled&&(c(this,Lt,$t)==="OFF_STAGE"||c(this,Lt,$t)==="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:Ie.media.screenshare.canProduce;return this.stageEnabled&&(c(this,Lt,$t)==="ACCEPTED_TO_JOIN_STAGE"||c(this,Lt,$t)==="ON_STAGE")&&e===K.CanRequest?K.Allowed:this.stageEnabled&&(c(this,Lt,$t)==="OFF_STAGE"||c(this,Lt,$t)==="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:Ie.media.audio.canProduce;return this.stageEnabled&&(c(this,Lt,$t)==="ACCEPTED_TO_JOIN_STAGE"||c(this,Lt,$t)==="ON_STAGE")&&e===K.CanRequest?K.Allowed:this.stageEnabled&&(c(this,Lt,$t)==="OFF_STAGE"||c(this,Lt,$t)==="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:Ie.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:Ie.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:Ie.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:Ie.chat.message}get connectedMeetings(){var t,e;return(e=(t=c(this,q))==null?void 0:t.connectedMeetings)!=null?e:Ie==null?void 0:Ie.connectedMeetings}get hiddenParticipant(){var t,e;return(e=(t=c(this,q))==null?void 0:t.hiddenParticipant)!=null?e:Ie.hiddenParticipant}get showParticipantList(){var t;return(t=c(this,q).showParticipantList)!=null?t:Ie.showParticipantList}get canChangeParticipantRole(){var t,e;return(e=(t=c(this,q))==null?void 0:t.canChangeParticipantPermissions)!=null?e:Ie.canChangeParticipantPermissions}get canChangeParticipantPermissions(){var t,e;return(e=(t=c(this,q))==null?void 0:t.canChangeParticipantPermissions)!=null?e:Ie.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 W1=Pa;q=new WeakMap,Ca=new WeakMap,Na=new WeakMap,Zl=new WeakMap,Lt=new WeakSet,$t=function(){return c(this,Na).getValue("stageStatus")};var Dv;class Ov extends zt{constructor(){super(...arguments),f(this,"localMediaHandler"),T(this,Dv,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"?w.emit(b.MEDIA_PERMISSION_ERROR,m):w.emit(b.MEDIA_PERMISSION_UPDATE,m)};if(Ee.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(Ee.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 Ut(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(w.on(b.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)})),w.on(b.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{}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{}finally{this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})})}}Dv=new WeakMap;const ia={},Fn={executeWithLock({methodName:t,lockName:e,timeout:r}){return(n,i,s)=>{const a=s.value;return s.value=function(...o){if(ia[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}ia[e]=!0;const d=setTimeout(()=>delete ia[e],r),h=a.apply(this,o);return Promise.resolve(h).then(()=>{delete ia[e],clearTimeout(d)}).catch(()=>{delete ia[e],clearTimeout(d)}),h},s}}};var $1=Object.defineProperty,J1=Object.getOwnPropertyDescriptor,Dt=(t,e,r,n)=>{for(var i=n>1?void 0:n?J1(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&&$1(e,r,i),i},sa,Ot,aa,Dr,ln,Jn,it,ut,Ye,tt,oa,ca,Io,ul,vm;let lt=(vm=class extends Ov{constructor(t,e,r,n,i){var s;super(),T(this,ln),T(this,it),T(this,Ye),T(this,Io),f(this,"name"),f(this,"picture"),f(this,"customParticipantId"),f(this,"waitlistStatus"),T(this,sa,void 0),T(this,Ot,void 0),T(this,aa,void 0),f(this,"role"),f(this,"userId"),f(this,"organizationId"),f(this,"supportsRemoteControl",!1),f(this,"device"),T(this,Dr,void 0),f(this,"hidden",!1),f(this,"presetName"),f(this,"roomState","init"),T(this,oa,new Set),T(this,ca,new Set),S(this,Dr,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,Ot,r),S(this,sa,n),this.hidden=!1,S(this,aa,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=Ee.isElectron(),this.device=Ee.getDeviceInfo(),this.presetName=i,n.viewType!==gt.Chat&&this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),Ke(this,Io,ul).call(this)}get stageStatus(){return c(this,Dr).getValue("stageStatus")}get id(){return c(this,Dr).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 lt(t,e,r,n,i);if(n.viewType===gt.Chat)return v;const I=ID(n.mediaConstraints);return gn(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,Ot).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",Ke(this,Io,ul)),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",()=>u(this,null,function*(){if(l.info("DyteSelf::setupEvents::AUDIO_TRACK_CHANGE",B({},ui(this))),c(this,Ye,tt)&&this.audioEnabled&&this.stageStatus==="ON_STAGE")try{yield c(this,it,ut).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",B({},ui(this))),c(this,Ye,tt)&&this.rawVideoTrack===void 0)l.info("DyteSelf::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&c(this,Ye,tt)&&this.stageStatus==="ON_STAGE")try{const t=yield c(this,it,ut).shareWebcam(this.videoTrack);t&&t.id!==this.videoTrack.id&&Q.hasFeature(ie.EXP_RESHARE)&&(yield c(this,it,ut).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,Ye,tt)){l.error("DyteSelf.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{yield c(this,it,ut).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",B({},ui(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",B({},ui(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,Ye,tt)&&(yield c(this,it,ut).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),$.videoOff()})),c(this,Ot).on("permissionsUpdate",t=>{var e,r,n;(e=t==null?void 0:t.media)!=null&&e.audio&&c(this,Ot).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,Ot).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,Ot).canProduceScreenshare!==K.Allowed&&(this.disableScreenShare(),l.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return c(this,Ot)}get config(){return c(this,sa)}get roomJoined(){var t;return c(this,sa).viewType===gt.Livestream&&this.stageStatus!=="ON_STAGE"?((t=c(this,Dr).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:c(this,Ye,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,Ot).canProduceAudio===K.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if($.audioOn(),yield this.localMediaHandler.enableAudio(),c(this,Ye,tt)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{yield c(this,it,ut).shareMic(this.audioTrack)}catch(t){l.error("DyteSelf::enableAudio::Error while sharing mic",{error:t}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return;c(this,it,ut).unmuteSelf()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}})}enableVideo(){return u(this,null,function*(){if(c(this,Ot).canProduceVideo!==K.NotAllowed&&!(c(this,Ot).canProduceVideo===K.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if($.videoOn(),yield this.localMediaHandler.enableVideo(),c(this,Ye,tt)&&this.stageStatus==="ON_STAGE")try{yield c(this,it,ut).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",B({},ui(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,Ye,tt))throw new _("Can`t enable screenshare without joining room","1105");if(c(this,Ot).canProduceScreenshare!==K.NotAllowed&&!(c(this,Ot).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,it,ut).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,Ye,tt)&&c(this,it,ut).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,Ye,tt)&&(yield c(this,it,ut).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,Ye,tt)&&(yield c(this,it,ut).disableScreenShare()),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))})}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var r;S(this,aa,t);const n=t?"pinned":"unpinned";(r=c(this,ln,Jn))==null||r.updateSource(this.id,{pinned:t}),e&&this.emit(n,this)}get isPinned(){return c(this,aa)}pin(){return u(this,null,function*(){if(!c(this,Ye,tt))throw new _("Can`t pin participants without joining room","1105");return this.show(),c(this,it,ut).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!c(this,Ye,tt))throw new _("Can`t unpin participants without joining room","1105");return c(this,it,ut).pinPeer(null)})}hide(){return u(this,null,function*(){if(!c(this,Ye,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,Ye,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{c(this,Ye,tt)&&(yield c(this,it,ut).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{c(this,Ye,tt)&&(yield c(this,it,ut).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,oa).add(t):c(this,ca).add(t),this.updateVideo(t),e||(n=c(this,ln,Jn))==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,ln,Jn).removeSource(this.id);return}t.srcObject=void 0,e?c(this,oa).delete(t):(c(this,ca).delete(t),c(this,ln,Jn).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,ln,Jn))==null||n.enableSource(this.id)}else t.srcObject=void 0,e||(i=c(this,ln,Jn))==null||i.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},sa=new WeakMap,Ot=new WeakMap,aa=new WeakMap,Dr=new WeakMap,ln=new WeakSet,Jn=function(){return c(this,Dr).getValue("pip")},it=new WeakSet,ut=function(){return c(this,Dr).getValue("roomNodeClient")},Ye=new WeakSet,tt=function(){var t;return((t=c(this,Dr).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},oa=new WeakMap,ca=new WeakMap,Io=new WeakSet,ul=function(){Array.from(c(this,ca)).forEach(t=>this.updateVideo(t,!1)),Array.from(c(this,oa)).forEach(t=>this.updateVideo(t,!0))},vm);Dt([y.trace("DyteSelf.cleanupEvents")],lt.prototype,"cleanupEvents",1);Dt([y.trace("DyteSelf.setupEvents")],lt.prototype,"setupEvents",1);Dt([y.trace("DyteSelf.setupTracks")],lt.prototype,"setupTracks",1);Dt([y.trace("DyteSelf.destructMediaHandler")],lt.prototype,"destructMediaHandler",1);Dt([y.trace("DyteSelf.removeDocumentEventListeners")],lt.prototype,"removeDocumentEventListeners",1);Dt([Fn.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),y.trace("DyteSelf.enableAudio")],lt.prototype,"enableAudio",1);Dt([Fn.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),y.trace("DyteSelf.enableVideo")],lt.prototype,"enableVideo",1);Dt([y.trace("DyteSelf.updateVideoConstraints")],lt.prototype,"updateVideoConstraints",1);Dt([y.trace("DyteSelf.enableScreenShare"),Fn.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3})],lt.prototype,"enableScreenShare",1);Dt([y.trace("DyteSelf.updateScreenshareConstraints")],lt.prototype,"updateScreenshareConstraints",1);Dt([Fn.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),y.trace("DyteSelf.disableAudio")],lt.prototype,"disableAudio",1);Dt([Fn.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),y.trace("DyteSelf.disableVideo")],lt.prototype,"disableVideo",1);Dt([Fn.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3}),y.trace("DyteSelf.disableScreenShare")],lt.prototype,"disableScreenShare",1);Dt([y.trace("DyteSelf.setDevice")],lt.prototype,"setDevice",1);lt=Dt([yt("1100")],lt);class G1 extends kv{constructor(e){super(e),f(this,"sessionDescription"),this.sessionDescription=e.sessionDescription}}class q1 extends wv{}class z1 extends bv{retryFailedConsumerCreationTasks(e){return u(this,null,function*(){return Fc(e.map(r=>u(this,null,function*(){return _r(n=>u(this,null,function*(){return n>0&&l.warn(`retrying failed consumer creation task: ${JSON.stringify(r)}`),this.consumerCreationTask(B({},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 oe=G;oe.enabled=!0,this.handler.midTransceiverMap.set(W.mid,W);const se=new G1({id:r,localId:W.mid,track:oe,paused:d,producerId:n,producingPeerId:i,handler:this.handler,appData:Z(B({},p),{screenShare:h,peerId:i}),reuseTrack:!0,rtpReceiver:W.receiver,producingTransportId:s,sessionDescription:g});this.consumers.set(r,se),se.once("close",()=>{this.consumers.delete(se.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",se),clearTimeout(D),A(se)}}catch(oe){l.warn("error while creating consumer:",oe),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 nt("closed");if(this.direction!=="recv")throw new Si("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}))})})),Fc(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 Si("not a sending Transport");if(e.readyState==="ended")throw new nt("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:Z(B({},o||{}),{mid:A})}),N=yield v(P);return{producerId:D,localId:N,rtpSender:I}}),"producer"),m=new q1({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 K1 extends Iv{createTransport({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,appData:a,config:o}){const d=Ei(),h=new z1({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 Pt;class Y1{constructor(e){T(this,Pt,void 0),S(this,Pt,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,Pt).sendMessagePromiseWithTimeout({event:de.joinRoom,protobuf:kg.toBinary(s),timeout:5e3})).payload})}connectTransport(e){return u(this,null,function*(){const r=(yield c(this,Pt).sendMessagePromise(de.createWebRTCTransport,yg.toBinary(e))).payload,{transportId:n,description:i}=wu.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,Pt).sendMessagePromise(de.produce,wg.toBinary(e))).payload,s=xg.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,Pt).sendMessagePromise(de.consume,Iu.toBinary(e))).payload,{consumerIdsMap:{map:n},description:i}=Lg.fromBinary(r);return{consumerStateMap:n,sessionDescription:i}})}closeProducer(e){return u(this,null,function*(){const r=(yield c(this,Pt).sendMessagePromise(de.closeProducer,Cg.toBinary(e))).payload,{description:n}=Fg.fromBinary(r);return n})}closeConsumer(e){return u(this,null,function*(){return(yield c(this,Pt).sendMessagePromise(de.closeConsumer,Pg.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,Pt).sendMessagePromise(de.hostControlPeer,Mg.toBinary(n))).payload;if(!i)return!1;const{status:s}=Bg.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,Pt).sendMessagePromise(de.hostControlAllPeers,Dg.toBinary(r))).payload;if(!n)return!1;const{status:i}=jg.fromBinary(n);return i==="success"})}kickAll(){return u(this,null,function*(){const e={},r=(yield c(this,Pt).sendMessagePromise(de.kickAll,Cu.toBinary(e))).payload;if(!r)return!1;const{status:n}=Ug.fromBinary(r);return n==="success"})}kickPeer(e){return u(this,null,function*(){const r=(yield c(this,Pt).sendMessagePromise(de.kickPeer,Rg.toBinary(e))).payload;if(!r)return!1;const{status:n}=Vg.fromBinary(r);return n==="success"})}changeDisplayName(e){return u(this,null,function*(){const r=(yield c(this,Pt).sendMessagePromise(de.changeDisplayName,Ag.toBinary(e))).payload;if(!r)return!1;const{status:n}=Hg.fromBinary(r);return n==="success"})}notifySelfJoinComplete(){return u(this,null,function*(){const e={},r=(yield c(this,Pt).sendMessagePromise(de.selfJoinComplete,_g.toBinary(e))).payload;return Ac.fromBinary(r)})}}Pt=new WeakMap;const Q1=Error("task execution aborted");class X1{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(Q1),this.executor.then(n=>e(n))})})}}let ym=0;const Co=new Map;class hl{static execute(e){const r=ym;ym+=1;const n=new X1(r,e);return Co.set(r,n),{id:r,value:n.execute().finally(()=>Co.delete(r))}}static stop(e){const r=Co.get(e);r&&(r.cancel(),Co.delete(e))}}const Z1=2e3;var Zi,Ra,jr;class eO extends vv{constructor(e,r){super(),T(this,Zi),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,jr,void 0),S(this,jr,e),this._device=new K1({}),this._socket=r,c(this,Zi,Ra).mediaState={recv:{state:er.NEW,reconnected:!1},send:{state:er.NEW,reconnected:!1}},this.transportDisconnected={consuming:!1,producing:!1},this._socketHandler=new Y1(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 ze().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&&hl.stop(I.id),s){case"send":{const A=hl.execute(this.createSendTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(a=c(this,jr).getValue("modules").e2ee)==null?void 0:a.enabled},config:{enableHighBitrate:(h=(d=(o=c(this,jr).getValue("defaults").mediaConfiguration)==null?void 0:o.audio)==null?void 0:d.enableHighBitrate)!=null?h:!1,enableStereo:(g=(m=(p=c(this,jr).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=hl.execute(this.createRecvTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(v=c(this,jr).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 _r((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(Z(B({},e),{additionalSettings:Z(B({},(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 _r((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?Gt.SUBSCRIBER:Gt.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,Vc(i),n,e);break}case"handshake":{const o={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,Vc(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{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=cu(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:Gt.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{}m.set(g,{consumerId:v.consumerId,trackId:(I=v.producerTrack)==null?void 0:I.trackId,streamId:v.producerTrack.streamId,kind:v.producerState.kind===xt.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{}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:Z(B({},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===xt.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)===zr.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:zr.INITIALIZING});try{const a=yield this._sendTransport.produce(r);return(i=r.appData)!=null&&i.e2ee&&w.emit(b.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:Gt.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:zr.INITIALIZED}),this.reconfigureWebcamLayers(),a.track}catch(a){throw this._producerStatus.set(e,{status:zr.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),w.emit(b.CONSUMER_CLOSED,{id:e.id})})),this._consumers.set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),w.emit(b.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 _r(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&&w.emit(b.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,jr).getValue("modules").e2ee.enabled&&w.emit(b.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(de.toggleConsumer,Rc.toBinary(r)),e.pause(),w.emit(b.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(de.toggleConsumer,Rc.toBinary(n)),r.resume(),w.emit(b.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:Gt.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(de.renegotiateSessionDescription,Sg.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(),w.emit(b.CONSUMER_PAUSED,{id:i.id})):(i.resume(),w.emit(b.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{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>20*1e3&&(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,Zi,Ra).mediaState[n]={state:r,reconnected:r==="connected"?this.transportDisconnected[n]:c(this,Zi,Ra).mediaState[n].reconnected},r==="connected"&&(this.transportDisconnected[n]=!1),w.emit(b.TRANSPORT_STATE_UPDATE,B({transport:n},c(this,Zi,Ra).mediaState[n]))}}Zi=new WeakSet,Ra=function(){return c(this,jr).getValue("connectionHandler")},jr=new WeakMap;var tO=Object.defineProperty,rO=Object.getOwnPropertyDescriptor,pe=(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&&tO(e,r,i),i},_t,ve,Or,Hi,Gn,qn,Po,Ro,Ao,un,da,Nr,hn,Sm;const Nv=(Sm=class extends gv{constructor(t,e){var r,n;super(),T(this,Nr),T(this,_t,void 0),T(this,ve,void 0),T(this,Or,void 0),T(this,Hi,void 0),T(this,Gn,void 0),T(this,qn,void 0),T(this,Po,void 0),T(this,Ro,void 0),T(this,Ao,void 0),T(this,un,void 0),T(this,da,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,_t,o),S(this,Or,!1),S(this,ve,new eO(t,o)),this.maxPreferredStreams=6,this.activatedProducingPeerIds=new Set,S(this,un,new Set),S(this,Hi,!1),S(this,Gn,0),S(this,qn,new us),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,Po,Yr(()=>u(this,null,function*(){if(!c(this,Nr,hn).mediaJoinAttempted)return;const{roomJoined:h}=yield this.joinRoom(this.peerDisplayName,this.roomUUID,{},!0,!0);h&&(w.emit(b.RESET_PRODUCER_STATE),w.emit(b.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3})),S(this,Ro,Yr(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports(["send"]),l.info("send transport reconected!"),w.emit(b.RESET_PRODUCER_STATE)}),1e3)),S(this,Ao,Yr(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports(["recv"]),l.info("recv transport reconnected!"),this.activatedProducingPeerIds=new Set,w.emit(b.UPDATE_ACTIVE,{createAllConsumers:!0})}),1e3))}get mediaState(){return c(this,Nr,hn).mediaState}get mediaJoined(){return c(this,Nr,hn).mediaJoined}set mediaJoined(t){c(this,Nr,hn).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 Nv(t,{legacyMode:r,authToken:i,socketClient:a,roomName:n,meetingTitle:s})})}get sfuHandler(){return c(this,ve)}get rejoinRoom(){return c(this,Po)}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,un).clear(),this.activatedProducingPeerIds.clear(),t&&(c(this,qn).stop(),this.sfuHandler.stopAllTransports(),this.sfuHandler.reset(),S(this,qn,new us))}reconnectTransport(t){return u(this,null,function*(){l.info(`CFNodeClient::Room joining state: ${c(this,Or)}`),!(!t||c(this,Or))&&(t.direction==="send"?yield c(this,Ro).call(this,t):yield c(this,Ao).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,Nr,hn).mediaJoinAttempted=!0,S(this,Or,!0),this.reset(s);const o=ze().ipInfo;if(o!=null&&o.loc&&!c(this,da)){const h=o.loc.split(",");S(this,da,{latitude:parseFloat(h[0]),longitude:parseFloat(h[1])})}let d;try{return d=yield c(this,qn).push(()=>this._joinRoom(r,n,i,a,c(this,da)),"joinRoom"),d}catch{d={roomJoined:!1}}return d.roomJoined||w.emit(b.ROOM_NODE_FAILED),d})}_partialJoinRoom(t,e,r=!1,n=void 0){return u(this,null,function*(){const i=ze().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 _r((a,o)=>(c(this,_t).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,qn).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:Z(B({},Ee.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,Or,!1),S(this,Hi,!0),this.mediaJoined=!0,w.emit(b.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,Hi,!1),c(this,Nr,hn).mediaJoinAttempted=!1;const t={closeRoom:!1};c(this,_t).sendMessagePromise(de.leaveRoom,bg.toBinary(t)).then(e=>{var r;(r=Ng.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 am||(r=640),e.encodings=bD[r],Q.hasFeature(ie.ENABLE_CF_SIMULCAST)&&(e.encodings=am[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:Ee.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:Ee.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 nt("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,_t).sendMessage(de.toggleProducer,Cn.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,_t).sendMessage(de.toggleProducer,Cn.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&&w.emit(b.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,_t).sendMessage(de.toggleProducer,Cn.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&&w.emit(b.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,_t).sendMessage(de.toggleProducer,Cn.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,un).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,_t).sendMessagePromise(de.globalPinPeer,Ig.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,un).add(t.consumerPeerId),c(this,un).size}switchConsumersToLayer(t,e){return u(this,null,function*(){this.sfuHandler.switchConsumersToLayer(t,e)})}handleSocketEvents(){return u(this,null,function*(){c(this,_t).on(de.peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:r}=Wg.fromBinary(t);if(e===this.peerId)return;l.info(`producer created broadcast: ${e}, producer state: ${r}`),w.emit(b.NEW_PRODUCER,{peerId:e,producer:Z(B({},r),{kind:r.kind===xt.AUDIO?"audio":"video"})})}catch(e){l.error("error in peer-producer-create-broadcast",{error:e})}}),c(this,_t).on(de.peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{kind:r,pause:n,producerId:i}}=Ol.fromBinary(t),s=r===xt.AUDIO?"audio":"video";l.info(`producer toggle broadcast: ${e}, producerId: ${i}, kind:${s}, paused:${n}`),w.emit(b.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(),w.emit(b.CONSUMER_PAUSED,{id:a.id})):(a.resume(),w.emit(b.CONSUMER_RESUMED,{id:a.id})))})}catch(e){l.error("error in producer toggle broadcast handler",{error:e})}}),c(this,_t).on(de.peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=Mc.fromBinary(t);if(e===this.peerId)return;l.info(`peer left broadcast:${e}`),c(this,un).delete(e),this.sfuHandler.cleanupConsumers(e)}catch(e){l.error("error in peer left broadcast",{error:e})}}),c(this,_t).on(de.peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=$g.fromBinary(t);if(e===this.peerId)return;l.info(`producer closed broadcast:${e}`),w.emit(b.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),w.emit(b.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,_t).on(de.mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!c(this,Or)&&!c(this,Hi)||(l.warn("media hub termination broadcast received, rejoining room"),w.emit(b.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,Nr,hn).socketState)==null?void 0:e.state)!=="connected"){l.warn("Ignoring rejoin attempt because socket is not connected");return}if(c(this,Gn)>3&&!t){l.warn("cannot rejoin more already rejoined 3 times");return}if(c(this,Or)&&!t){l.warn("room joining in progress, cannot start rejoining");return}S(this,Gn,c(this,Gn)+1),l.warn(`rejoining the room because transports are failing. [rejoinCount: ${c(this,Gn)}]`),this.mediaJoined=!1,w.emit(b.ROOM_NODE_DISCONNECTED),this.rejoinRoom()})}handleCallstatsEvents(){$.onConsumerScore(t=>{t.forEach((e,r)=>{const n=this.sfuHandler.consumers.get(r);n&&w.emit(b.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&&w.emit(b.PRODUCER_SCORE_UPDATE,{id:r,kind:n.kind,appData:n.appData,score:e.score,scoreStats:e})})})}},_t=new WeakMap,ve=new WeakMap,Or=new WeakMap,Hi=new WeakMap,Gn=new WeakMap,qn=new WeakMap,Po=new WeakMap,Ro=new WeakMap,Ao=new WeakMap,un=new WeakMap,da=new WeakMap,Nr=new WeakSet,hn=function(){return this.context.getValue("connectionHandler")},Sm);let ue=Nv;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 nO(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 iO(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 Lv(t,e){return u(this,arguments,function*(r,n,i=hs.HIVE){return i===hs.CF?iO(r,n):nO(r,n)})}function xv(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch{l.error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var sO=Object.defineProperty,aO=Object.getOwnPropertyDescriptor,oO=(t,e,r,n)=>{for(var i=n>1?void 0:n?aO(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&&sO(e,r,i),i};let Wi;var Mo,Em;const Fv=(Em=class{constructor(t,e){f(this,"socket"),T(this,Mo,void 0),S(this,Mo,e),this.socket=t,this.handleSocketEvents()}static create(t,e){return Wi||(Wi=new Fv(t,e)),Wi}static cleanup(){var t;try{(t=Wi==null?void 0:Wi.socket)==null||t.disconnect()}catch{l.error("roomSocketHandler::cleanup")}Wi=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,xC.toBinary(n));try{const{peer:s}=$i.fromBinary((yield i).payload);c(this,Mo).getValue("connectionHandler").socketJoined=!0,w.emit(b.SOCKET_SERVICE_ROOM_JOINED,{peer:s});const a=this.getRoomState(),o=this.getRoomPeersNonPaginated(),[{room:d},{peers:h}]=yield Promise.all([a,o]);return w.emit(b.ROOM_STATE,d),w.emit(b.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 EP.fromBinary((yield this.socket.sendMessagePromise(j.getAllAddedParticipants)).payload).participants.map(t=>{var e=t,{id:r}=e,n=zc(e,["id"]);return Z(B({},n),{userId:r})})}catch{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,IC.toBinary(i));n=$d.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=$d.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=$d.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,Gg.toBinary({peerId:t}));e=$i.fromBinary(r.payload)}catch(r){l.error("getPeerInfo::binary_decode_error",{error:r})}return e})}getRoomState(){return u(this,null,function*(){let t=Ap.create();try{const e=yield this.socket.sendMessagePromise(j.getRoomInfo);t=Ap.fromBinary(e.payload)}catch(e){l.error("getRoomState::binary_decode_error",{error:e})}return t})}getRoomStageState(){return u(this,null,function*(){let t=Np.create();try{const e=yield this.socket.sendMessagePromise(j.getRoomStageState);t=Np.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,Fs.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,Fs.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,Fs.toBinary(n))})}leaveRoom(){return u(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(j.leaveRoom,VC.toBinary({}))})}kick(t){return u(this,null,function*(){const e={peerIds:[t]};this.socket.sendMessage(j.kick,bP.toBinary(e))})}kickAll(t=!1){return u(this,null,function*(){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(j.kickAll,Cu.toBinary(e))})}getWaitingRoomRequests(){this.socket.sendMessage(j.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(j.acceptWaitingRoomRequests,CP.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(j.denyWaitingRoomRequests,RP.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(Wo.updateUserPreset,iR.toBinary(r))})}handleSocketEvents(){this.socket.on(j.broadcastMessage,({payload:t})=>{try{const e=Fs.fromBinary(t);w.emit(b.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=Fs.fromBinary(t);w.emit(b.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=$i.fromBinary.bind($i),n=$i.create();break}case j.getWaitingRoomRequests:{r=(i,s)=>i?Op.fromBinary(i,s):{requests:[]},n=Op.create();break}case j.recordingPaused:case j.recordingStarted:case j.recordingStopped:{r=Wp.fromBinary.bind(Wp);break}case Wo.updateUserPreset:{r=Lp.fromBinary.bind(Lp);break}case de.peerJoinedBroadcast:case ce.peerJoinedBroadcast:{r=wp.fromBinary.bind(wp);break}case de.selfJoinComplete:case ce.selfJoinComplete:{r=Ac.fromBinary.bind(Ac);break}case de.globalPeerPinBroadcast:case ce.globalPeerPinBroadcast:{r=Cp.fromBinary.bind(Cp);break}case de.selectedPeer:case ce.selectedPeer:{r=Dl.fromBinary.bind(Dl);break}case de.selectedPeerDiff:case ce.selectedPeerDiff:{r=bp.fromBinary.bind(bp);break}case de.leaveRoom:case ce.leaveRoom:{r=Mc.fromBinary.bind(Mc);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(Wo.getUserPresets,QP.toBinary(e)),n=tR.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}})}},Mo=new WeakMap,Em);let Bc=Fv;oO([y.trace("RoomSocketHandler.joinRoom")],Bc.prototype,"joinRoom",1);var cO=Object.defineProperty,dO=Object.getOwnPropertyDescriptor,Pi=(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&&cO(e,r,i),i},zn,yr,ft,Ht,Xt,Tm;const Vv=(Tm=class{constructor(t,e,r,n){T(this,Ht),f(this,"self"),f(this,"authToken"),T(this,zn,void 0),f(this,"viewType"),T(this,yr,void 0),T(this,ft,void 0);const{socket:i}=r,s=t.getValue("authToken");this.self=e,S(this,ft,t),this.viewType=n,this.authToken=s,S(this,zn,i),S(this,yr,r),e.config.viewType!==gt.Chat&&this.setupEvents()}get peerId(){return c(this,ft).getValue("peerId")}get mediaJoined(){return c(this,ft).getValue("connectionHandler").mediaJoined}static init(t,e,r,n,i){return u(this,null,function*(){const s=ze(),a=t.getValue("peerId"),o=!!t.getValue("cachedUserDetails"),d=yield lt.__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:Ee.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield s.getICEServers(),apiBase:t.getValue("apiBase"),flags:Q.getAllFlags(),logger:l,apiHostnames:fg(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 Vv(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,Ht,Xt).shareMic(e)}catch{this.self.disableAudio()}if(n.canProduceVideo&&s)try{const d=yield c(this,Ht,Xt).shareWebcam(r);d&&d.id!==r.id&&Q.hasFeature(ie.EXP_RESHARE)&&(yield c(this,Ht,Xt).shareWebcam(d))}catch{this.self.disableVideo()}if(n.canProduceScreenshare&&a)try{yield(t=c(this,Ht,Xt))==null?void 0:t.shareScreen({video:o.video,audio:o.audio})}catch{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,Ht,Xt).reset(),t&&(yield this.joinRoom(t))})}setupEvents(){w.on(b.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),w.on(b.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),w.on(b.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),w.on(b.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),w.on(b.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{t===!1&&(this.self.roomState="init"),this.resetSelf(t)}),w.on(b.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;t&&Q.hasFeature(ie.REFRESH_ID_ON_DISCONNECTION)&&(e=Ei()),c(this,zn).updateURL(e),y.resetPeerId(e),ze().setHeader("dyte-tracing-id",e),hi.remapContext(e,c(this,ft)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),w.on(b.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),c(this,yr).on(j.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),c(this,yr).on(Wo.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&w.emit(b.UPDATE_PERMISSIONS,e.patch)})}),c(this,yr).on(j.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),c(this,yr).on(j.kick,()=>{this.kickHandler({kickType:"kick"})}),c(this,yr).on(j.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),w.onAsync(b.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),w.on(b.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})}),w.on(b.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),$.audioOff())})),w.on(b.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),$.videoOff())})),w.onAsync(b.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),w.on(b.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return u(this,null,function*(){try{const{peer:e}=yield c(this,yr).joinRoom(this.self,this.self.config.viewType);c(this,yr).socket.flush();const r=Ou(e.stageType);if(c(this,ft).setValue("stageStatus",r,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),c(this,ft).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,zn))==null||e.disconnect()}catch{l.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),c(this,ft).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),c(this,ft).notify("stageStatus");try{(r=c(this,zn))==null||r.disconnect()}catch{l.error("SelfController::leaveRoom::socketDisconnect")}xv(c(this,ft)),Bc.cleanup(),this.self.roomState=t,this.self.emit("roomLeft",{state:t})})}partialMediaRoom(){var t;(t=c(this,Ht,Xt))==null||t.partialJoinRoom(this.self.name,c(this,ft).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,ft).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 Lv(c(this,ft),{socket:c(this,zn),peerId:n,meetingId:s,authToken:a,roomNodeUrl:p,meetingTitle:m},h)}const{roomJoined:g}=(r=yield(e=c(this,Ht,Xt))==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,ft).getValue("viewType");t!=="connected-meeting"&&(yield this.cleanupSelf()),!(t==="stageLeft"&&e===gt.Webinar)&&c(this,Ht,Xt)&&(c(this,Ht,Xt).mediaJoined&&t!=="disconnected"&&(yield c(this,Ht,Xt).leaveRoom()),!(t==="stageLeft"&&e===gt.Livestream)&&(c(this,Ht,Xt).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()})}},zn=new WeakMap,yr=new WeakMap,ft=new WeakMap,Ht=new WeakSet,Xt=function(){return c(this,ft).getValue("roomNodeClient")},Tm);let Vn=Vv;Pi([y.trace("SelfController.resetSelf")],Vn.prototype,"resetSelf",1);Pi([y.trace("SelfController.setupEvents")],Vn.prototype,"setupEvents",1);Pi([y.trace("SelfController.joinRoom")],Vn.prototype,"joinRoom",1);Pi([y.trace("SelfController.leaveRoom")],Vn.prototype,"leaveRoom",1);Pi([y.trace("SelfController.joinMediaRoom")],Vn.prototype,"joinMediaRoom",1);Pi([y.trace("SelfController.leaveMediaRoom")],Vn.prototype,"leaveMediaRoom",1);Pi([y.trace("SelfController.init")],Vn,"init",1);var cc;class lO{constructor(e){T(this,cc,void 0),S(this,cc,e)}on(e,r){let n;e===j.roomPeerCount?n=Rp.fromBinary.bind(Rp):n=Bp.fromBinary.bind(Bp),c(this,cc).on(e,({payload:i})=>{const s=n(i);return r(s)})}}cc=new WeakMap;var dc;class uO{constructor(e){T(this,dc,void 0),S(this,dc,e)}on(e,r){let n,i;switch(e){case j.transcript:{n=Wd.fromBinary.bind(Wd),i=Wd.create();break}default:{l.debug("AISocketHandler switch case hit default, event not accounted for.");break}}c(this,dc).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)})}}dc=new WeakMap;var hO=Object.defineProperty,pO=Object.getOwnPropertyDescriptor,Wu=(t,e,r,n)=>{for(var i=n>1?void 0:n?pO(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&&hO(e,r,i),i},_n;class fd{constructor(e){T(this,_n,void 0),S(this,_n,e)}getPolls(){return c(this,_n).sendMessagePromise(Hr.getPolls)}createPoll(e,r,n=!1,i=!1){const s={anonymous:n,hideVotes:i,question:e,options:r};return c(this,_n).sendMessage(Hr.createPoll,YA.toBinary(s))}votePoll(e,r){const n={index:r,pollId:e};return c(this,_n).sendMessage(Hr.votePoll,XA.toBinary(n))}on(e,r){let n,i;switch(e){case Hr.updatePoll:case Hr.createPoll:case Hr.votePoll:{n=Kd.fromBinary.bind(Kd),i=Kd.create();break}}c(this,_n).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,_n).removeListeners(e)}}_n=new WeakMap;Wu([y.trace("PollSocketHandler.getPolls")],fd.prototype,"getPolls",1);Wu([y.trace("PollSocketHandler.createPoll")],fd.prototype,"createPoll",1);Wu([y.trace("PollSocketHandler.votePoll")],fd.prototype,"votePoll",1);var Jt;class mO{constructor(e){T(this,Jt,void 0),S(this,Jt,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield c(this,Jt).sendMessagePromise(j.getStageRequests);return e?zd.fromBinary(e):{stageRequests:[]}})}requestAccess(){c(this,Jt).sendMessage(j.requestStageAccess)}cancelRequestAccess(){c(this,Jt).sendMessage(j.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const r={userIds:e};c(this,Jt).sendMessage(j.grantStageAccess,BA.toBinary(r))})}denyAccess(e){return u(this,null,function*(){const r={userIds:e};c(this,Jt).sendMessage(j.denyStageAccess,HA.toBinary(r))})}joinStage(){return c(this,Jt).sendMessagePromise(j.joinStage,void 0,void 0,j.peerStageStatusUpdate)}leaveStage(e){const r={userIds:[e]};return c(this,Jt).sendMessagePromise(j.leaveStage,Hp.toBinary(r),void 0,j.peerStageStatusUpdate)}kick(e){const r={userIds:e};return c(this,Jt).sendMessagePromise(j.leaveStage,Hp.toBinary(r))}on(e,r){let n;switch(e){case j.grantStageAccess:case j.denyStageAccess:{n=void 0;break}case j.getStagePeers:{n=jp.fromBinary.bind(jp);break}case j.getStageRequests:case j.requestStageAccess:case j.cancelStageRequest:{n=zd.fromBinary.bind(zd);break}case j.peerStageStatusUpdate:{n=Pp.fromBinary.bind(Pp);break}}c(this,Jt).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,Jt).sendMessagePromise(j.getPeerInfo,Gg.toBinary({peerId:e}));return $i.fromBinary(r.payload)})}}Jt=new WeakMap;var ot;class fO{constructor(e){T(this,ot,void 0),S(this,ot,e)}addPlugin(e,r){c(this,ot).sendMessage(z.addPlugin,nA.toBinary({pluginId:e,staggered:r}))}removePlugin(e){c(this,ot).sendMessage(z.removePlugin,sA.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield c(this,ot).sendMessagePromise(z.getPlugins);return e?PA.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,r,n){const i={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};c(this,ot).sendMessage(z.customPluginEventToRoom,fA.toBinary(i),n)}customPluginEventToPeers(e,r,n,i){const s={pluginId:e,peerIds:r,pluginData:new TextEncoder().encode(JSON.stringify(n))};c(this,ot).sendMessage(z.customPluginEventToPeers,vA.toBinary(s),i)}enablePluginForRoom(e,r){c(this,ot).sendMessage(z.enablePluginForRoom,oA.toBinary({pluginId:e}),r)}enablePluginForPeers(e,r,n){c(this,ot).sendMessage(z.enablePluginForPeers,uA.toBinary({pluginId:e,peerIds:r}),n)}disablePluginForRoom(e,r){c(this,ot).sendMessage(z.disablePluginForRoom,dA.toBinary({pluginId:e}),r)}disablePluginForPeers(e,r,n){c(this,ot).sendMessage(z.disablePluginForPeers,pA.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,ot).sendMessage(z.storeInsertKeys,xp.toBinary(s),i)}storeGetKeys(e,r,n,i){const s={pluginId:e,storeName:r,getKeys:n.map(a=>({storeKey:a.key}))};c(this,ot).sendMessage(z.storeGetKeys,TA.toBinary(s),i)}storeDeleteKeys(e,r,n,i){const s={pluginId:e,storeName:r,deleteKeys:n.map(a=>({storeKey:a.key}))};c(this,ot).sendMessage(z.storeDeleteKeys,_A.toBinary(s),i)}storeDelete(e,r,n){c(this,ot).sendMessage(z.storeDelete,wA.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,ot).sendMessage(z.storeInsertKeys,xp.toBinary(i))}on(e,r){let n;switch(e){case z.addPlugin:case z.enablePluginForPeers:case z.enablePluginForRoom:{n=Fl.fromBinary.bind(Fl);break}case z.removePlugin:case z.disablePluginForPeers:case z.disablePluginForRoom:{n=Fp.fromBinary.bind(Fp);break}case z.customPluginEventToPeers:case z.customPluginEventToRoom:{n=Up.fromBinary.bind(Up);break}case z.storeInsertKeys:case z.storeGetKeys:case z.storeDeleteKeys:case z.storeDelete:{n=Vp.fromBinary.bind(Vp);break}}c(this,ot).on(e,({payload:i,id:s})=>{const a=n(i);return r(a,s)})}}ot=new WeakMap;var gO=Object.defineProperty,vO=(t,e,r)=>e in t?gO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,yO=(t,e,r)=>(vO(t,typeof e!="symbol"?e+"":e,r),r),$u=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},F=(t,e,r)=>($u(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)=>($u(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),Le=(t,e,r)=>($u(t,e,"access private method"),r),bn,ii,si,He,ai,Ne,qe,wn,ct,Gr,Rn,ur,is,Wr,eu,Uv,Aa,lc,tu,Bv,Ju,jv,jc,Gu,ru,Hv,Ba,Hc,La,Wc,$c,qu,ss,ja,xa,Jc,zu={exports:{}},as=typeof Reflect=="object"?Reflect:null,km=as&&typeof as.apply=="function"?as.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},uc;as&&typeof as.ownKeys=="function"?uc=as.ownKeys:Object.getOwnPropertySymbols?uc=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:uc=function(t){return Object.getOwnPropertyNames(t)};function SO(t){console&&console.warn&&console.warn(t)}var Wv=Number.isNaN||function(t){return t!==t};function ke(){ke.init.call(this)}zu.exports=ke;zu.exports.once=_O;ke.EventEmitter=ke;ke.prototype._events=void 0;ke.prototype._eventsCount=0;ke.prototype._maxListeners=void 0;var _m=10;function gd(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 _m},set:function(t){if(typeof t!="number"||t<0||Wv(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");_m=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||Wv(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 $v(t){return t._maxListeners===void 0?ke.defaultMaxListeners:t._maxListeners}ke.prototype.getMaxListeners=function(){return $v(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")km(o,this,e);else for(var d=o.length,h=Kv(o,d),r=0;r<d;++r)km(h[r],this,e);return!0};function Jv(t,e,r,n){var i,s,a;if(gd(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=$v(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,SO(o)}return t}ke.prototype.addListener=function(t,e){return Jv(this,t,e,!1)};ke.prototype.on=ke.prototype.addListener;ke.prototype.prependListener=function(t,e){return Jv(this,t,e,!0)};function EO(){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 Gv(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=EO.bind(n);return i.listener=r,n.wrapFn=i,i}ke.prototype.once=function(t,e){return gd(e),this.on(t,Gv(this,t,e)),this};ke.prototype.prependOnceListener=function(t,e){return gd(e),this.prependListener(t,Gv(this,t,e)),this};ke.prototype.removeListener=function(t,e){var r,n,i,s,a;if(gd(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():TO(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 qv(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?kO(i):Kv(i,i.length)}ke.prototype.listeners=function(t){return qv(this,t,!0)};ke.prototype.rawListeners=function(t){return qv(this,t,!1)};ke.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):zv.call(t,e)};ke.prototype.listenerCount=zv;function zv(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?uc(this._events):[]};function Kv(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function TO(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function kO(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function _O(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))}Yv(t,e,s,{once:!0}),e!=="error"&&bO(t,i,{once:!0})})}function bO(t,e,r){typeof t.on=="function"&&Yv(t,"error",e,r)}function Yv(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 wO=zu.exports;class IO 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 bm=new IO;class Qv{static encode(e){return bm.toBinary(e)}static decode(e){return bm.fromBinary(new Uint8Array(e))}}function CO(t,e){return Math.floor(Math.random()*(e-t+1)+t)}class PO{constructor(e={}){yO(this,"opts"),Me(this,bn,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},Se(this,bn,0)}wait(){return u(this,null,function*(){Se(this,bn,F(this,bn)+1);const e=CO(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*oS(2,F(this,bn))));yield new Promise(r=>{setTimeout(r,e)})})}getAttempts(){return F(this,bn)}reset(){Se(this,bn,0)}}bn=new WeakMap;const pn={debug:0,info:1,warn:2,error:3};class RO{constructor(e){Me(this,ii,void 0),Me(this,si,void 0),Se(this,ii,console),Se(this,si,e)}debug(...e){pn[F(this,si)]>pn.debug||F(this,ii).debug("[Sockrates]:",...e)}info(...e){pn[F(this,si)]>pn.info||F(this,ii).info("[Sockrates]:",...e)}warn(...e){pn[F(this,si)]>pn.warn||F(this,ii).warn("[Sockrates]:",...e)}error(...e){pn[F(this,si)]>pn.error||F(this,ii).error("[Sockrates]:",...e)}}ii=new WeakMap;si=new WeakMap;var Xv=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(Xv||{});const AO="2",MO="3";class DO{constructor(e,r){Me(this,eu),Me(this,Aa),Me(this,tu),Me(this,Ju),Me(this,jc),Me(this,ru),Me(this,Ba),Me(this,La),Me(this,$c),Me(this,ss),Me(this,xa),Me(this,He,void 0),Me(this,ai,void 0),Me(this,Ne,void 0),Me(this,qe,void 0),Me(this,wn,void 0),Me(this,ct,void 0),Me(this,Gr,void 0),Me(this,Rn,void 0),Me(this,ur,void 0),Me(this,is,void 0),Me(this,Wr,void 0);var n,i,s,a,o,d,h,p,m,g;Se(this,ai,e),Se(this,wn,[]),Se(this,ct,new wO),Se(this,Gr,!0),Se(this,ur,!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,Rn,{code:void 0,reason:void 0}),Se(this,qe,(g=F(this,Ne).logger)!=null?g:new RO(F(this,Ne).debug?"debug":"info")),Se(this,Wr,new PO)}get readyState(){var e;return(e=F(this,He))==null?void 0:e.readyState}get url(){return F(this,ai)}updateURL(e){Se(this,ai,e),Le(this,ru,Hv).call(this)}get config(){return F(this,Ne)}get sendQueue(){return F(this,wn)}flush(){if(!F(this,Ne).queueOnDisconnect)return!1;const e=[];return F(this,wn).forEach(r=>{this.send(r.event,r.id,r.payload,r.metadata)||e.push(r)}),Se(this,wn,e),F(this,wn)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){F(this,qe).debug("Websocket was already connecting or connected.");return}if(F(this,Gr)!==!1)return new Promise((r,n)=>{Le(this,ss,ja).call(this),Le(this,xa,Jc).call(this);try{Se(this,He,new WebSocket(Le(this,eu,Uv).call(this,F(this,ai)))),F(this,He).binaryType="arraybuffer",F(this,qe).debug("Connecting to",F(this,ai));const i=setTimeout(()=>{F(this,qe).debug("Connection timeout. Closing socket"),Se(this,Gr,!0),Le(this,xa,Jc).call(this),F(this,He).close(3001,"Connection Timeout"),F(this,Ne).autoReconnect&&!F(this,ur)&&(F(this,ct).emit("reconnecting"),Le(this,Ba,Hc).call(this)),n(new Error("Connection timed out!"))},F(this,Ne).connectionTimeout);F(this,He).onopen=()=>{F(this,qe).debug(`Ready State: ${Xv[F(this,He).readyState]}`),i&&clearTimeout(i),Le(this,$c,qu).call(this),Se(this,Rn,{code:void 0,reason:void 0}),F(this,ct).emit("connected"),F(this,Ne).flushOnReconnect&&this.flush(),r()},F(this,He).onclose=s=>{try{i&&clearTimeout(i);const{code:a,reason:o}=s;n(o),F(this,qe).debug("Socket closed. Close event:",s),F(this,qe).debug("Connection closed code:",a),F(this,qe).debug("Connection closed reason:",o),F(this,ur)||Le(this,jc,Gu).call(this,a,o)}catch(a){Le(this,Aa,lc).call(this,a)}},F(this,He).onerror=s=>{Le(this,Aa,lc).call(this,s)},F(this,He).onmessage=s=>Le(this,tu,Bv).call(this,s)}catch(i){Le(this,Aa,lc).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,He)||F(this,He).readyState!==1))return F(this,qe).debug("Queuing message since socket is not connected!",s),F(this,wn).push(s),!1;const a=Qv.encode(s);return Le(this,La,Wc).call(this,a)}emit(e,r,n,i){return this.send(e,r,n,i)}sendRaw(e){return Le(this,La,Wc).call(this,e)}receive(e,r){return F(this,ct).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,ct).on(e,r);return}this.receive(e,r)}removeAllListeners(){F(this,ct).removeAllListeners()}removeReceiver(e,r){this.removeListener(e,r)}removeListener(e,r){F(this,ct).removeListener(e.toString(),r)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){F(this,ct).listeners(e.toString()).map(r=>this.removeListener(e,r))}disconnect(){Se(this,Gr,!1),Le(this,ss,ja).call(this),this.removeAllListeners(),Se(this,Rn,{code:1e3,reason:"Sockrates disconnect method called"}),F(this,He).close(1e3,"Sockrates disconnect method called.")}}He=new WeakMap;ai=new WeakMap;Ne=new WeakMap;qe=new WeakMap;wn=new WeakMap;ct=new WeakMap;Gr=new WeakMap;Rn=new WeakMap;ur=new WeakMap;is=new WeakMap;Wr=new WeakMap;eu=new WeakSet;Uv=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)://.")};Aa=new WeakSet;lc=function(t,e){F(this,qe).error("Error:",{error:t}),F(this,ct).emit("errored",{error:t}),e==null||e(t)};tu=new WeakSet;Bv=function(t){if(Le(this,$c,qu).call(this),t.data===AO){F(this,qe).debug("Received ping from server"),Le(this,La,Wc).call(this,MO);return}const e=Qv.decode(t.data),{id:r,payload:n}=e;F(this,qe).debug("Received message",{event:e.event,messageID:r}),F(this,ct).emit(e.event.toString(),{id:r,payload:n})};Ju=new WeakSet;jv=function(){return F(this,He).readyState===1};jc=new WeakSet;Gu=function(t,e){Se(this,Rn,{reason:e,code:t}),F(this,ct).emit("disconnected",{code:t,reason:e})};ru=new WeakSet;Hv=function(){const{reason:t,code:e}=F(this,Rn);e&&e!==1e3&&F(this,Gr)&&F(this,Ne).autoReconnect&&!F(this,ur)&&(F(this,qe).debug(`Triggering reconnection due to ${t}.`),F(this,ct).emit("reconnecting"),Le(this,Ba,Hc).call(this))};Ba=new WeakSet;Hc=function(t=!0){return u(this,null,function*(){if(t&&F(this,ur)){F(this,qe).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(F(this,ur)||F(this,Wr).reset(),F(this,Ne).maxReconnectionAttempts!==null&&F(this,Wr).getAttempts()>=F(this,Ne).maxReconnectionAttempts){F(this,ct).emit("failed"),Se(this,ur,!1);return}Se(this,ur,!0),Le(this,xa,Jc).call(this),Le(this,ss,ja).call(this);try{if(yield F(this,Wr).wait(),F(this,Gr)===!1)return;if(F(this,qe).debug(`Reconnection attempt ${F(this,Wr).getAttempts()}`),F(this,ct).emit("reconnectAttempt",{attempt:F(this,Wr).getAttempts()}),yield this.connect(),!Le(this,Ju,jv).call(this))throw Error("Reconnect Failed");Se(this,ur,!1),Se(this,Rn,{code:void 0,reason:void 0}),F(this,ct).emit("reconnected")}catch{F(this,qe).debug("Failed to reconnect."),F(this,ct).emit("reconnectFailure",{attempt:F(this,Wr).getAttempts()}),Le(this,Ba,Hc).call(this,!1)}})};La=new WeakSet;Wc=function(t){try{return F(this,He).send(t),!0}catch(e){return F(this,qe).error(e.message),!1}};$c=new WeakSet;qu=function(){this.config.disconnectOnPingTimeout&&(F(this,qe).debug("Resetting ping timeout"),Le(this,ss,ja).call(this),Se(this,is,setTimeout(()=>{var t;F(this,qe).debug("Disconnecting the socket due to ping timeout"),Se(this,Gr,!0);const e=3002,r="Ping timeout";(t=F(this,He))==null||t.close(e,r),Le(this,jc,Gu).call(this,e,r)},F(this,Ne).pingTimeout)))};ss=new WeakSet;ja=function(){F(this,is)&&(clearTimeout(F(this,is)),Se(this,is,void 0))};xa=new WeakSet;Jc=function(){F(this,He)&&(F(this,He).onopen=void 0,F(this,He).onerror=void 0,F(this,He).onmessage=void 0,F(this,He).onclose=void 0)};var OO=Object.defineProperty,NO=Object.getOwnPropertyDescriptor,vd=(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};const wm=65535,LO=3e3;var Kn,Ve,Ue,We,ir,mn,Do,pl,Oo,ml,Im;const Zv=(Im=class{constructor(t,{peerId:e,meetingId:r,authToken:n,capabilities:i}){T(this,Ue),T(this,Do),T(this,Oo),T(this,Kn,void 0),T(this,Ve,void 0),f(this,"roomName"),f(this,"authToken"),f(this,"capabilities"),T(this,ir,void 0),T(this,mn,void 0);var s;if(!e||!r||!n)throw new _("peerId, meetingId, or authToken can not be empty","0404");S(this,ir,void 0),S(this,mn,t),this.capabilities=i,this.roomName=r,this.authToken=n,S(this,Kn,Ke(this,Do,pl).call(this,e)),S(this,Ve,new DO(c(this,Kn),{autoReconnect:!0,disconnectOnPingTimeout:(s=i.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:l})),this.handleSocketConnectionEvents()}get joinAttempted(){return c(this,Ue,We).socketJoinAttempted}set joinAttempted(t){c(this,Ue,We).socketJoinAttempted=t}get peerId(){return c(this,mn).getValue("peerId")}updateURL(t){t!==this.peerId&&(S(this,Kn,Ke(this,Do,pl).call(this,t)),l.debug("SocketService:: Connection URL updated.")),c(this,Ve).updateURL(c(this,Kn))}static getSocketEdgeDomain(t){return ns({servicePrefix:"socket-edge",baseURI:t})}get url(){return c(this,Kn)}connect(){return u(this,null,function*(){c(this,Ue,We).socketJoinAttempted=!0,yield c(this,Ve).connect(),c(this,Ue,We).socketJoinAttempted=!0,c(this,Ue,We).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){return u(this,null,function*(){c(this,Ue,We).socketJoinAttempted=!1,c(this,Ve).disconnect(),c(this,Ue,We).socketJoinAttempted=!0,c(this,Ue,We).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}})}get isConnected(){try{return c(this,Ve).readyState===1}catch{return!1}}sendMessage(t,e,r){const n={};return y.injectContext(n),c(this,Ve).send(t,r!=null?r:Ke(this,Oo,ml).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,Ve).removeListener(s,v),c(this,Ve).removeListener(wm,I),c(this,Ve).removeListener(ce.errorResponse,I),c(this,Ve).removeListener(de.errorResponse,I)},h=n!=null?n:Ke(this,Oo,ml).call(this),p={};y.injectContext(p);const m=({id:v,payload:I})=>{if(h===v){let A;try{const P=PI.fromBinary(I);A=new Error(P.errorMessage)}catch(P){A=new Error("failed to parse error message",{cause:P});try{const D=SC.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,Ve).on(s,g),c(this,Ve).on(wm,m),c(this,Ve).on(ce.errorResponse,m),c(this,Ve).on(de.errorResponse,m),setTimeout(()=>{d(g,m),o(new Error(`request timeout for callback eventId:${t}`))},e),c(this,Ve).send(t,h,r,new TextEncoder().encode(JSON.stringify(p)))})}on(t,e){c(this,Ve).on(t,e)}onStateEvent(t,e){c(this,Ve).on(t,e)}removeListener(t,e){c(this,Ve).removeListener(t,e)}removeListeners(t){c(this,Ve).removeListeners(t)}flush(){return c(this,Ve).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){l.info("SocketService::Connected to socket-edge"),c(this,ir)&&(clearTimeout(c(this,ir)),S(this,ir,void 0)),c(this,Ue,We).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,Ue,We).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?w.emit(b.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:c(this,Ue,We).joinAttempted}):S(this,ir,setTimeout(()=>{w.emit(b.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:c(this,Ue,We).joinAttempted}),S(this,ir,void 0)},LO)),c(this,Ue,We).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){l.info("SocketService::Reconnecting to socket-edge",{country:y.location.country}),c(this,Ue,We).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,Ue,We).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{l.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),c(this,Ue,We).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){l.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:c(this,Ue,We).joinAttempted}}),c(this,ir)&&(clearTimeout(c(this,ir)),S(this,ir,void 0)),w.emit(b.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:c(this,Ue,We).joinAttempted}),c(this,Ue,We).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){l.info("SocketService::Failed to connect to socket-edge",{country:y.location.country}),w.emit(b.SOCKET_SERVICE_FAILED),c(this,Ue,We).updateSocketConnectionState("failed")}))}},Kn=new WeakMap,Ve=new WeakMap,Ue=new WeakSet,We=function(){return c(this,mn).getValue("connectionHandler")},ir=new WeakMap,mn=new WeakMap,Do=new WeakSet,pl=function(t){let e=Zv.getSocketEdgeDomain(c(this,mn).getValue("baseURI"));typeof Pc(c(this,mn),"socket_server_base")=="string"&&(e=Pc(c(this,mn),"socket_server_base"));const r=`wss://${e}`,n=new URL(`${r}/ws`),i=this.peerId,s=Z(B({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},i!==t&&{oldPeerID:i}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(a=>Dc[a]).join(" "),joinWithDetails:!0});return Object.entries(s).forEach(([a,o])=>{n.searchParams.append(a,o.toString())}),n.href},Oo=new WeakSet,ml=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Im);let Xa=Zv;vd([y.trace("SocketService.connect")],Xa.prototype,"connect",1);vd([y.trace("SocketService.disconnect")],Xa.prototype,"disconnect",1);vd([y.trace("SocketService.sendMessagePromise")],Xa.prototype,"sendMessagePromise",1);vd([y.trace("SocketService.sendMessagePromiseWithTimeout")],Xa.prototype,"sendMessagePromiseWithTimeout",1);const oi=class{static handleConnectedRoomsDumpRaw({payload:t}){var e;const r=GC.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=yP.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}static handleMovedPeerRaw({payload:t}){const e=qg.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}static handleConnectedRoomsUpdatedRaw({payload:t}){return Dp.fromBinary(t).payloads.map(e=>({id:e.id,title:e.title}))}static handleConnectedRoomsDeletedRaw({payload:t}){return cP.fromBinary(t).payloads}static getConnectedRoomsDump(){return u(this,null,function*(){const t=yield oi.socketService.sendMessagePromise(j.getConnectedRoomsDump);return oi.handleConnectedRoomsDumpRaw(t)})}static createConnectedRooms(t){return u(this,null,function*(){const{payload:e}=yield oi.socketService.sendMessagePromise(j.createConnectedRooms,YC.toBinary({payloads:t}));return Dp.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 oi.socketService.sendMessagePromise(j.deleteConnectedRooms,aP.toBinary({payloads:e}));return oi.handleConnectedRoomsDeletedRaw(r)})}static movePeersBetweenRooms(t){return u(this,null,function*(){try{const e=yield oi.socketService.sendMessagePromise(j.movePeers,mP.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=oi;f(Fe,"socketService"),f(Fe,"currentMeetingId");var xO=Object.defineProperty,FO=Object.getOwnPropertyDescriptor,yd=(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};const ci=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(w.reset(),Bc.cleanup(),xv(t),Ee.isSupported()===!1)throw new _("Browser not supported","0010",!0);const d=AM(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 hD;t.setValue("connectionHandler",h);const p=ci.createSocketService(t),m=p.connect(),g=d.getPlugins(),[{sfu:v,userResponse:I,meetingTitle:A,roomNodeUrl:P}]=yield Promise.all([ci.getRoomMetadata(),ci.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 ci.setupControllers(p,t,I,g);tD(D)&&ci.createRoomNodeClient(t,p),Aw();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 ci(n,N)})}static getRoomMetadata(){return u(this,null,function*(){const t=ze(),[{roomNodeUrl:e,meetingTitle:r,sfu:n=hs.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=Pw(i),o=Z(B({entity:Ml.PEER,clientId:s,isAnonUser:!s,sdkVersion:t.getValue("sdkVersion"),meetingHash:a,roomName:i},Ee.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const d=n!=null&&n.whitelabelled_flags_endpoint?ns({servicePrefix:"flags",baseURI:r}):"edge.api.flagsmith.com";yield Q.identify(`${Ml.PEER}_${e}`,JSON.parse(JSON.stringify(o)),!1,5e3,d),l.info("flagsmith::allFlags",{flags:JSON.stringify(Q.getAllFlags())},!0)}catch{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=KD.init(d,!o.theme),{viewType:I,mediaConstraints:{audio:A}}=v;e.setValue("viewType",I),e.setValue("defaults",B({mediaConfiguration:{audio:{enableHighBitrate:(i=A.enableHighBitrate)!=null?i:!1,enableStereo:(s=A.enableStereo)!=null?s:!1}}},p));const P=W1.init(e,I,d.permissions);e.setValue("maxPreferredStreams",Ee.isMobile()?v.maxVideoStreams.mobile:v.maxVideoStreams.desktop);let D,N,J,C,G,W,oe,se;const Oe=new uO(t);Fe.socketService=t;const Et=new fd(t),O=new tr(t),k=new mO(t),R=Bc.create(t,e),H=new fO(t),Re=new lO(t),Xe=new gi(t),U=yield Vn.init(e,R,h,P,v),M=yield iv.init(e,U.self,R,Oe,g);if(o.participant&&(m===hs.CF&&(se=new Av(e,U.self,R)),se=new Mv(e,U.self,R)),(a=o.e2ee)!=null&&a.enabled&&o.e2ee.manager.init(l,w),o.chat&&(N=yield qr.init(e,O,Xe,U.self,se.participants)),o.internals&&(G=yield Lu.init()),o.livestream&&v.viewType===gt.Livestream&&Q.hasFeature(ie.LIVESTREAM)&&(oe=new pv(U.self,Re)),v.viewType!==gt.Chat){if(o.poll&&(D=yield ev.init(e,U.self,Et)),o.recording&&(W=new cv(e,U.self,R)),o.stage&&(J=new sv(e,k,R,U.self,se.participants)),o.plugin){if(!se)throw new _("The plugin module cannot be initialized without the `participant` module","0102");const Cr=yield n;C=yield za.init(e,Cr,H,O,N==null?void 0:N.chat,U.self,se.participants)}if(o.pip){const Cr=yield Ow._init(e,U.self);e.setValue("pip",Cr)}}const Ze={storesManager:new n1(e,H),pollController:D,selfController:U,metaController:M,chatController:N,stageController:J,pluginController:C,recordingController:W,internalsController:G,livestreamController:oe,participantController:se};return{theme:v,permissions:P,controllers:Ze}})}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 Lv(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 Za=ci;yd([y.trace("Controller.init")],Za,"init",1);yd([y.trace("setupFlagsmith")],Za,"setupFlagsmith",1);yd([y.trace("Controller.createSocketServiceAndRoomNodeClient")],Za,"createRoomNodeClient",1);yd([y.trace("Controller.createSocketService")],Za,"createSocketService",1);var VO=Object.defineProperty,UO=Object.getOwnPropertyDescriptor,BO=(t,e,r,n)=>{for(var i=n>1?void 0:n?UO(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&&VO(e,r,i),i},hc,nu;class ey extends zt{constructor(e,r){super(),T(this,hc,void 0),f(this,"meetings",[]),f(this,"parentMeeting",null),T(this,nu,void 0),S(this,nu,e),S(this,hc,r.self)}get supportsConnectedMeetings(){return c(this,hc).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 Z(B({},s),{participants:a})}if(e===s.id){const a=s.participants.filter(o=>!n.includes(o.id));return Z(B({},s),{participants:a})}return s})}}hc=new WeakMap,nu=new WeakMap;BO([Vt({maxInvocations:60,period:60})],ey.prototype,"getConnectedMeetings",1);var jO=Object.defineProperty,HO=Object.getOwnPropertyDescriptor,Ku=(t,e,r,n)=>{for(var i=n>1?void 0:n?HO(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&&jO(e,r,i),i},la,sr,fl,gl;const In=(fl=class{constructor(t,e,r){f(this,"connectedMeetings"),T(this,la,void 0),T(this,sr,void 0),T(this,gl,void 0),S(this,gl,t),S(this,la,r),this.connectedMeetings=new ey(t,e),this.setCurrentMeeting(e)}static init(t,e,r){return In.instance||(In.instance=new In(t,e,r)),In.instance.connectedMeetings.supportsConnectedMeetings&&(In.instance.setupEvents(),e.self.once("roomJoined",()=>In.instance.getConnectedMeetings())),In.instance}setCurrentMeeting(t){S(this,sr,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,sr).self.videoEnabled,audio:c(this,sr).self.audioEnabled};try{c(this,sr).self.cleanupEvents(),yield c(this,sr).leave("connected-meeting")}catch(h){l.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(i=(n=c(this,sr))==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 ty.init(Z(B({},c(this,la)),{cachedUserDetails:null,defaults:Z(B(B({},c(this,la).defaults),o),{mediaHandler:c(this,sr).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,sr).self;d.self.setName(c(this,sr).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,Z(B({},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})}},la=new WeakMap,sr=new WeakMap,gl=new WeakMap,f(fl,"instance"),fl);let Sd=In;Ku([y.trace("ConnectedMeetingsController.getConnectedMeetings")],Sd.prototype,"getConnectedMeetings",1);Ku([y.trace("ConnectedMeetingsController.setupEvents")],Sd.prototype,"setupEvents",1);Ku([y.trace("ConnectedMeetingsController.switchMeeting")],Sd.prototype,"switchMeeting",1);class WO{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 Cm=new WO;function $O(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 JO=Object.defineProperty,GO=Object.getOwnPropertyDescriptor,Ed=(t,e,r,n)=>{for(var i=n>1?void 0:n?GO(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&&JO(e,r,i),i},ht,No,Lo,vl,Pm,Rm;let Nn=(Rm=class{constructor(t,e){T(this,vl),T(this,ht,void 0),T(this,No,void 0),T(this,Lo,void 0),S(this,Lo,t),S(this,ht,e)}static init(t){return u(this,null,function*(){var e,r,n,i,s;ww(),Ee.init();const a=Ei();Cm.init();const{authToken:o,baseURI:d}=t,h=$O(o,d),{meetingId:p}=h,m=zc(h,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const g=Nn.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:Z(B({},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 Za.init(g),I=new Nn(g,v);return Ke(s=I,vl,Pm).call(s,t),I})}static setupContext(t,e,r,n){var i;const s=hi.createContext(t,e),a=B(B({},Sw),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",Ew({baseURI:n.baseURI})),s.setValue("defaults",e.defaults||{audio:!0,video:!0}),s.setValue("onError",e.onError||(()=>{})),s.setValue("cachedUserDetails",hr(e.cachedUserDetails)),s.setValue("sdkVersion","2.4.4"),s}join(){return u(this,null,function*(){const{selfController:t}=c(this,ht);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){Cm.cleanup();const{selfController:e}=c(this,ht);return e.leaveRoom(t)})}get participants(){var t;return(t=c(this,ht).participantController)==null?void 0:t.participants}get self(){var t;return(t=c(this,ht).selfController)==null?void 0:t.self}get meta(){var t;return(t=c(this,ht).metaController)==null?void 0:t.meta}get ai(){var t;return(t=c(this,ht).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=c(this,ht).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=c(this,ht).chatController)==null?void 0:t.chat}get polls(){var t;return(t=c(this,ht).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=c(this,No))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=c(this,ht).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=c(this,ht).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=c(this,ht).stageController)==null?void 0:t.stage}get stores(){return c(this,ht).storesManager}get __internals__(){var t;return(t=c(this,ht).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)})}},ht=new WeakMap,No=new WeakMap,Lo=new WeakMap,vl=new WeakSet,Pm=function(t){S(this,No,Sd.init(c(this,Lo),this,t))},Rm);Ed([yt("0002"),Fn.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Nn.prototype,"join",1);Ed([yt("0003")],Nn.prototype,"leave",1);Ed([yt("0001"),Fn.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Nn,"init",1);Nn=Ed([yt("0000")],Nn);const ty=Nn;exports.DyteSelfMedia=Ov;exports.default=ty;