@cloudflare/realtimekit 2.2.0-staging.1 → 2.2.0-staging.2
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/EncryptionManager.cjs.js +1 -1
- package/dist/EncryptionManager.d.ts +11 -1
- package/dist/EncryptionManager.es.js +200 -200
- package/dist/browser.js +10 -10
- package/dist/dependencies.txt +1 -1
- package/dist/index.cjs.js +7 -7
- package/dist/index.d.ts +11 -1
- package/dist/index.es.js +2976 -2961
- package/dist/index.es5.js +2242 -2237
- package/dist/index.rn.js +7 -7
- package/dist/ts3.4/dist/EncryptionManager.d.ts +11 -1
- package/dist/ts3.4/dist/index.d.ts +11 -1
- package/package.json +1 -1
package/dist/browser.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
var RealtimeKitClient=function(){var Ho,fr,vr,xS,Lt,ei,gt,os,Le,cs,Sr,je,Ue,ia,na,aa,Tr,oa,zl,qo,Wt,ca,ie,Ji,ot,da,Yl,sT,jo,Wp,$S,Ki,US,Ql,rT,Xl,iT,la,ua,Go,BS,ti,ha,zi,FS,Yi,Wo,Jp,yr,pa,HS,Jo,qS,si,Qi,Jt,jS,ds,Zl,le,Ko,Us,Qe,zo,Kp,ma,eh,ri,Ps,ii,Yo,Et,Xi,Er,Qo,Xo,Zi,GS,Be,en,ks,ga,ni,tn,eu,nT,Zo,zp,ec,Yp,tc,Qp,WS,sc,fa,va,Sa,th,JS,sn,rn,Ge,Ce,be,br,ls,rc,Ve,nn,ic,an,tu,Ta,us,Xe,KS,on,nc,ya,ac,bt,cn,oc,Ea,wa,cc,Pa,ka,wr,Bs,ct,ai,oi,su,aT,ci,di,dc,Xp,lc,_s,ru,oT,_a,Ca,Kt,dn,Ed,li,so,ln,bd,iu,cT,wt,uc,ui,un,wd,Pr,nu,hc,Zp,au,dT,ou,lT,zS,hi,xe,pc,em,hn,Pd,Ra,sh,pn,Vt,YS,hs,Fs,pi,Ze,kr,mn,gn,kd,cu,uT,du,hT,mc,tm,lu,pT,uu,mT,hu,QS,z,Ia,Aa,pu,Pt,es,zt,Ma,kt,Oa,et,_r,Vn,tt,St,Da,rh,Fe,Je,Na,La,gc,sm,XS,fc,vc,Sc,fn,Hs,gu,qs,Pi,Tc,rm,fu,gT,vu,fT,Cs,Va,xa,vn,ps,dt,mi,$a,Su,Yt,As,Ua,st,Cr,Sn,Fa,rt,it,yc,Ec,Tn,Ha,bc,qa,yn,js,Gs,ki,wc,im,Tu,vT,Pc,nm,yu,ST,Eu,TT,bu,yT,wu,ET,Pu,bT,kc,am,Ws,_i,ku,ms,En,Js,_c,Ks,_u,Rr,ja,Cc,om,Cu,wT,Ru,PT,Iu,kT,Au,_T,Rc,Ic,Ac,Ga,Wa,Ja,Mc,Oc,Ka,xt,Rs,Is,bn,wn,Ir,Dc,Mu,CT,Ou,RT,Du,IT,Nu,AT,Nc,Lc,Ar,Mr,Or,Vc,za,Ya,gi,Pn,Qa,kn,Dr,zs,xc,cm,Vu,MT,$c,dm,Uc,lm,xu,OT,Fc,Hc,nt,H,$u,_t,Nr,_n,Cn,qc,Qt,Lr,Ct,Rt,Vr,xn,fi,ro,jc,um,Uu,DT,Bu,NT,Fu,LT,Gc,hm,Hu,VT,qu,xT,lt,Mt,Rn,_d,Wc,pm,ju,$T,Gu,UT,Wu,BT,Xa,gs,te,ft,Ut,ZS,Jc,Kc,zc,xr,Za,Xt,$t,vi,eo,Ys,to,Ie,ut,Ot,Si,Ti,In,An,yi,Qs,Xs,Ei,Mn,It,bi,At,We,Yc,mm,Ju,FT,Ku,HT,zu,qT,Qc,gm,Xc,fm,On,Cd,Yu,qp,jT,Qu,GT,Zc,vm,ed,Sm,td,Tm,Xu,WT,sd,ym,rd,Em,Zt,Se,eT,wi,Dn,Nn,id,Zu,JT,Zs,qe,Ln,tT;"use strict";var vL=Object.defineProperty;var SL=(Ae,Re,Me)=>Re in Ae?vL(Ae,Re,{enumerable:!0,configurable:!0,writable:!0,value:Me}):Ae[Re]=Me;var p=(Ae,Re,Me)=>(SL(Ae,typeof Re!="symbol"?Re+"":Re,Me),Me),Gp=(Ae,Re,Me)=>{if(!Re.has(Ae))throw TypeError("Cannot "+Me)};var a=(Ae,Re,Me)=>(Gp(Ae,Re,"read from private field"),Me?Me.call(Ae):Re.get(Ae)),m=(Ae,Re,Me)=>{if(Re.has(Ae))throw TypeError("Cannot add the same private member more than once");Re instanceof WeakSet?Re.add(Ae):Re.set(Ae,Me)},f=(Ae,Re,Me,Rd)=>(Gp(Ae,Re,"write to private field"),Rd?Rd.call(Ae,Me):Re.set(Ae,Me),Me);var R=(Ae,Re,Me)=>(Gp(Ae,Re,"access private method"),Me);function Ae(s){const{length:t}=this,e=s>=0?s:t+s;return e<0||e>=t?void 0:this[e]}Array.prototype.at||Object.assign(Array.prototype,{at:Ae});function Re(s){const{length:t}=this,e=s>=0?s:t+s;return e<0||e>=t?void 0:this[e]}String.prototype.at||Object.assign(String.prototype,{at:Re});var Me,Rd=new Uint8Array(16);function KT(){if(!Me&&(Me=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!Me))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Me(Rd)}const zT=/^(?:[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 ih(s){return typeof s=="string"&&zT.test(s)}for(var at=[],nh=0;nh<256;++nh)at.push((nh+256).toString(16).substr(1));function YT(s){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(at[s[t+0]]+at[s[t+1]]+at[s[t+2]]+at[s[t+3]]+"-"+at[s[t+4]]+at[s[t+5]]+"-"+at[s[t+6]]+at[s[t+7]]+"-"+at[s[t+8]]+at[s[t+9]]+"-"+at[s[t+10]]+at[s[t+11]]+at[s[t+12]]+at[s[t+13]]+at[s[t+14]]+at[s[t+15]]).toLowerCase();if(!ih(e))throw TypeError("Stringified UUID is invalid");return e}function Ci(s,t,e){s=s||{};var r=s.random||(s.rng||KT)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){e=e||0;for(var i=0;i<16;++i)t[e+i]=r[i];return t}return YT(r)}const QT=s=>{!navigator.isReactNative&&typeof window!="undefined"&&(window.addEventListener("error",t=>{var e;!((e=t.filename)!=null&&e.includes("localhost"))&&t.lineno!==0&&s.error("window::error",{error:t.error},!0)}),window.addEventListener("unhandledrejection",t=>{var e,r,i,n,o,c,d,l;s.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:(n=(i=t==null?void 0:t.reason)==null?void 0:i.config)==null?void 0:n.baseURL,method:(c=(o=t==null?void 0:t.reason)==null?void 0:o.config)==null?void 0:c.method,status:(d=t==null?void 0:t.reason)==null?void 0:d.status,statusText:(l=t==null?void 0:t.reason)==null?void 0:l.statusText}},!0)}),window.addEventListener("offline",()=>{s.info("window::offline")}),window.addEventListener("online",()=>{s.info("window::online")}))},XT={AmazonBot:"amazonbot","Amazon Silk":"amazon_silk","Android Browser":"android",BaiduSpider:"baiduspider",Bada:"bada",BingCrawler:"bingcrawler",Brave:"brave",BlackBerry:"blackberry","ChatGPT-User":"chatgpt_user",Chrome:"chrome",ClaudeBot:"claudebot",Chromium:"chromium",Diffbot:"diffbot",DuckDuckBot:"duckduckbot",DuckDuckGo:"duckduckgo",Electron:"electron",Epiphany:"epiphany",FacebookExternalHit:"facebookexternalhit",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot",GPTBot:"gptbot","Internet Explorer":"ie",InternetArchiveCrawler:"internetarchivecrawler","K-Meleon":"k_meleon",LibreWolf:"librewolf",Linespider:"linespider",Maxthon:"maxthon","Meta-ExternalAds":"meta_externalads","Meta-ExternalAgent":"meta_externalagent","Meta-ExternalFetcher":"meta_externalfetcher","Meta-WebIndexer":"meta_webindexer","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver","OAI-SearchBot":"oai_searchbot",Omgilibot:"omgilibot",Opera:"opera","Opera Coast":"opera_coast","Pale Moon":"pale_moon",PerplexityBot:"perplexitybot","Perplexity-User":"perplexity_user",PhantomJS:"phantomjs",PingdomBot:"pingdombot",Puffin:"puffin",QQ:"qq",QQLite:"qqlite",QupZilla:"qupzilla",Roku:"roku",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SlackBot:"slackbot",SeaMonkey:"seamonkey",Sleipnir:"sleipnir","Sogou Browser":"sogou",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat",YahooSlurp:"yahooslurp","Yandex Browser":"yandex",YandexBot:"yandexbot",YouBot:"youbot"},bm={amazonbot:"AmazonBot",amazon_silk:"Amazon Silk",android:"Android Browser",baiduspider:"BaiduSpider",bada:"Bada",bingcrawler:"BingCrawler",blackberry:"BlackBerry",brave:"Brave",chatgpt_user:"ChatGPT-User",chrome:"Chrome",claudebot:"ClaudeBot",chromium:"Chromium",diffbot:"Diffbot",duckduckbot:"DuckDuckBot",duckduckgo:"DuckDuckGo",edge:"Microsoft Edge",electron:"Electron",epiphany:"Epiphany",facebookexternalhit:"FacebookExternalHit",firefox:"Firefox",focus:"Focus",generic:"Generic",google_search:"Google Search",googlebot:"Googlebot",gptbot:"GPTBot",ie:"Internet Explorer",internetarchivecrawler:"InternetArchiveCrawler",k_meleon:"K-Meleon",librewolf:"LibreWolf",linespider:"Linespider",maxthon:"Maxthon",meta_externalads:"Meta-ExternalAds",meta_externalagent:"Meta-ExternalAgent",meta_externalfetcher:"Meta-ExternalFetcher",meta_webindexer:"Meta-WebIndexer",mz:"MZ Browser",naver:"NAVER Whale Browser",oai_searchbot:"OAI-SearchBot",omgilibot:"Omgilibot",opera:"Opera",opera_coast:"Opera Coast",pale_moon:"Pale Moon",perplexitybot:"PerplexityBot",perplexity_user:"Perplexity-User",phantomjs:"PhantomJS",pingdombot:"PingdomBot",puffin:"Puffin",qq:"QQ Browser",qqlite:"QQ Browser Lite",qupzilla:"QupZilla",roku:"Roku",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",slackbot:"SlackBot",sleipnir:"Sleipnir",sogou:"Sogou Browser",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yahooslurp:"YahooSlurp",yandex:"Yandex Browser",yandexbot:"YandexBot",youbot:"YouBot"},Q={bot:"bot",desktop:"desktop",mobile:"mobile",tablet:"tablet",tv:"tv"},ht={Android:"Android",Bada:"Bada",BlackBerry:"BlackBerry",ChromeOS:"Chrome OS",HarmonyOS:"HarmonyOS",iOS:"iOS",Linux:"Linux",MacOS:"macOS",PlayStation4:"PlayStation 4",Roku:"Roku",Tizen:"Tizen",WebOS:"WebOS",Windows:"Windows",WindowsPhone:"Windows Phone"},$r={Blink:"Blink",EdgeHTML:"EdgeHTML",Gecko:"Gecko",Presto:"Presto",Trident:"Trident",WebKit:"WebKit"};class b{static getFirstMatch(t,e){const r=e.match(t);return r&&r.length>0&&r[1]||""}static getSecondMatch(t,e){const r=e.match(t);return r&&r.length>1&&r[2]||""}static matchAndReturnConst(t,e,r){if(t.test(e))return r}static getWindowsVersionName(t){switch(t){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(t){const e=t.split(".").splice(0,2).map(n=>parseInt(n,10)||0);e.push(0);const r=e[0],i=e[1];if(r===10)switch(i){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}switch(r){case 11:return"Big Sur";case 12:return"Monterey";case 13:return"Ventura";case 14:return"Sonoma";case 15:return"Sequoia";default:return}}static getAndroidVersionName(t){const e=t.split(".").splice(0,2).map(r=>parseInt(r,10)||0);if(e.push(0),!(e[0]===1&&e[1]<5)){if(e[0]===1&&e[1]<6)return"Cupcake";if(e[0]===1&&e[1]>=6)return"Donut";if(e[0]===2&&e[1]<2)return"Eclair";if(e[0]===2&&e[1]===2)return"Froyo";if(e[0]===2&&e[1]>2)return"Gingerbread";if(e[0]===3)return"Honeycomb";if(e[0]===4&&e[1]<1)return"Ice Cream Sandwich";if(e[0]===4&&e[1]<4)return"Jelly Bean";if(e[0]===4&&e[1]>=4)return"KitKat";if(e[0]===5)return"Lollipop";if(e[0]===6)return"Marshmallow";if(e[0]===7)return"Nougat";if(e[0]===8)return"Oreo";if(e[0]===9)return"Pie"}}static getVersionPrecision(t){return t.split(".").length}static compareVersions(t,e,r=!1){const i=b.getVersionPrecision(t),n=b.getVersionPrecision(e);let o=Math.max(i,n),c=0;const d=b.map([t,e],l=>{const u=o-b.getVersionPrecision(l),h=l+new Array(u+1).join(".0");return b.map(h.split("."),g=>new Array(20-g.length).join("0")+g).reverse()});for(r&&(c=o-Math.min(i,n)),o-=1;o>=c;){if(d[0][o]>d[1][o])return 1;if(d[0][o]===d[1][o]){if(o===c)return 0;o-=1}else if(d[0][o]<d[1][o])return-1}}static map(t,e){const r=[];let i;if(Array.prototype.map)return Array.prototype.map.call(t,e);for(i=0;i<t.length;i+=1)r.push(e(t[i]));return r}static find(t,e){let r,i;if(Array.prototype.find)return Array.prototype.find.call(t,e);for(r=0,i=t.length;r<i;r+=1){const n=t[r];if(e(n,r))return n}}static assign(t,...e){const r=t;let i,n;if(Object.assign)return Object.assign(t,...e);for(i=0,n=e.length;i<n;i+=1){const o=e[i];typeof o=="object"&&o!==null&&Object.keys(o).forEach(d=>{r[d]=o[d]})}return t}static getBrowserAlias(t){return XT[t]}static getBrowserTypeByAlias(t){return bm[t]||""}}const X=/version\/(\d+(\.?_?\d+)+)/i,ZT=[{test:[/gptbot/i],describe(s){const t={name:"GPTBot"},e=b.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/chatgpt-user/i],describe(s){const t={name:"ChatGPT-User"},e=b.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/oai-searchbot/i],describe(s){const t={name:"OAI-SearchBot"},e=b.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe(s){const t={name:"ClaudeBot"},e=b.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/omgilibot/i,/webzio-extended/i],describe(s){const t={name:"Omgilibot"},e=b.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/diffbot/i],describe(s){const t={name:"Diffbot"},e=b.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/perplexitybot/i],describe(s){const t={name:"PerplexityBot"},e=b.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/perplexity-user/i],describe(s){const t={name:"Perplexity-User"},e=b.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/youbot/i],describe(s){const t={name:"YouBot"},e=b.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/meta-webindexer/i],describe(s){const t={name:"Meta-WebIndexer"},e=b.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/meta-externalads/i],describe(s){const t={name:"Meta-ExternalAds"},e=b.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/meta-externalagent/i],describe(s){const t={name:"Meta-ExternalAgent"},e=b.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/meta-externalfetcher/i],describe(s){const t={name:"Meta-ExternalFetcher"},e=b.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/googlebot/i],describe(s){const t={name:"Googlebot"},e=b.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/linespider/i],describe(s){const t={name:"Linespider"},e=b.getFirstMatch(/(?:linespider)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/amazonbot/i],describe(s){const t={name:"AmazonBot"},e=b.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/bingbot/i],describe(s){const t={name:"BingCrawler"},e=b.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/baiduspider/i],describe(s){const t={name:"BaiduSpider"},e=b.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/duckduckbot/i],describe(s){const t={name:"DuckDuckBot"},e=b.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/ia_archiver/i],describe(s){const t={name:"InternetArchiveCrawler"},e=b.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe(){return{name:"FacebookExternalHit"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe(s){const t={name:"SlackBot"},e=b.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/yahoo!?[\s/]*slurp/i],describe(){return{name:"YahooSlurp"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe(){return{name:"YandexBot"}}},{test:[/pingdom/i],describe(){return{name:"PingdomBot"}}},{test:[/opera/i],describe(s){const t={name:"Opera"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/opr\/|opios/i],describe(s){const t={name:"Opera"},e=b.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/SamsungBrowser/i],describe(s){const t={name:"Samsung Internet for Android"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/Whale/i],describe(s){const t={name:"NAVER Whale Browser"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/PaleMoon/i],describe(s){const t={name:"Pale Moon"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/MZBrowser/i],describe(s){const t={name:"MZ Browser"},e=b.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/focus/i],describe(s){const t={name:"Focus"},e=b.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/swing/i],describe(s){const t={name:"Swing"},e=b.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/coast/i],describe(s){const t={name:"Opera Coast"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(s){const t={name:"Opera Touch"},e=b.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/yabrowser/i],describe(s){const t={name:"Yandex Browser"},e=b.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/ucbrowser/i],describe(s){const t={name:"UC Browser"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/Maxthon|mxios/i],describe(s){const t={name:"Maxthon"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/epiphany/i],describe(s){const t={name:"Epiphany"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/puffin/i],describe(s){const t={name:"Puffin"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/sleipnir/i],describe(s){const t={name:"Sleipnir"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/k-meleon/i],describe(s){const t={name:"K-Meleon"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/micromessenger/i],describe(s){const t={name:"WeChat"},e=b.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/qqbrowser/i],describe(s){const t={name:/qqbrowserlite/i.test(s)?"QQ Browser Lite":"QQ Browser"},e=b.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/msie|trident/i],describe(s){const t={name:"Internet Explorer"},e=b.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/\sedg\//i],describe(s){const t={name:"Microsoft Edge"},e=b.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/edg([ea]|ios)/i],describe(s){const t={name:"Microsoft Edge"},e=b.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/vivaldi/i],describe(s){const t={name:"Vivaldi"},e=b.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/seamonkey/i],describe(s){const t={name:"SeaMonkey"},e=b.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/sailfish/i],describe(s){const t={name:"Sailfish"},e=b.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,s);return e&&(t.version=e),t}},{test:[/silk/i],describe(s){const t={name:"Amazon Silk"},e=b.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/phantom/i],describe(s){const t={name:"PhantomJS"},e=b.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/slimerjs/i],describe(s){const t={name:"SlimerJS"},e=b.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(s){const t={name:"BlackBerry"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/(web|hpw)[o0]s/i],describe(s){const t={name:"WebOS Browser"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/bada/i],describe(s){const t={name:"Bada"},e=b.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/tizen/i],describe(s){const t={name:"Tizen"},e=b.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/qupzilla/i],describe(s){const t={name:"QupZilla"},e=b.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/librewolf/i],describe(s){const t={name:"LibreWolf"},e=b.getFirstMatch(/(?:librewolf)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/firefox|iceweasel|fxios/i],describe(s){const t={name:"Firefox"},e=b.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/electron/i],describe(s){const t={name:"Electron"},e=b.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/sogoumobilebrowser/i,/metasr/i,/se 2\.[x]/i],describe(s){const t={name:"Sogou Browser"},e=b.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,s),r=b.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,s),i=b.getFirstMatch(/se ([\d.]+)x/i,s),n=e||r||i;return n&&(t.version=n),t}},{test:[/MiuiBrowser/i],describe(s){const t={name:"Miui"},e=b.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test(s){return s.hasBrand("DuckDuckGo")?!0:s.test(/\sDdg\/[\d.]+$/i)},describe(s,t){const e={name:"DuckDuckGo"};if(t){const i=t.getBrandVersion("DuckDuckGo");if(i)return e.version=i,e}const r=b.getFirstMatch(/\sDdg\/([\d.]+)$/i,s);return r&&(e.version=r),e}},{test(s){return s.hasBrand("Brave")},describe(s,t){const e={name:"Brave"};if(t){const r=t.getBrandVersion("Brave");if(r)return e.version=r,e}return e}},{test:[/chromium/i],describe(s){const t={name:"Chromium"},e=b.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/chrome|crios|crmo/i],describe(s){const t={name:"Chrome"},e=b.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/GSA/i],describe(s){const t={name:"Google Search"},e=b.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test(s){const t=!s.test(/like android/i),e=s.test(/android/i);return t&&e},describe(s){const t={name:"Android Browser"},e=b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/playstation 4/i],describe(s){const t={name:"PlayStation 4"},e=b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/safari|applewebkit/i],describe(s){const t={name:"Safari"},e=b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/.*/i],describe(s){const t=/^(.*)\/(.*) /,e=/^(.*)\/(.*)[ \t]\((.*)/,i=s.search("\\(")!==-1?e:t;return{name:b.getFirstMatch(i,s),version:b.getSecondMatch(i,s)}}}],ey=[{test:[/Roku\/DVP/],describe(s){const t=b.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,s);return{name:ht.Roku,version:t}}},{test:[/windows phone/i],describe(s){const t=b.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,s);return{name:ht.WindowsPhone,version:t}}},{test:[/windows /i],describe(s){const t=b.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,s),e=b.getWindowsVersionName(t);return{name:ht.Windows,version:t,versionName:e}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(s){const t={name:ht.iOS},e=b.getSecondMatch(/(Version\/)(\d[\d.]+)/,s);return e&&(t.version=e),t}},{test:[/macintosh/i],describe(s){const t=b.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,s).replace(/[_\s]/g,"."),e=b.getMacOSVersionName(t),r={name:ht.MacOS,version:t};return e&&(r.versionName=e),r}},{test:[/(ipod|iphone|ipad)/i],describe(s){const t=b.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,s).replace(/[_\s]/g,".");return{name:ht.iOS,version:t}}},{test:[/OpenHarmony/i],describe(s){const t=b.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,s);return{name:ht.HarmonyOS,version:t}}},{test(s){const t=!s.test(/like android/i),e=s.test(/android/i);return t&&e},describe(s){const t=b.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,s),e=b.getAndroidVersionName(t),r={name:ht.Android,version:t};return e&&(r.versionName=e),r}},{test:[/(web|hpw)[o0]s/i],describe(s){const t=b.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,s),e={name:ht.WebOS};return t&&t.length&&(e.version=t),e}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(s){const t=b.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,s)||b.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,s)||b.getFirstMatch(/\bbb(\d+)/i,s);return{name:ht.BlackBerry,version:t}}},{test:[/bada/i],describe(s){const t=b.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,s);return{name:ht.Bada,version:t}}},{test:[/tizen/i],describe(s){const t=b.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,s);return{name:ht.Tizen,version:t}}},{test:[/linux/i],describe(){return{name:ht.Linux}}},{test:[/CrOS/],describe(){return{name:ht.ChromeOS}}},{test:[/PlayStation 4/],describe(s){const t=b.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,s);return{name:ht.PlayStation4,version:t}}}],ty=[{test:[/googlebot/i],describe(){return{type:Q.bot,vendor:"Google"}}},{test:[/linespider/i],describe(){return{type:Q.bot,vendor:"Line"}}},{test:[/amazonbot/i],describe(){return{type:Q.bot,vendor:"Amazon"}}},{test:[/gptbot/i],describe(){return{type:Q.bot,vendor:"OpenAI"}}},{test:[/chatgpt-user/i],describe(){return{type:Q.bot,vendor:"OpenAI"}}},{test:[/oai-searchbot/i],describe(){return{type:Q.bot,vendor:"OpenAI"}}},{test:[/baiduspider/i],describe(){return{type:Q.bot,vendor:"Baidu"}}},{test:[/bingbot/i],describe(){return{type:Q.bot,vendor:"Bing"}}},{test:[/duckduckbot/i],describe(){return{type:Q.bot,vendor:"DuckDuckGo"}}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe(){return{type:Q.bot,vendor:"Anthropic"}}},{test:[/omgilibot/i,/webzio-extended/i],describe(){return{type:Q.bot,vendor:"Webz.io"}}},{test:[/diffbot/i],describe(){return{type:Q.bot,vendor:"Diffbot"}}},{test:[/perplexitybot/i],describe(){return{type:Q.bot,vendor:"Perplexity AI"}}},{test:[/perplexity-user/i],describe(){return{type:Q.bot,vendor:"Perplexity AI"}}},{test:[/youbot/i],describe(){return{type:Q.bot,vendor:"You.com"}}},{test:[/ia_archiver/i],describe(){return{type:Q.bot,vendor:"Internet Archive"}}},{test:[/meta-webindexer/i],describe(){return{type:Q.bot,vendor:"Meta"}}},{test:[/meta-externalads/i],describe(){return{type:Q.bot,vendor:"Meta"}}},{test:[/meta-externalagent/i],describe(){return{type:Q.bot,vendor:"Meta"}}},{test:[/meta-externalfetcher/i],describe(){return{type:Q.bot,vendor:"Meta"}}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe(){return{type:Q.bot,vendor:"Meta"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe(){return{type:Q.bot,vendor:"Slack"}}},{test:[/yahoo/i],describe(){return{type:Q.bot,vendor:"Yahoo"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe(){return{type:Q.bot,vendor:"Yandex"}}},{test:[/pingdom/i],describe(){return{type:Q.bot,vendor:"Pingdom"}}},{test:[/huawei/i],describe(s){const t=b.getFirstMatch(/(can-l01)/i,s)&&"Nova",e={type:Q.mobile,vendor:"Huawei"};return t&&(e.model=t),e}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe(){return{type:Q.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe(){return{type:Q.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(){return{type:Q.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe(){return{type:Q.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe(){return{type:Q.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe(){return{type:Q.tablet}}},{test(s){const t=s.test(/ipod|iphone/i),e=s.test(/like (ipod|iphone)/i);return t&&!e},describe(s){const t=b.getFirstMatch(/(ipod|iphone)/i,s);return{type:Q.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe(){return{type:Q.mobile,vendor:"Nexus"}}},{test:[/Nokia/i],describe(s){const t=b.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,s),e={type:Q.mobile,vendor:"Nokia"};return t&&(e.model=t),e}},{test:[/[^-]mobi/i],describe(){return{type:Q.mobile}}},{test(s){return s.getBrowserName(!0)==="blackberry"},describe(){return{type:Q.mobile,vendor:"BlackBerry"}}},{test(s){return s.getBrowserName(!0)==="bada"},describe(){return{type:Q.mobile}}},{test(s){return s.getBrowserName()==="windows phone"},describe(){return{type:Q.mobile,vendor:"Microsoft"}}},{test(s){const t=Number(String(s.getOSVersion()).split(".")[0]);return s.getOSName(!0)==="android"&&t>=3},describe(){return{type:Q.tablet}}},{test(s){return s.getOSName(!0)==="android"},describe(){return{type:Q.mobile}}},{test:[/smart-?tv|smarttv/i],describe(){return{type:Q.tv}}},{test:[/netcast/i],describe(){return{type:Q.tv}}},{test(s){return s.getOSName(!0)==="macos"},describe(){return{type:Q.desktop,vendor:"Apple"}}},{test(s){return s.getOSName(!0)==="windows"},describe(){return{type:Q.desktop}}},{test(s){return s.getOSName(!0)==="linux"},describe(){return{type:Q.desktop}}},{test(s){return s.getOSName(!0)==="playstation 4"},describe(){return{type:Q.tv}}},{test(s){return s.getOSName(!0)==="roku"},describe(){return{type:Q.tv}}}],sy=[{test(s){return s.getBrowserName(!0)==="microsoft edge"},describe(s){if(/\sedg\//i.test(s))return{name:$r.Blink};const e=b.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,s);return{name:$r.EdgeHTML,version:e}}},{test:[/trident/i],describe(s){const t={name:$r.Trident},e=b.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test(s){return s.test(/presto/i)},describe(s){const t={name:$r.Presto},e=b.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test(s){const t=s.test(/gecko/i),e=s.test(/like gecko/i);return t&&!e},describe(s){const t={name:$r.Gecko},e=b.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:$r.Blink}}},{test:[/(apple)?webkit/i],describe(s){const t={name:$r.WebKit},e=b.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}}];class wm{constructor(t,e=!1,r=null){if(t==null||t==="")throw new Error("UserAgent parameter can't be empty");this._ua=t;let i=!1;typeof e=="boolean"?(i=e,this._hints=r):e!=null&&typeof e=="object"?this._hints=e:this._hints=null,this.parsedResult={},i!==!0&&this.parse()}getHints(){return this._hints}hasBrand(t){if(!this._hints||!Array.isArray(this._hints.brands))return!1;const e=t.toLowerCase();return this._hints.brands.some(r=>r.brand&&r.brand.toLowerCase()===e)}getBrandVersion(t){if(!this._hints||!Array.isArray(this._hints.brands))return;const e=t.toLowerCase(),r=this._hints.brands.find(i=>i.brand&&i.brand.toLowerCase()===e);return r?r.version:void 0}getUA(){return this._ua}test(t){return t.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const t=b.find(ZT,e=>{if(typeof e.test=="function")return e.test(this);if(Array.isArray(e.test))return e.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.browser=t.describe(this.getUA(),this)),this.parsedResult.browser}getBrowser(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()}getBrowserName(t){return t?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 t=b.find(ey,e=>{if(typeof e.test=="function")return e.test(this);if(Array.isArray(e.test))return e.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.os=t.describe(this.getUA())),this.parsedResult.os}getOSName(t){const{name:e}=this.getOS();return t?String(e).toLowerCase()||"":e||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(t=!1){const{type:e}=this.getPlatform();return t?String(e).toLowerCase()||"":e||""}parsePlatform(){this.parsedResult.platform={};const t=b.find(ty,e=>{if(typeof e.test=="function")return e.test(this);if(Array.isArray(e.test))return e.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.platform=t.describe(this.getUA())),this.parsedResult.platform}getEngine(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()}getEngineName(t){return t?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""}parseEngine(){this.parsedResult.engine={};const t=b.find(sy,e=>{if(typeof e.test=="function")return e.test(this);if(Array.isArray(e.test))return e.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.engine=t.describe(this.getUA())),this.parsedResult.engine}parse(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this}getResult(){return b.assign({},this.parsedResult)}satisfies(t){const e={};let r=0;const i={};let n=0;if(Object.keys(t).forEach(c=>{const d=t[c];typeof d=="string"?(i[c]=d,n+=1):typeof d=="object"&&(e[c]=d,r+=1)}),r>0){const c=Object.keys(e),d=b.find(c,u=>this.isOS(u));if(d){const u=this.satisfies(e[d]);if(u!==void 0)return u}const l=b.find(c,u=>this.isPlatform(u));if(l){const u=this.satisfies(e[l]);if(u!==void 0)return u}}if(n>0){const c=Object.keys(i),d=b.find(c,l=>this.isBrowser(l,!0));if(d!==void 0)return this.compareVersion(i[d])}}isBrowser(t,e=!1){const r=this.getBrowserName().toLowerCase();let i=t.toLowerCase();const n=b.getBrowserTypeByAlias(i);return e&&n&&(i=n.toLowerCase()),i===r}compareVersion(t){let e=[0],r=t,i=!1;const n=this.getBrowserVersion();if(typeof n=="string")return t[0]===">"||t[0]==="<"?(r=t.substr(1),t[1]==="="?(i=!0,r=t.substr(2)):e=[],t[0]===">"?e.push(1):e.push(-1)):t[0]==="="?r=t.substr(1):t[0]==="~"&&(i=!0,r=t.substr(1)),e.indexOf(b.compareVersions(n,r,i))>-1}isOS(t){return this.getOSName(!0)===String(t).toLowerCase()}isPlatform(t){return this.getPlatformType(!0)===String(t).toLowerCase()}isEngine(t){return this.getEngineName(!0)===String(t).toLowerCase()}is(t,e=!1){return this.isBrowser(t,e)||this.isOS(t)||this.isPlatform(t)}some(t=[]){return t.some(e=>this.is(e))}}/*!
|
|
1
|
+
var RealtimeKitClient=function(){var Ho,fr,vr,US,Lt,ei,gt,os,Le,cs,Sr,je,Ue,ia,na,aa,Tr,oa,Yl,qo,Wt,ca,ie,Ji,ot,da,Ql,iT,jo,Kp,BS,Ki,FS,Xl,nT,Zl,aT,la,ua,Go,HS,ti,ha,zi,qS,Yi,Wo,zp,yr,pa,jS,Jo,GS,si,Qi,Jt,WS,ds,eu,le,Ko,Us,Qe,zo,Yp,ma,th,ri,Ps,ii,Yo,Et,Xi,Er,Qo,Xo,Zi,JS,Be,en,ks,ga,ni,tn,tu,oT,Zo,Qp,ec,Xp,tc,Zp,KS,sc,fa,va,Sa,sh,zS,sn,rn,rc,Ge,Ce,be,br,ls,ic,Ve,nn,nc,an,su,Ta,us,Xe,YS,on,ac,ya,oc,bt,cn,cc,Ea,wa,dc,Pa,ka,wr,Bs,ct,ai,oi,ru,cT,ci,di,lc,em,uc,_s,iu,dT,_a,Ca,Kt,dn,bd,li,so,ln,wd,nu,lT,wt,hc,ui,un,Pd,Pr,au,pc,tm,ou,uT,cu,hT,QS,hi,xe,mc,sm,hn,kd,Ra,rh,pn,Vt,XS,hs,Fs,pi,Ze,kr,mn,gn,_d,du,pT,lu,mT,gc,rm,uu,gT,hu,fT,pu,ZS,z,Ia,Aa,mu,Pt,es,zt,Ma,kt,Oa,et,_r,Vn,tt,St,Da,ih,Fe,Je,Na,La,fc,im,eT,vc,Sc,Tc,fn,Hs,fu,qs,Pi,yc,nm,vu,vT,Su,ST,Cs,Va,xa,vn,ps,dt,mi,$a,Tu,Yt,As,Ua,st,Cr,Sn,Fa,rt,it,Ec,bc,Tn,Ha,wc,qa,yn,js,Gs,ki,Pc,am,yu,TT,kc,om,Eu,yT,bu,ET,wu,bT,Pu,wT,ku,PT,_c,cm,Ws,_i,_u,ms,En,Js,Cc,Ks,Cu,Rr,ja,Rc,dm,Ru,kT,Iu,_T,Au,CT,Mu,RT,Ic,Ac,Mc,Ga,Wa,Ja,Oc,Dc,Ka,xt,Rs,Is,bn,wn,Ir,Nc,Ou,IT,Du,AT,Nu,MT,Lu,OT,Lc,Vc,Ar,Mr,Or,xc,za,Ya,gi,Pn,Qa,kn,Dr,zs,$c,lm,xu,DT,Uc,um,Bc,hm,$u,NT,Hc,qc,nt,H,Uu,_t,Nr,_n,Cn,jc,Qt,Lr,Ct,Rt,Vr,xn,fi,ro,Gc,pm,Bu,LT,Fu,VT,Hu,xT,Wc,mm,qu,$T,ju,UT,lt,Mt,Rn,Cd,Jc,gm,Gu,BT,Wu,FT,Ju,HT,Xa,gs,te,ft,Ut,tT,Kc,zc,Yc,xr,Za,Xt,$t,vi,eo,Ys,to,Ie,ut,Ot,Si,Ti,In,An,yi,Qs,Xs,Ei,Mn,It,bi,At,We,Qc,fm,Ku,qT,zu,jT,Yu,GT,Xc,vm,Zc,Sm,On,Rd,Qu,Gp,WT,Xu,JT,ed,Tm,td,ym,sd,Em,Zu,KT,rd,bm,id,wm,Zt,Se,sT,wi,Dn,Nn,nd,eh,zT,Zs,qe,Ln,rT;"use strict";var TL=Object.defineProperty;var yL=(Ae,Re,Me)=>Re in Ae?TL(Ae,Re,{enumerable:!0,configurable:!0,writable:!0,value:Me}):Ae[Re]=Me;var p=(Ae,Re,Me)=>(yL(Ae,typeof Re!="symbol"?Re+"":Re,Me),Me),Jp=(Ae,Re,Me)=>{if(!Re.has(Ae))throw TypeError("Cannot "+Me)};var a=(Ae,Re,Me)=>(Jp(Ae,Re,"read from private field"),Me?Me.call(Ae):Re.get(Ae)),m=(Ae,Re,Me)=>{if(Re.has(Ae))throw TypeError("Cannot add the same private member more than once");Re instanceof WeakSet?Re.add(Ae):Re.set(Ae,Me)},f=(Ae,Re,Me,Id)=>(Jp(Ae,Re,"write to private field"),Id?Id.call(Ae,Me):Re.set(Ae,Me),Me);var R=(Ae,Re,Me)=>(Jp(Ae,Re,"access private method"),Me);function Ae(s){const{length:t}=this,e=s>=0?s:t+s;return e<0||e>=t?void 0:this[e]}Array.prototype.at||Object.assign(Array.prototype,{at:Ae});function Re(s){const{length:t}=this,e=s>=0?s:t+s;return e<0||e>=t?void 0:this[e]}String.prototype.at||Object.assign(String.prototype,{at:Re});var Me,Id=new Uint8Array(16);function YT(){if(!Me&&(Me=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!Me))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Me(Id)}const QT=/^(?:[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 nh(s){return typeof s=="string"&&QT.test(s)}for(var at=[],ah=0;ah<256;++ah)at.push((ah+256).toString(16).substr(1));function XT(s){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(at[s[t+0]]+at[s[t+1]]+at[s[t+2]]+at[s[t+3]]+"-"+at[s[t+4]]+at[s[t+5]]+"-"+at[s[t+6]]+at[s[t+7]]+"-"+at[s[t+8]]+at[s[t+9]]+"-"+at[s[t+10]]+at[s[t+11]]+at[s[t+12]]+at[s[t+13]]+at[s[t+14]]+at[s[t+15]]).toLowerCase();if(!nh(e))throw TypeError("Stringified UUID is invalid");return e}function Ci(s,t,e){s=s||{};var r=s.random||(s.rng||YT)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){e=e||0;for(var i=0;i<16;++i)t[e+i]=r[i];return t}return XT(r)}const ZT=s=>{!navigator.isReactNative&&typeof window!="undefined"&&(window.addEventListener("error",t=>{var e;!((e=t.filename)!=null&&e.includes("localhost"))&&t.lineno!==0&&s.error("window::error",{error:t.error},!0)}),window.addEventListener("unhandledrejection",t=>{var e,r,i,n,o,c,d,l;s.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:(n=(i=t==null?void 0:t.reason)==null?void 0:i.config)==null?void 0:n.baseURL,method:(c=(o=t==null?void 0:t.reason)==null?void 0:o.config)==null?void 0:c.method,status:(d=t==null?void 0:t.reason)==null?void 0:d.status,statusText:(l=t==null?void 0:t.reason)==null?void 0:l.statusText}},!0)}),window.addEventListener("offline",()=>{s.info("window::offline")}),window.addEventListener("online",()=>{s.info("window::online")}))},ey={AmazonBot:"amazonbot","Amazon Silk":"amazon_silk","Android Browser":"android",BaiduSpider:"baiduspider",Bada:"bada",BingCrawler:"bingcrawler",Brave:"brave",BlackBerry:"blackberry","ChatGPT-User":"chatgpt_user",Chrome:"chrome",ClaudeBot:"claudebot",Chromium:"chromium",Diffbot:"diffbot",DuckDuckBot:"duckduckbot",DuckDuckGo:"duckduckgo",Electron:"electron",Epiphany:"epiphany",FacebookExternalHit:"facebookexternalhit",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot",GPTBot:"gptbot","Internet Explorer":"ie",InternetArchiveCrawler:"internetarchivecrawler","K-Meleon":"k_meleon",LibreWolf:"librewolf",Linespider:"linespider",Maxthon:"maxthon","Meta-ExternalAds":"meta_externalads","Meta-ExternalAgent":"meta_externalagent","Meta-ExternalFetcher":"meta_externalfetcher","Meta-WebIndexer":"meta_webindexer","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver","OAI-SearchBot":"oai_searchbot",Omgilibot:"omgilibot",Opera:"opera","Opera Coast":"opera_coast","Pale Moon":"pale_moon",PerplexityBot:"perplexitybot","Perplexity-User":"perplexity_user",PhantomJS:"phantomjs",PingdomBot:"pingdombot",Puffin:"puffin",QQ:"qq",QQLite:"qqlite",QupZilla:"qupzilla",Roku:"roku",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SlackBot:"slackbot",SeaMonkey:"seamonkey",Sleipnir:"sleipnir","Sogou Browser":"sogou",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat",YahooSlurp:"yahooslurp","Yandex Browser":"yandex",YandexBot:"yandexbot",YouBot:"youbot"},Pm={amazonbot:"AmazonBot",amazon_silk:"Amazon Silk",android:"Android Browser",baiduspider:"BaiduSpider",bada:"Bada",bingcrawler:"BingCrawler",blackberry:"BlackBerry",brave:"Brave",chatgpt_user:"ChatGPT-User",chrome:"Chrome",claudebot:"ClaudeBot",chromium:"Chromium",diffbot:"Diffbot",duckduckbot:"DuckDuckBot",duckduckgo:"DuckDuckGo",edge:"Microsoft Edge",electron:"Electron",epiphany:"Epiphany",facebookexternalhit:"FacebookExternalHit",firefox:"Firefox",focus:"Focus",generic:"Generic",google_search:"Google Search",googlebot:"Googlebot",gptbot:"GPTBot",ie:"Internet Explorer",internetarchivecrawler:"InternetArchiveCrawler",k_meleon:"K-Meleon",librewolf:"LibreWolf",linespider:"Linespider",maxthon:"Maxthon",meta_externalads:"Meta-ExternalAds",meta_externalagent:"Meta-ExternalAgent",meta_externalfetcher:"Meta-ExternalFetcher",meta_webindexer:"Meta-WebIndexer",mz:"MZ Browser",naver:"NAVER Whale Browser",oai_searchbot:"OAI-SearchBot",omgilibot:"Omgilibot",opera:"Opera",opera_coast:"Opera Coast",pale_moon:"Pale Moon",perplexitybot:"PerplexityBot",perplexity_user:"Perplexity-User",phantomjs:"PhantomJS",pingdombot:"PingdomBot",puffin:"Puffin",qq:"QQ Browser",qqlite:"QQ Browser Lite",qupzilla:"QupZilla",roku:"Roku",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",slackbot:"SlackBot",sleipnir:"Sleipnir",sogou:"Sogou Browser",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yahooslurp:"YahooSlurp",yandex:"Yandex Browser",yandexbot:"YandexBot",youbot:"YouBot"},Q={bot:"bot",desktop:"desktop",mobile:"mobile",tablet:"tablet",tv:"tv"},ht={Android:"Android",Bada:"Bada",BlackBerry:"BlackBerry",ChromeOS:"Chrome OS",HarmonyOS:"HarmonyOS",iOS:"iOS",Linux:"Linux",MacOS:"macOS",PlayStation4:"PlayStation 4",Roku:"Roku",Tizen:"Tizen",WebOS:"WebOS",Windows:"Windows",WindowsPhone:"Windows Phone"},$r={Blink:"Blink",EdgeHTML:"EdgeHTML",Gecko:"Gecko",Presto:"Presto",Trident:"Trident",WebKit:"WebKit"};class b{static getFirstMatch(t,e){const r=e.match(t);return r&&r.length>0&&r[1]||""}static getSecondMatch(t,e){const r=e.match(t);return r&&r.length>1&&r[2]||""}static matchAndReturnConst(t,e,r){if(t.test(e))return r}static getWindowsVersionName(t){switch(t){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(t){const e=t.split(".").splice(0,2).map(n=>parseInt(n,10)||0);e.push(0);const r=e[0],i=e[1];if(r===10)switch(i){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}switch(r){case 11:return"Big Sur";case 12:return"Monterey";case 13:return"Ventura";case 14:return"Sonoma";case 15:return"Sequoia";default:return}}static getAndroidVersionName(t){const e=t.split(".").splice(0,2).map(r=>parseInt(r,10)||0);if(e.push(0),!(e[0]===1&&e[1]<5)){if(e[0]===1&&e[1]<6)return"Cupcake";if(e[0]===1&&e[1]>=6)return"Donut";if(e[0]===2&&e[1]<2)return"Eclair";if(e[0]===2&&e[1]===2)return"Froyo";if(e[0]===2&&e[1]>2)return"Gingerbread";if(e[0]===3)return"Honeycomb";if(e[0]===4&&e[1]<1)return"Ice Cream Sandwich";if(e[0]===4&&e[1]<4)return"Jelly Bean";if(e[0]===4&&e[1]>=4)return"KitKat";if(e[0]===5)return"Lollipop";if(e[0]===6)return"Marshmallow";if(e[0]===7)return"Nougat";if(e[0]===8)return"Oreo";if(e[0]===9)return"Pie"}}static getVersionPrecision(t){return t.split(".").length}static compareVersions(t,e,r=!1){const i=b.getVersionPrecision(t),n=b.getVersionPrecision(e);let o=Math.max(i,n),c=0;const d=b.map([t,e],l=>{const u=o-b.getVersionPrecision(l),h=l+new Array(u+1).join(".0");return b.map(h.split("."),g=>new Array(20-g.length).join("0")+g).reverse()});for(r&&(c=o-Math.min(i,n)),o-=1;o>=c;){if(d[0][o]>d[1][o])return 1;if(d[0][o]===d[1][o]){if(o===c)return 0;o-=1}else if(d[0][o]<d[1][o])return-1}}static map(t,e){const r=[];let i;if(Array.prototype.map)return Array.prototype.map.call(t,e);for(i=0;i<t.length;i+=1)r.push(e(t[i]));return r}static find(t,e){let r,i;if(Array.prototype.find)return Array.prototype.find.call(t,e);for(r=0,i=t.length;r<i;r+=1){const n=t[r];if(e(n,r))return n}}static assign(t,...e){const r=t;let i,n;if(Object.assign)return Object.assign(t,...e);for(i=0,n=e.length;i<n;i+=1){const o=e[i];typeof o=="object"&&o!==null&&Object.keys(o).forEach(d=>{r[d]=o[d]})}return t}static getBrowserAlias(t){return ey[t]}static getBrowserTypeByAlias(t){return Pm[t]||""}}const X=/version\/(\d+(\.?_?\d+)+)/i,ty=[{test:[/gptbot/i],describe(s){const t={name:"GPTBot"},e=b.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/chatgpt-user/i],describe(s){const t={name:"ChatGPT-User"},e=b.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/oai-searchbot/i],describe(s){const t={name:"OAI-SearchBot"},e=b.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe(s){const t={name:"ClaudeBot"},e=b.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/omgilibot/i,/webzio-extended/i],describe(s){const t={name:"Omgilibot"},e=b.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/diffbot/i],describe(s){const t={name:"Diffbot"},e=b.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/perplexitybot/i],describe(s){const t={name:"PerplexityBot"},e=b.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/perplexity-user/i],describe(s){const t={name:"Perplexity-User"},e=b.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/youbot/i],describe(s){const t={name:"YouBot"},e=b.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/meta-webindexer/i],describe(s){const t={name:"Meta-WebIndexer"},e=b.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/meta-externalads/i],describe(s){const t={name:"Meta-ExternalAds"},e=b.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/meta-externalagent/i],describe(s){const t={name:"Meta-ExternalAgent"},e=b.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/meta-externalfetcher/i],describe(s){const t={name:"Meta-ExternalFetcher"},e=b.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/googlebot/i],describe(s){const t={name:"Googlebot"},e=b.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/linespider/i],describe(s){const t={name:"Linespider"},e=b.getFirstMatch(/(?:linespider)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/amazonbot/i],describe(s){const t={name:"AmazonBot"},e=b.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/bingbot/i],describe(s){const t={name:"BingCrawler"},e=b.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/baiduspider/i],describe(s){const t={name:"BaiduSpider"},e=b.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/duckduckbot/i],describe(s){const t={name:"DuckDuckBot"},e=b.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/ia_archiver/i],describe(s){const t={name:"InternetArchiveCrawler"},e=b.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe(){return{name:"FacebookExternalHit"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe(s){const t={name:"SlackBot"},e=b.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/yahoo!?[\s/]*slurp/i],describe(){return{name:"YahooSlurp"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe(){return{name:"YandexBot"}}},{test:[/pingdom/i],describe(){return{name:"PingdomBot"}}},{test:[/opera/i],describe(s){const t={name:"Opera"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/opr\/|opios/i],describe(s){const t={name:"Opera"},e=b.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/SamsungBrowser/i],describe(s){const t={name:"Samsung Internet for Android"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/Whale/i],describe(s){const t={name:"NAVER Whale Browser"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/PaleMoon/i],describe(s){const t={name:"Pale Moon"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/MZBrowser/i],describe(s){const t={name:"MZ Browser"},e=b.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/focus/i],describe(s){const t={name:"Focus"},e=b.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/swing/i],describe(s){const t={name:"Swing"},e=b.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/coast/i],describe(s){const t={name:"Opera Coast"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(s){const t={name:"Opera Touch"},e=b.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/yabrowser/i],describe(s){const t={name:"Yandex Browser"},e=b.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/ucbrowser/i],describe(s){const t={name:"UC Browser"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/Maxthon|mxios/i],describe(s){const t={name:"Maxthon"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/epiphany/i],describe(s){const t={name:"Epiphany"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/puffin/i],describe(s){const t={name:"Puffin"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/sleipnir/i],describe(s){const t={name:"Sleipnir"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/k-meleon/i],describe(s){const t={name:"K-Meleon"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/micromessenger/i],describe(s){const t={name:"WeChat"},e=b.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/qqbrowser/i],describe(s){const t={name:/qqbrowserlite/i.test(s)?"QQ Browser Lite":"QQ Browser"},e=b.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/msie|trident/i],describe(s){const t={name:"Internet Explorer"},e=b.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/\sedg\//i],describe(s){const t={name:"Microsoft Edge"},e=b.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/edg([ea]|ios)/i],describe(s){const t={name:"Microsoft Edge"},e=b.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/vivaldi/i],describe(s){const t={name:"Vivaldi"},e=b.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/seamonkey/i],describe(s){const t={name:"SeaMonkey"},e=b.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/sailfish/i],describe(s){const t={name:"Sailfish"},e=b.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,s);return e&&(t.version=e),t}},{test:[/silk/i],describe(s){const t={name:"Amazon Silk"},e=b.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/phantom/i],describe(s){const t={name:"PhantomJS"},e=b.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/slimerjs/i],describe(s){const t={name:"SlimerJS"},e=b.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(s){const t={name:"BlackBerry"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/(web|hpw)[o0]s/i],describe(s){const t={name:"WebOS Browser"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/bada/i],describe(s){const t={name:"Bada"},e=b.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/tizen/i],describe(s){const t={name:"Tizen"},e=b.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/qupzilla/i],describe(s){const t={name:"QupZilla"},e=b.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/librewolf/i],describe(s){const t={name:"LibreWolf"},e=b.getFirstMatch(/(?:librewolf)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/firefox|iceweasel|fxios/i],describe(s){const t={name:"Firefox"},e=b.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/electron/i],describe(s){const t={name:"Electron"},e=b.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/sogoumobilebrowser/i,/metasr/i,/se 2\.[x]/i],describe(s){const t={name:"Sogou Browser"},e=b.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,s),r=b.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,s),i=b.getFirstMatch(/se ([\d.]+)x/i,s),n=e||r||i;return n&&(t.version=n),t}},{test:[/MiuiBrowser/i],describe(s){const t={name:"Miui"},e=b.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test(s){return s.hasBrand("DuckDuckGo")?!0:s.test(/\sDdg\/[\d.]+$/i)},describe(s,t){const e={name:"DuckDuckGo"};if(t){const i=t.getBrandVersion("DuckDuckGo");if(i)return e.version=i,e}const r=b.getFirstMatch(/\sDdg\/([\d.]+)$/i,s);return r&&(e.version=r),e}},{test(s){return s.hasBrand("Brave")},describe(s,t){const e={name:"Brave"};if(t){const r=t.getBrandVersion("Brave");if(r)return e.version=r,e}return e}},{test:[/chromium/i],describe(s){const t={name:"Chromium"},e=b.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/chrome|crios|crmo/i],describe(s){const t={name:"Chrome"},e=b.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/GSA/i],describe(s){const t={name:"Google Search"},e=b.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test(s){const t=!s.test(/like android/i),e=s.test(/android/i);return t&&e},describe(s){const t={name:"Android Browser"},e=b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/playstation 4/i],describe(s){const t={name:"PlayStation 4"},e=b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/safari|applewebkit/i],describe(s){const t={name:"Safari"},e=b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/.*/i],describe(s){const t=/^(.*)\/(.*) /,e=/^(.*)\/(.*)[ \t]\((.*)/,i=s.search("\\(")!==-1?e:t;return{name:b.getFirstMatch(i,s),version:b.getSecondMatch(i,s)}}}],sy=[{test:[/Roku\/DVP/],describe(s){const t=b.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,s);return{name:ht.Roku,version:t}}},{test:[/windows phone/i],describe(s){const t=b.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,s);return{name:ht.WindowsPhone,version:t}}},{test:[/windows /i],describe(s){const t=b.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,s),e=b.getWindowsVersionName(t);return{name:ht.Windows,version:t,versionName:e}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(s){const t={name:ht.iOS},e=b.getSecondMatch(/(Version\/)(\d[\d.]+)/,s);return e&&(t.version=e),t}},{test:[/macintosh/i],describe(s){const t=b.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,s).replace(/[_\s]/g,"."),e=b.getMacOSVersionName(t),r={name:ht.MacOS,version:t};return e&&(r.versionName=e),r}},{test:[/(ipod|iphone|ipad)/i],describe(s){const t=b.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,s).replace(/[_\s]/g,".");return{name:ht.iOS,version:t}}},{test:[/OpenHarmony/i],describe(s){const t=b.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,s);return{name:ht.HarmonyOS,version:t}}},{test(s){const t=!s.test(/like android/i),e=s.test(/android/i);return t&&e},describe(s){const t=b.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,s),e=b.getAndroidVersionName(t),r={name:ht.Android,version:t};return e&&(r.versionName=e),r}},{test:[/(web|hpw)[o0]s/i],describe(s){const t=b.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,s),e={name:ht.WebOS};return t&&t.length&&(e.version=t),e}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(s){const t=b.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,s)||b.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,s)||b.getFirstMatch(/\bbb(\d+)/i,s);return{name:ht.BlackBerry,version:t}}},{test:[/bada/i],describe(s){const t=b.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,s);return{name:ht.Bada,version:t}}},{test:[/tizen/i],describe(s){const t=b.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,s);return{name:ht.Tizen,version:t}}},{test:[/linux/i],describe(){return{name:ht.Linux}}},{test:[/CrOS/],describe(){return{name:ht.ChromeOS}}},{test:[/PlayStation 4/],describe(s){const t=b.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,s);return{name:ht.PlayStation4,version:t}}}],ry=[{test:[/googlebot/i],describe(){return{type:Q.bot,vendor:"Google"}}},{test:[/linespider/i],describe(){return{type:Q.bot,vendor:"Line"}}},{test:[/amazonbot/i],describe(){return{type:Q.bot,vendor:"Amazon"}}},{test:[/gptbot/i],describe(){return{type:Q.bot,vendor:"OpenAI"}}},{test:[/chatgpt-user/i],describe(){return{type:Q.bot,vendor:"OpenAI"}}},{test:[/oai-searchbot/i],describe(){return{type:Q.bot,vendor:"OpenAI"}}},{test:[/baiduspider/i],describe(){return{type:Q.bot,vendor:"Baidu"}}},{test:[/bingbot/i],describe(){return{type:Q.bot,vendor:"Bing"}}},{test:[/duckduckbot/i],describe(){return{type:Q.bot,vendor:"DuckDuckGo"}}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe(){return{type:Q.bot,vendor:"Anthropic"}}},{test:[/omgilibot/i,/webzio-extended/i],describe(){return{type:Q.bot,vendor:"Webz.io"}}},{test:[/diffbot/i],describe(){return{type:Q.bot,vendor:"Diffbot"}}},{test:[/perplexitybot/i],describe(){return{type:Q.bot,vendor:"Perplexity AI"}}},{test:[/perplexity-user/i],describe(){return{type:Q.bot,vendor:"Perplexity AI"}}},{test:[/youbot/i],describe(){return{type:Q.bot,vendor:"You.com"}}},{test:[/ia_archiver/i],describe(){return{type:Q.bot,vendor:"Internet Archive"}}},{test:[/meta-webindexer/i],describe(){return{type:Q.bot,vendor:"Meta"}}},{test:[/meta-externalads/i],describe(){return{type:Q.bot,vendor:"Meta"}}},{test:[/meta-externalagent/i],describe(){return{type:Q.bot,vendor:"Meta"}}},{test:[/meta-externalfetcher/i],describe(){return{type:Q.bot,vendor:"Meta"}}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe(){return{type:Q.bot,vendor:"Meta"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe(){return{type:Q.bot,vendor:"Slack"}}},{test:[/yahoo/i],describe(){return{type:Q.bot,vendor:"Yahoo"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe(){return{type:Q.bot,vendor:"Yandex"}}},{test:[/pingdom/i],describe(){return{type:Q.bot,vendor:"Pingdom"}}},{test:[/huawei/i],describe(s){const t=b.getFirstMatch(/(can-l01)/i,s)&&"Nova",e={type:Q.mobile,vendor:"Huawei"};return t&&(e.model=t),e}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe(){return{type:Q.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe(){return{type:Q.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(){return{type:Q.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe(){return{type:Q.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe(){return{type:Q.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe(){return{type:Q.tablet}}},{test(s){const t=s.test(/ipod|iphone/i),e=s.test(/like (ipod|iphone)/i);return t&&!e},describe(s){const t=b.getFirstMatch(/(ipod|iphone)/i,s);return{type:Q.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe(){return{type:Q.mobile,vendor:"Nexus"}}},{test:[/Nokia/i],describe(s){const t=b.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,s),e={type:Q.mobile,vendor:"Nokia"};return t&&(e.model=t),e}},{test:[/[^-]mobi/i],describe(){return{type:Q.mobile}}},{test(s){return s.getBrowserName(!0)==="blackberry"},describe(){return{type:Q.mobile,vendor:"BlackBerry"}}},{test(s){return s.getBrowserName(!0)==="bada"},describe(){return{type:Q.mobile}}},{test(s){return s.getBrowserName()==="windows phone"},describe(){return{type:Q.mobile,vendor:"Microsoft"}}},{test(s){const t=Number(String(s.getOSVersion()).split(".")[0]);return s.getOSName(!0)==="android"&&t>=3},describe(){return{type:Q.tablet}}},{test(s){return s.getOSName(!0)==="android"},describe(){return{type:Q.mobile}}},{test:[/smart-?tv|smarttv/i],describe(){return{type:Q.tv}}},{test:[/netcast/i],describe(){return{type:Q.tv}}},{test(s){return s.getOSName(!0)==="macos"},describe(){return{type:Q.desktop,vendor:"Apple"}}},{test(s){return s.getOSName(!0)==="windows"},describe(){return{type:Q.desktop}}},{test(s){return s.getOSName(!0)==="linux"},describe(){return{type:Q.desktop}}},{test(s){return s.getOSName(!0)==="playstation 4"},describe(){return{type:Q.tv}}},{test(s){return s.getOSName(!0)==="roku"},describe(){return{type:Q.tv}}}],iy=[{test(s){return s.getBrowserName(!0)==="microsoft edge"},describe(s){if(/\sedg\//i.test(s))return{name:$r.Blink};const e=b.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,s);return{name:$r.EdgeHTML,version:e}}},{test:[/trident/i],describe(s){const t={name:$r.Trident},e=b.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test(s){return s.test(/presto/i)},describe(s){const t={name:$r.Presto},e=b.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test(s){const t=s.test(/gecko/i),e=s.test(/like gecko/i);return t&&!e},describe(s){const t={name:$r.Gecko},e=b.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:$r.Blink}}},{test:[/(apple)?webkit/i],describe(s){const t={name:$r.WebKit},e=b.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}}];class km{constructor(t,e=!1,r=null){if(t==null||t==="")throw new Error("UserAgent parameter can't be empty");this._ua=t;let i=!1;typeof e=="boolean"?(i=e,this._hints=r):e!=null&&typeof e=="object"?this._hints=e:this._hints=null,this.parsedResult={},i!==!0&&this.parse()}getHints(){return this._hints}hasBrand(t){if(!this._hints||!Array.isArray(this._hints.brands))return!1;const e=t.toLowerCase();return this._hints.brands.some(r=>r.brand&&r.brand.toLowerCase()===e)}getBrandVersion(t){if(!this._hints||!Array.isArray(this._hints.brands))return;const e=t.toLowerCase(),r=this._hints.brands.find(i=>i.brand&&i.brand.toLowerCase()===e);return r?r.version:void 0}getUA(){return this._ua}test(t){return t.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const t=b.find(ty,e=>{if(typeof e.test=="function")return e.test(this);if(Array.isArray(e.test))return e.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.browser=t.describe(this.getUA(),this)),this.parsedResult.browser}getBrowser(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()}getBrowserName(t){return t?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 t=b.find(sy,e=>{if(typeof e.test=="function")return e.test(this);if(Array.isArray(e.test))return e.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.os=t.describe(this.getUA())),this.parsedResult.os}getOSName(t){const{name:e}=this.getOS();return t?String(e).toLowerCase()||"":e||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(t=!1){const{type:e}=this.getPlatform();return t?String(e).toLowerCase()||"":e||""}parsePlatform(){this.parsedResult.platform={};const t=b.find(ry,e=>{if(typeof e.test=="function")return e.test(this);if(Array.isArray(e.test))return e.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.platform=t.describe(this.getUA())),this.parsedResult.platform}getEngine(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()}getEngineName(t){return t?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""}parseEngine(){this.parsedResult.engine={};const t=b.find(iy,e=>{if(typeof e.test=="function")return e.test(this);if(Array.isArray(e.test))return e.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.engine=t.describe(this.getUA())),this.parsedResult.engine}parse(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this}getResult(){return b.assign({},this.parsedResult)}satisfies(t){const e={};let r=0;const i={};let n=0;if(Object.keys(t).forEach(c=>{const d=t[c];typeof d=="string"?(i[c]=d,n+=1):typeof d=="object"&&(e[c]=d,r+=1)}),r>0){const c=Object.keys(e),d=b.find(c,u=>this.isOS(u));if(d){const u=this.satisfies(e[d]);if(u!==void 0)return u}const l=b.find(c,u=>this.isPlatform(u));if(l){const u=this.satisfies(e[l]);if(u!==void 0)return u}}if(n>0){const c=Object.keys(i),d=b.find(c,l=>this.isBrowser(l,!0));if(d!==void 0)return this.compareVersion(i[d])}}isBrowser(t,e=!1){const r=this.getBrowserName().toLowerCase();let i=t.toLowerCase();const n=b.getBrowserTypeByAlias(i);return e&&n&&(i=n.toLowerCase()),i===r}compareVersion(t){let e=[0],r=t,i=!1;const n=this.getBrowserVersion();if(typeof n=="string")return t[0]===">"||t[0]==="<"?(r=t.substr(1),t[1]==="="?(i=!0,r=t.substr(2)):e=[],t[0]===">"?e.push(1):e.push(-1)):t[0]==="="?r=t.substr(1):t[0]==="~"&&(i=!0,r=t.substr(1)),e.indexOf(b.compareVersions(n,r,i))>-1}isOS(t){return this.getOSName(!0)===String(t).toLowerCase()}isPlatform(t){return this.getPlatformType(!0)===String(t).toLowerCase()}isEngine(t){return this.getEngineName(!0)===String(t).toLowerCase()}is(t,e=!1){return this.isBrowser(t,e)||this.isOS(t)||this.isPlatform(t)}some(t=[]){return t.some(e=>this.is(e))}}/*!
|
|
2
2
|
* Bowser - a browser detector
|
|
3
3
|
* https://github.com/bowser-js/bowser
|
|
4
4
|
* MIT License | (c) Dustin Diaz 2012-2015
|
|
5
5
|
* MIT License | (c) Denis Demchenko 2015-2019
|
|
6
|
-
*/class Pm{static getParser(t,e=!1,r=null){if(typeof t!="string")throw new Error("UserAgent should be a string");return new wm(t,e,r)}static parse(t,e=null){return new wm(t,e).getResult()}static get BROWSER_MAP(){return bm}static get ENGINE_MAP(){return $r}static get OS_MAP(){return ht}static get PLATFORMS_MAP(){return Q}}const io="chrome",km="opera",_m="firefox",Cm="iexplorer",Rm="safari",Im="nwjs",Am="electron",Mm="react-native",ah="unknown",Id={Chrome:io,Chromium:io,Opera:km,Firefox:_m,"Internet Explorer":Cm,Safari:Rm};function ry(){const{userAgent:s}=navigator,t={name:ah,version:void 0};if(s.match(/Chrome/)&&!s.match(/Edge/))if(s.match(/Edg(A?)/)){const e=s.match(/Chrome\/([\d.]+)/)[1];Number.parseInt(e,10)>72&&(t.name=io,t.version=e)}else t.name=io,t.version=s.match(/Chrome\/([\d.]+)/)[1];return t}function iy(){const{userAgent:s}=navigator;if(s.match(/Electron/)){const t=s.match(/Electron\/([\d.]+)/)[1];return{name:Am,version:t}}return null}function ny(){const{userAgent:s}=navigator;if(s.match(/JitsiMeetNW/)){const t=s.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:Im,version:t}}}function ay(){const s=navigator.userAgent.match(/\b(react[ \t_-]*native)(?:\/(\S+))?/i);let t;if(s||navigator.product==="ReactNative")return s&&s.length>2&&(s[1],t=s[2]),t||(t="unknown"),{name:Mm,version:t}}function oy(s){let t;const e=[ay,iy,ny];for(let i=0;i<e.length;i+=1)if(t=e[i](),t)return t;const r=s.getBrowserName();return r in Id?{name:Id[r],version:s.getBrowserVersion()}:(t=ry(),t||{name:ah,version:void 0})}class cy{constructor(){p(this,"_bowser");p(this,"_name");p(this,"_version");p(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(t){let e,r;if(this._bowser=Pm.getParser(navigator.userAgent),typeof t=="undefined"){const i=oy(this._bowser);e=i.name,r=i.version}else t.name in Id?(e=Id[t.name],r=t.version):(e=ah,r=void 0);this._name=e,this._version=r}getName(){return this._name}isChrome(){return this._name===io}isOpera(){return this._name===km}isFirefox(){return this._name===_m}isIExplorer(){return this._name===Cm}isSafari(){return this._name===Rm}isNWJS(){return this._name===Im}isElectron(){return this._name===Am}isReactNative(){return this._name===Mm||navigator.isReactNative===!0}getVersion(){return this._version}isMobile(){return this._bowser.getPlatformType()==="mobile"}_checkCondition(t){if(this._version)return this._bowser.satisfies(t)}isVersionGreaterThan(t){return this._checkCondition({[this._name]:`>${t}`})}isVersionLessThan(t){return this._checkCondition({[this._name]:`<${t}`})}isVersionEqualTo(t){return this._checkCondition({[this._name]:`~${t}`})}}class dy extends cy{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 t=new ReadableStream;try{return window.postMessage(t,"*",[t]),!0}catch(e){return!1}}supportsAudioRed(){return Boolean(window.RTCRtpSender&&window.RTCRtpSender.getCapabilities&&window.RTCRtpSender.getCapabilities("audio").codecs.some(t=>t.mimeType==="audio/red")&&window.RTCRtpReceiver&&window.RTCRtpReceiver.getCapabilities&&window.RTCRtpReceiver.getCapabilities("audio").codecs.some(t=>t.mimeType==="audio/red"))}supportsSdpSemantics(){return this.isChromiumBased()}_getChromiumBasedVersion(){if(this.isChromiumBased()){if(this.isNWJS())return Number.parseInt(process.versions.chromium,10);const t=navigator.userAgent;if(t.match(/Chrome/))return Number.parseInt(t.match(/Chrome\/([\d.]+)/)[1],10)}return-1}isIOSMobile(){return this.isMobile&&this._bowser.getOSName()==="iOS"}}const Pe=new dy;var Tt={},ly={get exports(){return Tt},set exports(s){Tt=s}},$n=typeof Reflect=="object"?Reflect:null,Om=$n&&typeof $n.apply=="function"?$n.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},Ad;$n&&typeof $n.ownKeys=="function"?Ad=$n.ownKeys:Object.getOwnPropertySymbols?Ad=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Ad=function(t){return Object.getOwnPropertyNames(t)};function uy(s){console&&console.warn&&console.warn(s)}var Dm=Number.isNaN||function(t){return t!==t};function ue(){ue.init.call(this)}ly.exports=ue,Tt.once=gy,ue.EventEmitter=ue,ue.prototype._events=void 0,ue.prototype._eventsCount=0,ue.prototype._maxListeners=void 0;var Nm=10;function Md(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ue,"defaultMaxListeners",{enumerable:!0,get:function(){return Nm},set:function(s){if(typeof s!="number"||s<0||Dm(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Nm=s}}),ue.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},ue.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Dm(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 Lm(s){return s._maxListeners===void 0?ue.defaultMaxListeners:s._maxListeners}ue.prototype.getMaxListeners=function(){return Lm(this)},ue.prototype.emit=function(t){for(var e=[],r=1;r<arguments.length;r++)e.push(arguments[r]);var i=t==="error",n=this._events;if(n!==void 0)i=i&&n.error===void 0;else if(!i)return!1;if(i){var o;if(e.length>0&&(o=e[0]),o instanceof Error)throw o;var c=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw c.context=o,c}var d=n[t];if(d===void 0)return!1;if(typeof d=="function")Om(d,this,e);else for(var l=d.length,u=Bm(d,l),r=0;r<l;++r)Om(u[r],this,e);return!0};function Vm(s,t,e,r){var i,n,o;if(Md(e),n=s._events,n===void 0?(n=s._events=Object.create(null),s._eventsCount=0):(n.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),n=s._events),o=n[t]),o===void 0)o=n[t]=e,++s._eventsCount;else if(typeof o=="function"?o=n[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=Lm(s),i>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=s,c.type=t,c.count=o.length,uy(c)}return s}ue.prototype.addListener=function(t,e){return Vm(this,t,e,!1)},ue.prototype.on=ue.prototype.addListener,ue.prototype.prependListener=function(t,e){return Vm(this,t,e,!0)};function hy(){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 xm(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=hy.bind(r);return i.listener=e,r.wrapFn=i,i}ue.prototype.once=function(t,e){return Md(e),this.on(t,xm(this,t,e)),this},ue.prototype.prependOnceListener=function(t,e){return Md(e),this.prependListener(t,xm(this,t,e)),this},ue.prototype.removeListener=function(t,e){var r,i,n,o,c;if(Md(e),i=this._events,i===void 0)return this;if(r=i[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete i[t],i.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(n=-1,o=r.length-1;o>=0;o--)if(r[o]===e||r[o].listener===e){c=r[o].listener,n=o;break}if(n<0)return this;n===0?r.shift():py(r,n),r.length===1&&(i[t]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",t,c||e)}return this},ue.prototype.off=ue.prototype.removeListener,ue.prototype.removeAllListeners=function(t){var e,r,i;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 n=Object.keys(r),o;for(i=0;i<n.length;++i)o=n[i],o!=="removeListener"&&this.removeAllListeners(o);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(i=e.length-1;i>=0;i--)this.removeListener(t,e[i]);return this};function $m(s,t,e){var r=s._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?my(i):Bm(i,i.length)}ue.prototype.listeners=function(t){return $m(this,t,!0)},ue.prototype.rawListeners=function(t){return $m(this,t,!1)},ue.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):Um.call(s,t)},ue.prototype.listenerCount=Um;function Um(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}ue.prototype.eventNames=function(){return this._eventsCount>0?Ad(this._events):[]};function Bm(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function py(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function my(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function gy(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,n),r(o)}function n(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}Fm(s,t,n,{once:!0}),t!=="error"&&fy(s,i,{once:!0})})}function fy(s,t,e){typeof s.on=="function"&&Fm(s,"error",t,e)}function Fm(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(n){r.once&&s.removeEventListener(t,i),e(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}var W;(function(s){s[s.MAJOR_EVENT=0]="MAJOR_EVENT",s[s.MINOR_EVENT=1]="MINOR_EVENT"})(W||(W={}));var L;(function(s){s.PRECALL_TEST_BEGIN="precall_begin",s.PRECALL_TEST_COMPLETE="precall_end",s.CALL_JOIN_BEGIN="call_join",s.NET_QUALITY_TEST_BEGIN="net_quality_test_begin",s.NET_QUALITY_TEST_END="net_quality_test_end",s.WEBSOCKET_CONNECTED="websocket_connected",s.TRANSPORT_CONNECTED="transport_connected",s.AUDIO_ON="audio_on",s.AUDIO_OFF="audio_off",s.VIDEO_ON="video_on",s.VIDEO_OFF="video_off",s.PARTICIPANT_ROLE="participant_role",s.PING_STAT="ping_stat",s.DISCONNECT="disconnect",s.RECONNECT_ATTEMPT="reconnect_attempt",s.SCREENSHARE_START_REQUESTED="screenshare_start_requested",s.SCREENSHARE_STARTED="screenshare_started",s.SCREENSHARE_STOPPED="screenshare_stopped",s.TAB_CHANGE="tab_change",s.BROWSER_BACKGROUNDED="browser_backgrounded",s.BROWSER_FOREGROUNDED="browser_foregrounded",s.DOMINANT_SPEAKER="dominant_speaker",s.AUDIO_DEVICES_UPDATES="audio_devices_updates",s.VIDEO_DEVICES_UPDATES="video_devices_updates",s.SPEAKER_DEVICES_UPDATES="speaker_devices_updates",s.SELECTED_MICROHPONE_UPDATE="selected_microphone_update",s.SELECTED_CAMERA_UPDATE="selected_camera_update",s.SELECTED_SPEAKER_UPDATE="selected_speaker_update",s.EXPECTED_VIDEO_RESOLUTION="expected_video_resolution",s.EXPECTED_SCREENSHARE_RESOLUTION="expected_screenshare_resolution",s.MEDIA_PERMISSION="media_permission",s.LEGACY_SWITCH="legacy_switch",s.AUDIO_PLAY_FAILED="audio_play_failed",s.VIDEO_PLAY_FAILED="video_play_failed",s.AUDIO_TRACK_MUTED="audio_track_muted",s.VIDEO_TRACK_MUTED="video_track_muted",s.IVS_PLAYER_REBUFFERING="ivs_player_rebuffering",s.IVS_PLAYER_AUDIO_BLOCKED="ivs_player_audio_blocked",s.IVS_PLAYER_PLAYBACK_BLOCKED="ivs_player_playback_blocked",s.IVS_PLAYER_ERROR="ivs_player_error",s.IVS_PLAYER_RECOVERABLE_ERROR="ivs_player_recoverable_error",s.IVS_PLAYER_WORKER_ERROR="ivs_player_worker_error",s.IVS_PLAYER_NETWORK_UNAVAILABLE="ivs_player_network_unavailable",s.LIVESTREAM_LATENCY="livestream_latency",s.IVS_PLAYER_ANALYTICS_EVENT="ivs_player_analytics_event",s.IVS_PLAYER_PLAYBACK_RATE_CHANGED="ivs_player_playback_rate_changed",s.IVS_PLAYER_QUALITY_CHANGED="ivs_player_quality_changed",s.IVS_PLAYER_INITIALIZED="ivs_player_initialized"})(L||(L={}));const vy=new Map([[L.PRECALL_TEST_BEGIN,W.MINOR_EVENT],[L.PRECALL_TEST_COMPLETE,W.MINOR_EVENT],[L.CALL_JOIN_BEGIN,W.MAJOR_EVENT],[L.NET_QUALITY_TEST_BEGIN,W.MINOR_EVENT],[L.NET_QUALITY_TEST_END,W.MINOR_EVENT],[L.WEBSOCKET_CONNECTED,W.MINOR_EVENT],[L.TRANSPORT_CONNECTED,W.MAJOR_EVENT],[L.AUDIO_ON,W.MINOR_EVENT],[L.AUDIO_OFF,W.MINOR_EVENT],[L.VIDEO_ON,W.MINOR_EVENT],[L.VIDEO_OFF,W.MINOR_EVENT],[L.PARTICIPANT_ROLE,W.MINOR_EVENT],[L.PING_STAT,W.MAJOR_EVENT],[L.DISCONNECT,W.MAJOR_EVENT],[L.RECONNECT_ATTEMPT,W.MAJOR_EVENT],[L.SCREENSHARE_START_REQUESTED,W.MINOR_EVENT],[L.SCREENSHARE_STARTED,W.MINOR_EVENT],[L.SCREENSHARE_STOPPED,W.MINOR_EVENT],[L.TAB_CHANGE,W.MINOR_EVENT],[L.BROWSER_BACKGROUNDED,W.MINOR_EVENT],[L.BROWSER_FOREGROUNDED,W.MINOR_EVENT],[L.DOMINANT_SPEAKER,W.MINOR_EVENT],[L.AUDIO_DEVICES_UPDATES,W.MINOR_EVENT],[L.VIDEO_DEVICES_UPDATES,W.MINOR_EVENT],[L.SPEAKER_DEVICES_UPDATES,W.MINOR_EVENT],[L.SELECTED_MICROHPONE_UPDATE,W.MINOR_EVENT],[L.SELECTED_CAMERA_UPDATE,W.MINOR_EVENT],[L.SELECTED_SPEAKER_UPDATE,W.MINOR_EVENT],[L.MEDIA_PERMISSION,W.MINOR_EVENT],[L.LEGACY_SWITCH,W.MINOR_EVENT],[L.AUDIO_PLAY_FAILED,W.MINOR_EVENT],[L.VIDEO_PLAY_FAILED,W.MINOR_EVENT],[L.AUDIO_TRACK_MUTED,W.MINOR_EVENT],[L.VIDEO_TRACK_MUTED,W.MINOR_EVENT],[L.IVS_PLAYER_REBUFFERING,W.MAJOR_EVENT],[L.IVS_PLAYER_AUDIO_BLOCKED,W.MAJOR_EVENT],[L.IVS_PLAYER_PLAYBACK_BLOCKED,W.MAJOR_EVENT],[L.IVS_PLAYER_ERROR,W.MAJOR_EVENT],[L.IVS_PLAYER_RECOVERABLE_ERROR,W.MAJOR_EVENT],[L.IVS_PLAYER_WORKER_ERROR,W.MAJOR_EVENT],[L.IVS_PLAYER_NETWORK_UNAVAILABLE,W.MAJOR_EVENT],[L.LIVESTREAM_LATENCY,W.MAJOR_EVENT],[L.IVS_PLAYER_ANALYTICS_EVENT,W.MINOR_EVENT],[L.IVS_PLAYER_PLAYBACK_RATE_CHANGED,W.MINOR_EVENT],[L.IVS_PLAYER_QUALITY_CHANGED,W.MINOR_EVENT],[L.IVS_PLAYER_INITIALIZED,W.MINOR_EVENT],[L.EXPECTED_VIDEO_RESOLUTION,W.MINOR_EVENT],[L.EXPECTED_SCREENSHARE_RESOLUTION,W.MINOR_EVENT]]);class Sy{constructor(){p(this,"events");this.events=[]}add(t){this.events.push(t)}flush(){return{entries:this.events.splice(0,25)}}}class Ty extends Tt{constructor({logger:e,peerId:r,apiHostnames:i,authToken:n}){super();p(this,"logger");p(this,"peerId");p(this,"eventStore");p(this,"apiEndpoint");p(this,"authToken");this.logger=e,this.peerId=r,this.authToken=n,this.apiEndpoint=`https://${i.daCollector}`,this.eventStore=new Sy}async sendEventsChunkToServer(e){const r={payload:e,peerId:this.peerId},i=new AbortController,n=setTimeout(()=>i.abort(),3e3);try{return await fetch(this.apiEndpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.authToken}`},body:JSON.stringify(r),signal:i.signal}),!0}catch(o){return this.logger.error("callStats::sendEventsChunkToServer::catch",{peerId:this.peerId,endpoint:this.apiEndpoint,error:o instanceof Error?o.message:String(o),stack:o instanceof Error?o.stack:void 0}),!1}finally{clearTimeout(n)}}callEvent(e){e.timestamp=new Date,this.eventStore.add(e),this.emit(e.event,e.metaData),vy.get(e.event)===W.MAJOR_EVENT&&this.flush()}async flush(){var r;const e=this.eventStore.flush();if((r=e==null?void 0:e.entries)!=null&&r.length){const i=await this.sendEventsChunkToServer(e);return i||e.entries.forEach(n=>{this.eventStore.add(n)}),i}return!1}}var Hm;(function(s){s.CHROMIUM="chromum",s.FIREFOX="firefox",s.SAFARI="safari"})(Hm||(Hm={}));const qm={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var ts;(function(s){s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.SPEAKER="SPEAKER",s.SCREENSHARE="SCREENSHARE"})(ts||(ts={}));var jm;(function(s){s[s.INIT=0]="INIT",s[s.ACCEPTED=1]="ACCEPTED",s[s.DENIED=2]="DENIED",s[s.SYS_DENIED=3]="SYS_DENIED",s[s.FAILED=4]="FAILED",s[s.NOTFOUND=5]="NOTFOUND",s[s.NOT_APPLICABLE=6]="NOT_APPLICABLE"})(jm||(jm={}));function Un(s){return s?s.split(".").slice(0,2).concat(["0","0"]).join("."):""}function Od({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function Dd({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}const Gm=240,Wm=720,Jm=8,Km=3,Nd=10,Ld=.02,Vd=.03;function er({stat:s,weight:t,rangeMin:e,rangeMax:r,rangeRankingDirection:i}){return s==null?t:e===r?i==="UP"?s<=e?t:0:s>=r?t:0:i==="UP"?(1-Math.max(Math.min(r,Math.abs(s))-e,0)/(r-e))*t:i==="DOWN"?Math.max(Math.min(r,Math.abs(s))-e,0)/(r-e)*t:t}function zm({isLowQualityVideo:s,isVideoStuck:t,isVideoLagging:e,jitterQuality:r,packetsLostQuality:i}){const n=.8*((s?.85:1)*(e?.7:1)*(t?.5:1))+.2*(r*i);return Math.round((n+Number.EPSILON)*100)/100}function Ym({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function Qm({packetsLost:s,packetsSent:t,jitter:e}){const i=er({stat:Ym({packetsLost:s,packetsSent:t}),weight:.7,rangeMin:0,rangeMax:Nd,rangeRankingDirection:"UP"}),o=er({stat:e,weight:.3,rangeMin:Ld,rangeMax:Vd,rangeRankingDirection:"UP"});return i+o}function yy({frameWidth:s,isScreenShare:t}){return s<(t?Wm:Gm)}function Ey({framesPerSecond:s,isScreenShare:t}){return s<(t?Km:Jm)}function by({framesEncoded:s}){return s===0}function Xm({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsSent:r,jitter:i,isScreenShare:n,framesEncoded:o}){const c=er({stat:Ym({packetsLost:e,packetsSent:r}),weight:1,rangeMin:0,rangeMax:Nd,rangeRankingDirection:"UP"}),d=er({stat:i,weight:1,rangeMin:Ld,rangeMax:Vd,rangeRankingDirection:"UP"}),l=yy({frameWidth:s,isScreenShare:n}),u=Ey({framesPerSecond:t,isScreenShare:n}),h=by({framesEncoded:o,isScreenShare:n});return zm({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:h,jitterQuality:d,packetsLostQuality:c})}function Zm({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}function eg({concealmentEvents:s,packetsLost:t,packetsReceived:e,jitter:r}){const n=er({stat:s,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),o=.5,c=er({stat:Zm({packetsLost:t,packetsReceived:e}),weight:o,rangeMin:0,rangeMax:Nd,rangeRankingDirection:"UP"}),l=er({stat:r,weight:.3,rangeMin:Ld,rangeMax:Vd,rangeRankingDirection:"UP"});return n+c+l}function wy({framesDecoded:s}){return s===0}function Py({framesPerSecond:s,isScreenShare:t}){return s<(t?Km:Jm)}function ky({frameWidth:s,isScreenShare:t}){return s<(t?Wm:Gm)}function tg({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsReceived:r,jitter:i,isScreenShare:n,framesDecoded:o}){const c=er({stat:Zm({packetsLost:e,packetsReceived:r}),weight:1,rangeMin:0,rangeMax:Nd,rangeRankingDirection:"UP"}),d=er({stat:i,weight:1,rangeMin:Ld,rangeMax:Vd,rangeRankingDirection:"UP"}),l=ky({frameWidth:s,isScreenShare:n}),u=Py({framesPerSecond:t,isScreenShare:n}),h=wy({framesDecoded:o,isScreenShare:n});return zm({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:h,jitterQuality:d,packetsLostQuality:c})}class tr{constructor(t){p(this,"pc1");p(this,"pc2");p(this,"constrainVideoBitrateKbps");p(this,"constrainOfferToRemoveVideoFec",!1);p(this,"iceCandidateFilter");const e=new RTCPeerConnection(t),r=new RTCPeerConnection(t);this.pc1=e,this.pc2=r,this.iceCandidateFilter=tr.noFilter,this.pc1.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc2)),this.pc2.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc1))}static parseCandidate(t){const e="candidate:",r=t.indexOf(e)+e.length,i=t.substr(r).split(" ");return{type:i[7],protocol:i[2],address:i[4]}}static isNotHostCandidate(t){return t.type!=="host"}static isHost(t){return t.type==="host"}static isRelay(t){return t.type==="relay"}static isReflexive(t){return t.type==="srflx"}static noFilter(t){return!0}onIceCandidate(t,e){if(e.candidate){const r=tr.parseCandidate(e.candidate.candidate);this.iceCandidateFilter(r)&&t.addIceCandidate(e.candidate)}}setIceCandidateFilter(t){this.iceCandidateFilter=t}constrainVideoBitrate(t){this.constrainVideoBitrateKbps=t}disableVideoFec(){this.constrainOfferToRemoveVideoFec=!0}gotOffer(t){this.constrainOfferToRemoveVideoFec&&(t.sdp=t.sdp.replace(/(m=video 1 [^\r]+)(116 117)(\r\n)/g,`$1\r
|
|
6
|
+
*/class _m{static getParser(t,e=!1,r=null){if(typeof t!="string")throw new Error("UserAgent should be a string");return new km(t,e,r)}static parse(t,e=null){return new km(t,e).getResult()}static get BROWSER_MAP(){return Pm}static get ENGINE_MAP(){return $r}static get OS_MAP(){return ht}static get PLATFORMS_MAP(){return Q}}const io="chrome",Cm="opera",Rm="firefox",Im="iexplorer",Am="safari",Mm="nwjs",Om="electron",Dm="react-native",oh="unknown",Ad={Chrome:io,Chromium:io,Opera:Cm,Firefox:Rm,"Internet Explorer":Im,Safari:Am};function ny(){const{userAgent:s}=navigator,t={name:oh,version:void 0};if(s.match(/Chrome/)&&!s.match(/Edge/))if(s.match(/Edg(A?)/)){const e=s.match(/Chrome\/([\d.]+)/)[1];Number.parseInt(e,10)>72&&(t.name=io,t.version=e)}else t.name=io,t.version=s.match(/Chrome\/([\d.]+)/)[1];return t}function ay(){const{userAgent:s}=navigator;if(s.match(/Electron/)){const t=s.match(/Electron\/([\d.]+)/)[1];return{name:Om,version:t}}return null}function oy(){const{userAgent:s}=navigator;if(s.match(/JitsiMeetNW/)){const t=s.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:Mm,version:t}}}function cy(){const s=navigator.userAgent.match(/\b(react[ \t_-]*native)(?:\/(\S+))?/i);let t;if(s||navigator.product==="ReactNative")return s&&s.length>2&&(s[1],t=s[2]),t||(t="unknown"),{name:Dm,version:t}}function dy(s){let t;const e=[cy,ay,oy];for(let i=0;i<e.length;i+=1)if(t=e[i](),t)return t;const r=s.getBrowserName();return r in Ad?{name:Ad[r],version:s.getBrowserVersion()}:(t=ny(),t||{name:oh,version:void 0})}class ly{constructor(){p(this,"_bowser");p(this,"_name");p(this,"_version");p(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(t){let e,r;if(this._bowser=_m.getParser(navigator.userAgent),typeof t=="undefined"){const i=dy(this._bowser);e=i.name,r=i.version}else t.name in Ad?(e=Ad[t.name],r=t.version):(e=oh,r=void 0);this._name=e,this._version=r}getName(){return this._name}isChrome(){return this._name===io}isOpera(){return this._name===Cm}isFirefox(){return this._name===Rm}isIExplorer(){return this._name===Im}isSafari(){return this._name===Am}isNWJS(){return this._name===Mm}isElectron(){return this._name===Om}isReactNative(){return this._name===Dm||navigator.isReactNative===!0}getVersion(){return this._version}isMobile(){return this._bowser.getPlatformType()==="mobile"}_checkCondition(t){if(this._version)return this._bowser.satisfies(t)}isVersionGreaterThan(t){return this._checkCondition({[this._name]:`>${t}`})}isVersionLessThan(t){return this._checkCondition({[this._name]:`<${t}`})}isVersionEqualTo(t){return this._checkCondition({[this._name]:`~${t}`})}}class uy extends ly{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 t=new ReadableStream;try{return window.postMessage(t,"*",[t]),!0}catch(e){return!1}}supportsAudioRed(){return Boolean(window.RTCRtpSender&&window.RTCRtpSender.getCapabilities&&window.RTCRtpSender.getCapabilities("audio").codecs.some(t=>t.mimeType==="audio/red")&&window.RTCRtpReceiver&&window.RTCRtpReceiver.getCapabilities&&window.RTCRtpReceiver.getCapabilities("audio").codecs.some(t=>t.mimeType==="audio/red"))}supportsSdpSemantics(){return this.isChromiumBased()}_getChromiumBasedVersion(){if(this.isChromiumBased()){if(this.isNWJS())return Number.parseInt(process.versions.chromium,10);const t=navigator.userAgent;if(t.match(/Chrome/))return Number.parseInt(t.match(/Chrome\/([\d.]+)/)[1],10)}return-1}isIOSMobile(){return this.isMobile&&this._bowser.getOSName()==="iOS"}}const Pe=new uy;var Tt={},hy={get exports(){return Tt},set exports(s){Tt=s}},$n=typeof Reflect=="object"?Reflect:null,Nm=$n&&typeof $n.apply=="function"?$n.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},Md;$n&&typeof $n.ownKeys=="function"?Md=$n.ownKeys:Object.getOwnPropertySymbols?Md=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Md=function(t){return Object.getOwnPropertyNames(t)};function py(s){console&&console.warn&&console.warn(s)}var Lm=Number.isNaN||function(t){return t!==t};function ue(){ue.init.call(this)}hy.exports=ue,Tt.once=vy,ue.EventEmitter=ue,ue.prototype._events=void 0,ue.prototype._eventsCount=0,ue.prototype._maxListeners=void 0;var Vm=10;function Od(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ue,"defaultMaxListeners",{enumerable:!0,get:function(){return Vm},set:function(s){if(typeof s!="number"||s<0||Lm(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Vm=s}}),ue.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},ue.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Lm(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 xm(s){return s._maxListeners===void 0?ue.defaultMaxListeners:s._maxListeners}ue.prototype.getMaxListeners=function(){return xm(this)},ue.prototype.emit=function(t){for(var e=[],r=1;r<arguments.length;r++)e.push(arguments[r]);var i=t==="error",n=this._events;if(n!==void 0)i=i&&n.error===void 0;else if(!i)return!1;if(i){var o;if(e.length>0&&(o=e[0]),o instanceof Error)throw o;var c=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw c.context=o,c}var d=n[t];if(d===void 0)return!1;if(typeof d=="function")Nm(d,this,e);else for(var l=d.length,u=Hm(d,l),r=0;r<l;++r)Nm(u[r],this,e);return!0};function $m(s,t,e,r){var i,n,o;if(Od(e),n=s._events,n===void 0?(n=s._events=Object.create(null),s._eventsCount=0):(n.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),n=s._events),o=n[t]),o===void 0)o=n[t]=e,++s._eventsCount;else if(typeof o=="function"?o=n[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=xm(s),i>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=s,c.type=t,c.count=o.length,py(c)}return s}ue.prototype.addListener=function(t,e){return $m(this,t,e,!1)},ue.prototype.on=ue.prototype.addListener,ue.prototype.prependListener=function(t,e){return $m(this,t,e,!0)};function my(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Um(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=my.bind(r);return i.listener=e,r.wrapFn=i,i}ue.prototype.once=function(t,e){return Od(e),this.on(t,Um(this,t,e)),this},ue.prototype.prependOnceListener=function(t,e){return Od(e),this.prependListener(t,Um(this,t,e)),this},ue.prototype.removeListener=function(t,e){var r,i,n,o,c;if(Od(e),i=this._events,i===void 0)return this;if(r=i[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete i[t],i.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(n=-1,o=r.length-1;o>=0;o--)if(r[o]===e||r[o].listener===e){c=r[o].listener,n=o;break}if(n<0)return this;n===0?r.shift():gy(r,n),r.length===1&&(i[t]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",t,c||e)}return this},ue.prototype.off=ue.prototype.removeListener,ue.prototype.removeAllListeners=function(t){var e,r,i;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 n=Object.keys(r),o;for(i=0;i<n.length;++i)o=n[i],o!=="removeListener"&&this.removeAllListeners(o);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(i=e.length-1;i>=0;i--)this.removeListener(t,e[i]);return this};function Bm(s,t,e){var r=s._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?fy(i):Hm(i,i.length)}ue.prototype.listeners=function(t){return Bm(this,t,!0)},ue.prototype.rawListeners=function(t){return Bm(this,t,!1)},ue.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):Fm.call(s,t)},ue.prototype.listenerCount=Fm;function Fm(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}ue.prototype.eventNames=function(){return this._eventsCount>0?Md(this._events):[]};function Hm(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function gy(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function fy(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function vy(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,n),r(o)}function n(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}qm(s,t,n,{once:!0}),t!=="error"&&Sy(s,i,{once:!0})})}function Sy(s,t,e){typeof s.on=="function"&&qm(s,"error",t,e)}function qm(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(n){r.once&&s.removeEventListener(t,i),e(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}var W;(function(s){s[s.MAJOR_EVENT=0]="MAJOR_EVENT",s[s.MINOR_EVENT=1]="MINOR_EVENT"})(W||(W={}));var L;(function(s){s.PRECALL_TEST_BEGIN="precall_begin",s.PRECALL_TEST_COMPLETE="precall_end",s.CALL_JOIN_BEGIN="call_join",s.NET_QUALITY_TEST_BEGIN="net_quality_test_begin",s.NET_QUALITY_TEST_END="net_quality_test_end",s.WEBSOCKET_CONNECTED="websocket_connected",s.TRANSPORT_CONNECTED="transport_connected",s.AUDIO_ON="audio_on",s.AUDIO_OFF="audio_off",s.VIDEO_ON="video_on",s.VIDEO_OFF="video_off",s.PARTICIPANT_ROLE="participant_role",s.PING_STAT="ping_stat",s.DISCONNECT="disconnect",s.RECONNECT_ATTEMPT="reconnect_attempt",s.SCREENSHARE_START_REQUESTED="screenshare_start_requested",s.SCREENSHARE_STARTED="screenshare_started",s.SCREENSHARE_STOPPED="screenshare_stopped",s.TAB_CHANGE="tab_change",s.BROWSER_BACKGROUNDED="browser_backgrounded",s.BROWSER_FOREGROUNDED="browser_foregrounded",s.DOMINANT_SPEAKER="dominant_speaker",s.AUDIO_DEVICES_UPDATES="audio_devices_updates",s.VIDEO_DEVICES_UPDATES="video_devices_updates",s.SPEAKER_DEVICES_UPDATES="speaker_devices_updates",s.SELECTED_MICROHPONE_UPDATE="selected_microphone_update",s.SELECTED_CAMERA_UPDATE="selected_camera_update",s.SELECTED_SPEAKER_UPDATE="selected_speaker_update",s.EXPECTED_VIDEO_RESOLUTION="expected_video_resolution",s.EXPECTED_SCREENSHARE_RESOLUTION="expected_screenshare_resolution",s.MEDIA_PERMISSION="media_permission",s.LEGACY_SWITCH="legacy_switch",s.AUDIO_PLAY_FAILED="audio_play_failed",s.VIDEO_PLAY_FAILED="video_play_failed",s.AUDIO_TRACK_MUTED="audio_track_muted",s.VIDEO_TRACK_MUTED="video_track_muted",s.IVS_PLAYER_REBUFFERING="ivs_player_rebuffering",s.IVS_PLAYER_AUDIO_BLOCKED="ivs_player_audio_blocked",s.IVS_PLAYER_PLAYBACK_BLOCKED="ivs_player_playback_blocked",s.IVS_PLAYER_ERROR="ivs_player_error",s.IVS_PLAYER_RECOVERABLE_ERROR="ivs_player_recoverable_error",s.IVS_PLAYER_WORKER_ERROR="ivs_player_worker_error",s.IVS_PLAYER_NETWORK_UNAVAILABLE="ivs_player_network_unavailable",s.LIVESTREAM_LATENCY="livestream_latency",s.IVS_PLAYER_ANALYTICS_EVENT="ivs_player_analytics_event",s.IVS_PLAYER_PLAYBACK_RATE_CHANGED="ivs_player_playback_rate_changed",s.IVS_PLAYER_QUALITY_CHANGED="ivs_player_quality_changed",s.IVS_PLAYER_INITIALIZED="ivs_player_initialized"})(L||(L={}));const Ty=new Map([[L.PRECALL_TEST_BEGIN,W.MINOR_EVENT],[L.PRECALL_TEST_COMPLETE,W.MINOR_EVENT],[L.CALL_JOIN_BEGIN,W.MAJOR_EVENT],[L.NET_QUALITY_TEST_BEGIN,W.MINOR_EVENT],[L.NET_QUALITY_TEST_END,W.MINOR_EVENT],[L.WEBSOCKET_CONNECTED,W.MINOR_EVENT],[L.TRANSPORT_CONNECTED,W.MAJOR_EVENT],[L.AUDIO_ON,W.MINOR_EVENT],[L.AUDIO_OFF,W.MINOR_EVENT],[L.VIDEO_ON,W.MINOR_EVENT],[L.VIDEO_OFF,W.MINOR_EVENT],[L.PARTICIPANT_ROLE,W.MINOR_EVENT],[L.PING_STAT,W.MAJOR_EVENT],[L.DISCONNECT,W.MAJOR_EVENT],[L.RECONNECT_ATTEMPT,W.MAJOR_EVENT],[L.SCREENSHARE_START_REQUESTED,W.MINOR_EVENT],[L.SCREENSHARE_STARTED,W.MINOR_EVENT],[L.SCREENSHARE_STOPPED,W.MINOR_EVENT],[L.TAB_CHANGE,W.MINOR_EVENT],[L.BROWSER_BACKGROUNDED,W.MINOR_EVENT],[L.BROWSER_FOREGROUNDED,W.MINOR_EVENT],[L.DOMINANT_SPEAKER,W.MINOR_EVENT],[L.AUDIO_DEVICES_UPDATES,W.MINOR_EVENT],[L.VIDEO_DEVICES_UPDATES,W.MINOR_EVENT],[L.SPEAKER_DEVICES_UPDATES,W.MINOR_EVENT],[L.SELECTED_MICROHPONE_UPDATE,W.MINOR_EVENT],[L.SELECTED_CAMERA_UPDATE,W.MINOR_EVENT],[L.SELECTED_SPEAKER_UPDATE,W.MINOR_EVENT],[L.MEDIA_PERMISSION,W.MINOR_EVENT],[L.LEGACY_SWITCH,W.MINOR_EVENT],[L.AUDIO_PLAY_FAILED,W.MINOR_EVENT],[L.VIDEO_PLAY_FAILED,W.MINOR_EVENT],[L.AUDIO_TRACK_MUTED,W.MINOR_EVENT],[L.VIDEO_TRACK_MUTED,W.MINOR_EVENT],[L.IVS_PLAYER_REBUFFERING,W.MAJOR_EVENT],[L.IVS_PLAYER_AUDIO_BLOCKED,W.MAJOR_EVENT],[L.IVS_PLAYER_PLAYBACK_BLOCKED,W.MAJOR_EVENT],[L.IVS_PLAYER_ERROR,W.MAJOR_EVENT],[L.IVS_PLAYER_RECOVERABLE_ERROR,W.MAJOR_EVENT],[L.IVS_PLAYER_WORKER_ERROR,W.MAJOR_EVENT],[L.IVS_PLAYER_NETWORK_UNAVAILABLE,W.MAJOR_EVENT],[L.LIVESTREAM_LATENCY,W.MAJOR_EVENT],[L.IVS_PLAYER_ANALYTICS_EVENT,W.MINOR_EVENT],[L.IVS_PLAYER_PLAYBACK_RATE_CHANGED,W.MINOR_EVENT],[L.IVS_PLAYER_QUALITY_CHANGED,W.MINOR_EVENT],[L.IVS_PLAYER_INITIALIZED,W.MINOR_EVENT],[L.EXPECTED_VIDEO_RESOLUTION,W.MINOR_EVENT],[L.EXPECTED_SCREENSHARE_RESOLUTION,W.MINOR_EVENT]]);class yy{constructor(){p(this,"events");this.events=[]}add(t){this.events.push(t)}flush(){return{entries:this.events.splice(0,25)}}}class Ey extends Tt{constructor({logger:e,peerId:r,apiHostnames:i,authToken:n}){super();p(this,"logger");p(this,"peerId");p(this,"eventStore");p(this,"apiEndpoint");p(this,"authToken");this.logger=e,this.peerId=r,this.authToken=n,this.apiEndpoint=`https://${i.daCollector}`,this.eventStore=new yy}async sendEventsChunkToServer(e){const r={payload:e,peerId:this.peerId},i=new AbortController,n=setTimeout(()=>i.abort(),3e3);try{return await fetch(this.apiEndpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.authToken}`},body:JSON.stringify(r),signal:i.signal}),!0}catch(o){return this.logger.error("callStats::sendEventsChunkToServer::catch",{peerId:this.peerId,endpoint:this.apiEndpoint,error:o instanceof Error?o.message:String(o),stack:o instanceof Error?o.stack:void 0}),!1}finally{clearTimeout(n)}}callEvent(e){e.timestamp=new Date,this.eventStore.add(e),this.emit(e.event,e.metaData),Ty.get(e.event)===W.MAJOR_EVENT&&this.flush()}async flush(){var r;const e=this.eventStore.flush();if((r=e==null?void 0:e.entries)!=null&&r.length){const i=await this.sendEventsChunkToServer(e);return i||e.entries.forEach(n=>{this.eventStore.add(n)}),i}return!1}}var jm;(function(s){s.CHROMIUM="chromum",s.FIREFOX="firefox",s.SAFARI="safari"})(jm||(jm={}));const Gm={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var ts;(function(s){s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.SPEAKER="SPEAKER",s.SCREENSHARE="SCREENSHARE"})(ts||(ts={}));var Wm;(function(s){s[s.INIT=0]="INIT",s[s.ACCEPTED=1]="ACCEPTED",s[s.DENIED=2]="DENIED",s[s.SYS_DENIED=3]="SYS_DENIED",s[s.FAILED=4]="FAILED",s[s.NOTFOUND=5]="NOTFOUND",s[s.NOT_APPLICABLE=6]="NOT_APPLICABLE"})(Wm||(Wm={}));function Un(s){return s?s.split(".").slice(0,2).concat(["0","0"]).join("."):""}function Dd({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function Nd({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}const Jm=240,Km=720,zm=8,Ym=3,Ld=10,Vd=.02,xd=.03;function er({stat:s,weight:t,rangeMin:e,rangeMax:r,rangeRankingDirection:i}){return s==null?t:e===r?i==="UP"?s<=e?t:0:s>=r?t:0:i==="UP"?(1-Math.max(Math.min(r,Math.abs(s))-e,0)/(r-e))*t:i==="DOWN"?Math.max(Math.min(r,Math.abs(s))-e,0)/(r-e)*t:t}function Qm({isLowQualityVideo:s,isVideoStuck:t,isVideoLagging:e,jitterQuality:r,packetsLostQuality:i}){const n=.8*((s?.85:1)*(e?.7:1)*(t?.5:1))+.2*(r*i);return Math.round((n+Number.EPSILON)*100)/100}function Xm({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function Zm({packetsLost:s,packetsSent:t,jitter:e}){const i=er({stat:Xm({packetsLost:s,packetsSent:t}),weight:.7,rangeMin:0,rangeMax:Ld,rangeRankingDirection:"UP"}),o=er({stat:e,weight:.3,rangeMin:Vd,rangeMax:xd,rangeRankingDirection:"UP"});return i+o}function by({frameWidth:s,isScreenShare:t}){return s<(t?Km:Jm)}function wy({framesPerSecond:s,isScreenShare:t}){return s<(t?Ym:zm)}function Py({framesEncoded:s}){return s===0}function eg({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsSent:r,jitter:i,isScreenShare:n,framesEncoded:o}){const c=er({stat:Xm({packetsLost:e,packetsSent:r}),weight:1,rangeMin:0,rangeMax:Ld,rangeRankingDirection:"UP"}),d=er({stat:i,weight:1,rangeMin:Vd,rangeMax:xd,rangeRankingDirection:"UP"}),l=by({frameWidth:s,isScreenShare:n}),u=wy({framesPerSecond:t,isScreenShare:n}),h=Py({framesEncoded:o,isScreenShare:n});return Qm({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:h,jitterQuality:d,packetsLostQuality:c})}function tg({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}function sg({concealmentEvents:s,packetsLost:t,packetsReceived:e,jitter:r}){const n=er({stat:s,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),o=.5,c=er({stat:tg({packetsLost:t,packetsReceived:e}),weight:o,rangeMin:0,rangeMax:Ld,rangeRankingDirection:"UP"}),l=er({stat:r,weight:.3,rangeMin:Vd,rangeMax:xd,rangeRankingDirection:"UP"});return n+c+l}function ky({framesDecoded:s}){return s===0}function _y({framesPerSecond:s,isScreenShare:t}){return s<(t?Ym:zm)}function Cy({frameWidth:s,isScreenShare:t}){return s<(t?Km:Jm)}function rg({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsReceived:r,jitter:i,isScreenShare:n,framesDecoded:o}){const c=er({stat:tg({packetsLost:e,packetsReceived:r}),weight:1,rangeMin:0,rangeMax:Ld,rangeRankingDirection:"UP"}),d=er({stat:i,weight:1,rangeMin:Vd,rangeMax:xd,rangeRankingDirection:"UP"}),l=Cy({frameWidth:s,isScreenShare:n}),u=_y({framesPerSecond:t,isScreenShare:n}),h=ky({framesDecoded:o,isScreenShare:n});return Qm({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:h,jitterQuality:d,packetsLostQuality:c})}class tr{constructor(t){p(this,"pc1");p(this,"pc2");p(this,"constrainVideoBitrateKbps");p(this,"constrainOfferToRemoveVideoFec",!1);p(this,"iceCandidateFilter");const e=new RTCPeerConnection(t),r=new RTCPeerConnection(t);this.pc1=e,this.pc2=r,this.iceCandidateFilter=tr.noFilter,this.pc1.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc2)),this.pc2.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc1))}static parseCandidate(t){const e="candidate:",r=t.indexOf(e)+e.length,i=t.substr(r).split(" ");return{type:i[7],protocol:i[2],address:i[4]}}static isNotHostCandidate(t){return t.type!=="host"}static isHost(t){return t.type==="host"}static isRelay(t){return t.type==="relay"}static isReflexive(t){return t.type==="srflx"}static noFilter(t){return!0}onIceCandidate(t,e){if(e.candidate){const r=tr.parseCandidate(e.candidate.candidate);this.iceCandidateFilter(r)&&t.addIceCandidate(e.candidate)}}setIceCandidateFilter(t){this.iceCandidateFilter=t}constrainVideoBitrate(t){this.constrainVideoBitrateKbps=t}disableVideoFec(){this.constrainOfferToRemoveVideoFec=!0}gotOffer(t){this.constrainOfferToRemoveVideoFec&&(t.sdp=t.sdp.replace(/(m=video 1 [^\r]+)(116 117)(\r\n)/g,`$1\r
|
|
7
7
|
`),t.sdp=t.sdp.replace(/a=rtpmap:116 red\/90000\r\n/g,""),t.sdp=t.sdp.replace(/a=rtpmap:117 ulpfec\/90000\r\n/g,""),t.sdp=t.sdp.replace(/a=rtpmap:98 rtx\/90000\r\n/g,""),t.sdp=t.sdp.replace(/a=fmtp:98 apt=116\r\n/g,"")),this.pc1.setLocalDescription(t),this.pc2.setRemoteDescription(t),this.pc2.createAnswer().then(this.gotAnswer.bind(this),this.reportFatal.bind(this))}gotAnswer(t){this.constrainVideoBitrateKbps&&(t.sdp=t.sdp.replace(/a=mid:video\r\n/g,`a=mid:video\r
|
|
8
8
|
b=AS:${this.constrainVideoBitrateKbps}\r
|
|
9
|
-
`)),this.pc2.setLocalDescription(t),this.pc1.setRemoteDescription(t)}establishConnection(){this.pc1.createOffer().then(this.gotOffer.bind(this),this.reportFatal.bind(this))}reportFatal(t){console.error("Error:",t)}async getRoundTripTime(){const[t,e]=await Promise.all([this.pc1.getStats(),this.pc2.getStats()]);let r,i;if(t.forEach(n=>{n.type==="candidate-pair"&&n.nominated===!0&&n.bytesSent>0&&(r=n)}),e.forEach(n=>{n.type==="candidate-pair"&&n.nominated===!0&&n.bytesReceived>0&&(i=n)}),r&&i)try{if(r.currentRoundTripTime&&i.currentRoundTripTime)return{rtt:r.currentRoundTripTime,backendRTT:i.currentRoundTripTime};const n=(i.lastPacketReceivedTimestamp-r.lastPacketSentTimestamp)/1e3;return{rtt:n,backendRTT:n}}catch(n){return}}close(){this.pc1.close(),this.pc2.close()}}class sg extends Tt{constructor(e){super();p(this,"call");p(this,"timeOut");this.call=new tr(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 _y=8,Cy=1/1e3;class Ry extends sg{constructor(e){super(e);p(this,"senderChannel");p(this,"recieveChannel");p(this,"startTime");p(this,"lastBitrateMeasureTime");p(this,"sentPayloadBytes",0);p(this,"recievedPayloadBytes",0);p(this,"lastReceivedPayloadBytes",0);p(this,"stopSending",!1);p(this,"testProgress",0);p(this,"samplePacket","");p(this,"finalBitrateSum",0);p(this,"bitRateSampels",0);p(this,"maxNumberOfPacketsToSend",0);p(this,"bytesToKeepBuffered",0);p(this,"testDurationSeconds",5);this.call.setIceCandidateFilter(tr.isNotHostCandidate),this.senderChannel=this.call.pc1.createDataChannel(null);for(let r=0;r<262144;r+=1)this.samplePacket+="h";this.maxNumberOfPacketsToSend=1,this.bytesToKeepBuffered=1024*this.maxNumberOfPacketsToSend,this.testDurationSeconds=4,this.senderChannel.addEventListener("open",this.sendingStep.bind(this)),this.call.pc2.addEventListener("datachannel",this.onRecieverChannel.bind(this))}sendingStep(){const e=new Date;this.startTime||(this.startTime=e,this.lastBitrateMeasureTime=e);for(let i=0;i!==this.maxNumberOfPacketsToSend&&!(this.senderChannel.bufferedAmount>=this.bytesToKeepBuffered);i+=1){this.sentPayloadBytes+=this.samplePacket.length;try{this.senderChannel.send(this.samplePacket)}catch(n){}}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,i=r.getTime()-this.lastBitrateMeasureTime.getTime();if(i>=1e3){const o=(this.recievedPayloadBytes-this.lastReceivedPayloadBytes)*_y/(i/1e3);this.finalBitrateSum+=o,this.bitRateSampels+=1,this.lastReceivedPayloadBytes=this.recievedPayloadBytes,this.lastBitrateMeasureTime=r}if(this.stopSending&&this.sentPayloadBytes===this.recievedPayloadBytes){const n=this.finalBitrateSum/this.bitRateSampels;this.testComplete({throughput:Math.round(n*Cy)})}}testComplete(e){this.call.getRoundTripTime().then(({rtt:r,backendRTT:i})=>super.testComplete({RTT:r,backendRTT:i,throughput:e.throughput}))}onRecieverChannel(e){this.recieveChannel=e.channel,this.recieveChannel.addEventListener("message",this.onMessageRecieved.bind(this))}}class oh extends sg{constructor(e,r=tr.noFilter){super(e);p(this,"ch1");p(this,"ch2");this.call.setIceCandidateFilter(r);const i=this.call.pc1.createDataChannel(null);this.ch1=i,i.addEventListener("open",()=>{i.send("hello")}),i.addEventListener("message",this.onCh1Recieve.bind(this)),this.call.pc2.addEventListener("datachannel",this.dataChannelHandler.bind(this))}onCh1Recieve(e){e.data!=="world"?this.hangup("Invalid data transmitted."):this.testComplete({connectivity:!0})}onCh2Recieve(e){if(e.data!=="hello")this.hangup("Invalid data transmitted.");else try{this.ch2.send("world")}catch(r){}}dataChannelHandler(e){const r=e.channel;this.ch2=r,r.addEventListener("message",this.onCh2Recieve.bind(this))}hangup(e){this.testFailed(e)}}class Iy extends oh{constructor(t){super(t,tr.isHost)}}class Ay extends oh{constructor(t){super(t,tr.isRelay)}}class My extends oh{constructor(t){super(t,tr.isReflexive)}}const rg=[{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"}];class ig{constructor(){p(this,"transport");p(this,"candidatePair");p(this,"outboundVideoRtp",new Map);p(this,"inboundVideoRtp",new Map);p(this,"outboundAudioRtp",new Map);p(this,"inboundAudioRtp",new Map);p(this,"remoteInboundRtp",new Map);p(this,"producerStreamMap",new Map);p(this,"consumerStreamMap",new Map);p(this,"staleProducerStreamMap",!1);p(this,"staleConsumerStreamMap",!1)}}class ng extends Tt{constructor(){super();p(this,"observer");p(this,"outboundProducerMap",new Map);p(this,"inboundConsumerMap",new Map);p(this,"consumerPeerIdMap",new Map);p(this,"pausedConsumerMap",new Map);p(this,"pausedProducerMap",new Map);p(this,"overallProducingTransportsStatsMap",{});p(this,"overallConsumingTransportsStatsMap",{});p(this,"overallConsumersStatsMap",{});p(this,"overallProducersStatsMap",{});p(this,"videoProducerToStatsMap",new Map);p(this,"audioProducerToStatsMap",new Map);p(this,"videoConsumerToStatsMap",new Map);p(this,"audioConsumerToStatsMap",new Map);p(this,"consumerIdsWithFreezedVideo",new Set);p(this,"consumerIdsWithFreezedAudio",new Set);p(this,"producerIdsWithFreezedVideo",new Set);p(this,"producerIdsWithFreezedAudio",new Set);p(this,"freezedProducingTransportIds",new Set);p(this,"freezedConsumingTransportIds",new Set);p(this,"screenShareProducers",new Set);p(this,"screenShareConsumers",new Set);p(this,"callStatsInstance");this.observer=new Tt}async registerProducer(e){await this.generateProducerStreamMap(e),e.on("close",this.deregisterProducer.bind(this,e)),e.on("pause",this.pauseProducer.bind(this,e.id)),e.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)}pauseProducer(e){this.pausedProducerMap.set(e,{lastReportCalculated:!1})}resumeProducer(e){this.pausedProducerMap.delete(e)}processInboundConsumerVideoStats(e,r,i){var o,c;const n=((c=(o=this==null?void 0:this.callStatsInstance)==null?void 0:o.consumerSharedMediaStatesMap)==null?void 0:c.get(e))||{};r.totalVideoPacketsReceived===i.packetsReceived?(this.consumerIdsWithFreezedVideo.add(e),this.callStatsInstance&&n.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","pause",e))):(r.totalVideoPacketsReceived=i.packetsReceived,this.consumerIdsWithFreezedVideo.has(e)&&(this.consumerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&n.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","resume",e))))}processInboundConsumerAudioStats(e,r,i){var o,c;const n=((c=(o=this==null?void 0:this.callStatsInstance)==null?void 0:o.consumerSharedMediaStatesMap)==null?void 0:c.get(e))||{};r.totalAudioPacketsReceived===i.packetsReceived?(this.consumerIdsWithFreezedAudio.add(e),this.callStatsInstance&&n.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","pause",e))):(r.totalAudioPacketsReceived=i.packetsReceived,this.consumerIdsWithFreezedAudio.has(e)&&(this.consumerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&n.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","resume",e))))}processOutboundProducerVideoStats(e,r,i){var o;const n=((o=this==null?void 0:this.callStatsInstance)==null?void 0:o.currentUserMediaStates)||{};r.totalVideoPacketsSent===i.packetsSent?(this.producerIdsWithFreezedVideo.add(e),this.callStatsInstance&&n.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","pause",e))):(r.totalVideoPacketsSent=i.packetsSent,this.producerIdsWithFreezedVideo.has(e)&&(this.producerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&n.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","resume",e))))}processOutboundProducerAudioStats(e,r,i){var o;const n=((o=this==null?void 0:this.callStatsInstance)==null?void 0:o.currentUserMediaStates)||{};r.totalAudioPacketsSent===i.packetsSent?(this.producerIdsWithFreezedAudio.add(e),this.callStatsInstance&&n.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","pause",e))):(r.totalAudioPacketsSent=i.packetsSent,this.producerIdsWithFreezedAudio.has(e)&&(this.producerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&n.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","resume",e))))}processProducingTransportStats(e,r,i){var u;const n=((u=this==null?void 0:this.callStatsInstance)==null?void 0:u.currentUserMediaStates)||{},{audio:o,video:c,screen:d}=n,l=o||c||d;r.totalPacketsSent===i.packetsSent?(this.freezedProducingTransportIds.add(e),this.callStatsInstance&&l&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","pause",e))):(r.totalPacketsSent=i.packetsSent,this.freezedProducingTransportIds.has(e)&&(this.freezedProducingTransportIds.delete(e),this.callStatsInstance&&l&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","resume",e))))}processConsumingTransportStats(e,r,i){var c,d;const o=!!Array.from(((d=(c=this==null?void 0:this.callStatsInstance)==null?void 0:c.consumerSharedMediaStatesMap)==null?void 0:d.values())||[]).reduce((l,u)=>l||u.audio||u.video||u.screen,!1);r.totalPacketsReceived===i.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=i.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))))}async registerConsumer(e){await this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.on("close",this.deregisterConsumer.bind(this,e)),e.on("pause",this.pauseConsumer.bind(this,e.id)),e.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)}pauseConsumer(e){this.pausedConsumerMap.set(e,{lastReportCalculated:!1})}resumeConsumer(e){this.pausedConsumerMap.delete(e)}async generateProducerStreamMap(e,r=!1){const i=await e.getStats(),n=r?this.getProducerStatsFromReport(this.parseRTCReport(i,["outbound-rtp","remote-inbound-rtp"],!1,e.id))[0]:void 0;for(const o of i.values())switch(o.type){case"outbound-rtp":{this.outboundProducerMap.set(o.id,e.id);break}}return n}async generateConsumerStreamMap(e,r=!1){const i=await e.getStats(),n=r?this.getConsumerStatsFromReport(this.parseRTCReport(i,["inbound-rtp"],!1,e.id))[0]:void 0;for(const o of i.values())switch(o.type){case"inbound-rtp":{this.inboundConsumerMap.set(o.id,e.id);break}}return n}deregisterProducer(e){this.outboundProducerMap.forEach((r,i)=>{r===e.id&&this.outboundProducerMap.delete(i)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.inboundConsumerMap.forEach((r,i)=>{r===e.id&&this.inboundConsumerMap.delete(i)}),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(i=>{const n=i.framesEncoded>0,o=i.packetsSent>0,c=i.frameWidth&&i.frameHeight;return n&&o&&!!c})||e[e.length-1]}parseRTCReport(e,r=[],i=!1,n=void 0,o=void 0){var k,I,D,N,B,U,j,Z,re,F,ee,we,vt;const c=e,d=new ig,l=r.length?new Set(r):void 0,u=[],h=[],g=[],v=new Map,y=new Map;for(const A of c.values()){if(l){if(l.size===0)break;if(l.has(A.type))i&&l.delete(A.type);else continue}switch(A.type){case"local-candidate":{u.push(this.getIceCandidateStats(A));break}case"remote-candidate":{h.push(this.getIceCandidateStats(A));break}case"candidate-pair":{const{nominated:S}=A,{selected:w}=A,$=A,ce={nominated:S!=null?S:w,currentRoundTripTime:$.currentRoundTripTime,totalRoundTripTime:$.totalRoundTripTime,bytesReceived:$.bytesReceived,bytesSent:$.bytesSent,availableOutgoingBitrate:$.availableOutgoingBitrate,availableIncomingBitrate:$.availableIncomingBitrate,lastPacketReceivedTimestamp:$.lastPacketReceivedTimestamp,lastPacketSentTimestamp:$.lastPacketSentTimestamp,localCandidateId:$.localCandidateId,remoteCandidateId:$.remoteCandidateId,bytesDiscardedOnSend:$.bytesDiscardedOnSend,packetsSent:$.packetsSent,packetsReceived:$.packetsReceived,packetsDiscardedOnSend:$.packetsDiscardedOnSend};g.push(ce),(A.nominated===!0||A.selected===!0)&&(d.candidatePair=ce);break}case"transport":{const S=A;o&&(o.producing&&(this.overallProducingTransportsStatsMap[o.id]||(this.overallProducingTransportsStatsMap[o.id]={totalPacketsSent:0})),o.consuming&&(this.overallConsumingTransportsStatsMap[o.id]||(this.overallConsumingTransportsStatsMap[o.id]={totalPacketsReceived:0})));const w={bytesReceived:S.bytesReceived,bytesSent:S.bytesSent,packetsSent:S.packetsSent,packetsReceived:S.packetsReceived,dtlsCipher:S.dtlsCipher,dtlsState:S.dtlsState,iceRole:S.iceRole};if(d.transport=w,o){if(o.producing){const $=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,$,w)}if(o.consuming){const $=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,$,w)}}break}case"remote-inbound-rtp":{const S=A,w={jitter:S.jitter,fractionLost:S.fractionLost,roundTripTime:S.roundTripTime,roundTripTimeMeasurements:S.roundTripTimeMeasurements,totalRoundTripTime:S.totalRoundTripTime,packetsLost:S.packetsLost};d.remoteInboundRtp.set(S.localId,w);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(A.id))break;const S=A,w=n||this.outboundProducerMap.get(A.id),$=this.pausedProducerMap.get(w);if($){if($.lastReportCalculated===!0)break;this.pausedProducerMap.set(w,{lastReportCalculated:!0})}this.overallProducersStatsMap[w]||(this.overallProducersStatsMap[w]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const ce=this.overallProducersStatsMap[w];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.outboundProducerMap.has(A.id)){d.staleProducerStreamMap=!0;break}const fe=this.callStatsInstance.producers.get(w);if(((k=fe==null?void 0:fe.track)==null?void 0:k.readyState)==="ended")break;d.producerStreamMap.has(w)||d.producerStreamMap.set(w,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const V={bytesSent:S.bytesSent,packetsSent:S.packetsSent,nackCount:S.nackCount,ssrc:S.ssrc,mid:S.mid,active:S.active,codecId:S.codecId,headerBytesSent:S.headerBytesSent||0,totalPacketSendDelay:S.totalPacketSendDelay||0};if(S.mediaType==="video"||S.kind==="video"){const _=S,He={frameHeight:_.frameHeight,frameWidth:_.frameWidth,framesEncoded:_.framesEncoded,framesDropped:_.framesDropped,framesPerSecond:_.framesPerSecond,framesSent:_.framesSent,keyFramesEncoded:_.keyFramesEncoded,firCount:_.firCount,encoderImplementation:_.encoderImplementation,hugeFramesSent:_.hugeFramesSent,pliCount:_.pliCount,qpSum:_.qpSum,qualityLimitationDurations:_.qualityLimitationDurations,qualityLimitationReason:_.qualityLimitationReason,qualityLimitationResolutionChanges:_.qualityLimitationResolutionChanges,totalEncodeTime:_.targetBitrate,totalPacketSendDelay:_.totalPacketSendDelay,retransmittedBytesSent:_.retransmittedBytesSent,retransmittedPacketsSent:_.retransmittedPacketsSent,scalabilityMode:_.scalabilityMode,powerEfficientEncoder:_.powerEfficientEncoder,...V};d.outboundVideoRtp.set(A.id,He),d.producerStreamMap.get(w).outboundVideoRtpId.push(A.id),this.processOutboundProducerVideoStats(w,ce,He)}else if(S.mediaType==="audio"||S.kind==="audio"){const _=S,He={retransmittedBytesSent:_.retransmittedBytesSent,retransmittedPacketsSent:_.retransmittedPacketsSent,...V};d.outboundAudioRtp.set(A.id,He),d.producerStreamMap.get(w).outboundAudioRtpId.push(A.id),this.processOutboundProducerAudioStats(w,ce,He)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(A.id))break;const S=A,w=n||this.inboundConsumerMap.get(A.id),$=this.pausedConsumerMap.get(w);if($){if($.lastReportCalculated===!0)break;this.pausedConsumerMap.set(w,{lastReportCalculated:!0})}if(S.ssrc===1234)break;this.overallConsumersStatsMap[w]||(this.overallConsumersStatsMap[w]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const ce=this.overallConsumersStatsMap[w];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.inboundConsumerMap.has(A.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(w)||d.consumerStreamMap.set(w,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const fe={bytesReceived:S.bytesReceived,packetsReceived:S.packetsReceived,packetsLost:S.packetsLost>=0?S.packetsLost:0,jitter:S.jitter,nackCount:S.nackCount,jitterBufferDelay:S.jitterBufferDelay,jitterBufferEmittedCount:S.jitterBufferEmittedCount,lastPacketReceivedTimestamp:S.lastPacketReceivedTimestamp,ssrc:S.ssrc,mid:S.mid,codecId:S.codecId,headerBytesReceived:S.headerBytesReceived||0,packetsDiscarded:S.packetsDiscarded||0,jitterBufferMinimumDelay:S.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:S.jitterBufferTargetDelay||0};if(S.mediaType==="video"||S.kind==="video"){const V=S,_={frameHeight:V.frameHeight,frameWidth:V.frameWidth,framesDecoded:V.framesDecoded,framesDropped:V.framesDropped,framesPerSecond:V.framesPerSecond,framesReceived:V.framesReceived,keyFramesDecoded:V.keyFramesDecoded,firCount:V.firCount,decoderImplementation:V.decoderImplementation,pliCount:V.pliCount,totalProcessingDelay:V.totalProcessingDelay,qpSum:V.qpSum||0,totalAssemblyTime:V.totalAssemblyTime||0,totalDecodeTime:V.totalDecodeTime||0,totalFreezesDuration:V.totalFreezesDuration||0,totalInterFrameDelay:V.totalInterFrameDelay||0,totalPausesDuration:V.totalPausesDuration||0,totalSquaredInterFrameDelay:V.totalSquaredInterFrameDelay||0,freezeCount:V.freezeCount||0,pauseCount:V.pauseCount||0,powerEfficientDecoder:V.powerEfficientDecoder,...fe};_.score=tg({frameWidth:_.frameWidth||0,framesDecoded:(_.framesDecoded||0)-(((I=this.videoConsumerToStatsMap.get(w))==null?void 0:I.framesDecoded)||0),framesPerSecond:_.framesPerSecond||0,packetsLost:(_.packetsLost||0)-(((D=this.videoConsumerToStatsMap.get(w))==null?void 0:D.packetsLost)||0),packetsReceived:(_.packetsReceived||0)-(((N=this.videoConsumerToStatsMap.get(w))==null?void 0:N.packetsReceived)||0),jitter:_.jitter||0,isScreenShare:this.screenShareConsumers.has(w)}),y.set(w,{score:+(_.score*10).toFixed(),frameWidth:_.frameWidth||0,frameHeight:_.frameHeight||0,framesPerSecond:_.framesPerSecond||0,packetsLostPercentage:Dd({packetsLost:(_.packetsLost||0)-(((B=this.videoConsumerToStatsMap.get(w))==null?void 0:B.packetsLost)||0),packetsReceived:(_.packetsReceived||0)-(((U=this.videoConsumerToStatsMap.get(w))==null?void 0:U.packetsReceived)||0)}),jitter:_.jitter||0,isScreenShare:this.screenShareConsumers.has(w),bitrate:((_.bytesReceived||0)-(((j=this.videoConsumerToStatsMap.get(w))==null?void 0:j.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(w,_),d.inboundVideoRtp.set(A.id,_),d.consumerStreamMap.get(w).inboundVideoRtpId.push(A.id),this.processInboundConsumerVideoStats(w,ce,_)}else if(S.mediaType==="audio"||S.kind==="audio"){const V=S,_={audioLevel:V.audioLevel,concealedSamples:V.concealedSamples,concealmentEvents:V.concealmentEvents,totalAudioEnergy:V.totalAudioEnergy,totalSamplesDuration:V.totalSamplesDuration,totalSamplesReceived:V.totalSamplesReceived,fecPacketsDiscarded:V.fecPacketsDiscarded||0,fecPacketsReceived:V.fecPacketsReceived||0,insertedSamplesForDeceleration:V.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:V.removedSamplesForAcceleration||0,silentConcealedSamples:V.silentConcealedSamples||0,playoutId:V.playoutId,...fe};_.score=eg({concealmentEvents:(_.concealmentEvents||0)-(((Z=this.audioConsumerToStatsMap.get(w))==null?void 0:Z.concealmentEvents)||0),packetsLost:(_.packetsLost||0)-(((re=this.audioConsumerToStatsMap.get(w))==null?void 0:re.packetsLost)||0),packetsReceived:(_.packetsReceived||0)-(((F=this.audioConsumerToStatsMap.get(w))==null?void 0:F.packetsReceived)||0),jitter:_.jitter||0}),y.set(w,{score:+(_.score*10).toFixed(),packetsLostPercentage:Dd({packetsLost:(_.packetsLost||0)-(((ee=this.audioConsumerToStatsMap.get(w))==null?void 0:ee.packetsLost)||0),packetsReceived:(_.packetsReceived||0)-(((we=this.audioConsumerToStatsMap.get(w))==null?void 0:we.packetsReceived)||0)}),jitter:_.jitter||0,isScreenShare:this.screenShareConsumers.has(w),bitrate:((_.bytesReceived||0)-(((vt=this.audioConsumerToStatsMap.get(w))==null?void 0:vt.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(w,_),d.inboundAudioRtp.set(A.id,_),d.consumerStreamMap.get(w).inboundAudioRtpId.push(A.id),this.processInboundConsumerAudioStats(w,ce,_)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}}}if(d.producerStreamMap.forEach((A,S)=>{var w,$,ce,fe,V,_,He,nd,ad,od,cd,dd,ld,ud,hd,pd,md,gd,fd,vd,Sd,Td,yd;if(A.outboundVideoRtpId.length>0){const Te=[];A.outboundVideoRtpId.forEach(jp=>{Te.push(d.outboundVideoRtp.get(jp))});const se=this.getWorkingSimulcastVideoStats(Te);se.score=Xm({frameWidth:se.frameWidth||0,framesPerSecond:se.framesPerSecond||0,jitter:((w=se.remoteData)==null?void 0:w.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsSent:(se.packetsSent||0)-((($=this.videoProducerToStatsMap.get(S))==null?void 0:$.packetsSent)||0),packetsLost:(((ce=se.remoteData)==null?void 0:ce.packetsLost)||0)-(((V=(fe=this.videoProducerToStatsMap.get(S))==null?void 0:fe.remoteData)==null?void 0:V.packetsLost)||0),framesEncoded:(se.framesEncoded||0)-(((_=this.videoProducerToStatsMap.get(S))==null?void 0:_.framesEncoded)||0)}),v.set(S,{score:+(se.score*10).toFixed(),frameWidth:se.frameWidth||0,frameHeight:se.frameHeight||0,framesPerSecond:se.framesPerSecond||0,jitter:((He=se.remoteData)==null?void 0:He.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsLostPercentage:Od({packetsSent:(se.packetsSent||0)-(((nd=this.videoProducerToStatsMap.get(S))==null?void 0:nd.packetsSent)||0),packetsLost:(((ad=se.remoteData)==null?void 0:ad.packetsLost)||0)-(((cd=(od=this.videoProducerToStatsMap.get(S))==null?void 0:od.remoteData)==null?void 0:cd.packetsLost)||0)}),bitrate:((se.bytesSent||0)-(((dd=this.videoProducerToStatsMap.get(S))==null?void 0:dd.bytesSent)||0))*8/7,cpuLimitations:se.qualityLimitationReason==="cpu",bandwidthLimitations:se.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(S,se)}else if(A.outboundAudioRtpId.length>0){const Te=d.outboundAudioRtp.get(A.outboundAudioRtpId[0]);Te.score=Qm({packetsSent:(Te.packetsSent||0)-(((ld=this.audioProducerToStatsMap.get(S))==null?void 0:ld.packetsSent)||0),packetsLost:(((ud=Te.remoteData)==null?void 0:ud.packetsLost)||0)-(((pd=(hd=this.audioProducerToStatsMap.get(S))==null?void 0:hd.remoteData)==null?void 0:pd.packetsLost)||0),jitter:((md=Te.remoteData)==null?void 0:md.jitter)||0}),v.set(S,{score:+(Te.score*10).toFixed(),bitrate:((Te.bytesSent||0)-(((gd=this.audioProducerToStatsMap.get(S))==null?void 0:gd.bytesSent)||0))*8/7,packetsLostPercentage:Od({packetsSent:(Te.packetsSent||0)-(((fd=this.audioProducerToStatsMap.get(S))==null?void 0:fd.packetsSent)||0),packetsLost:(((vd=Te.remoteData)==null?void 0:vd.packetsLost)||0)-(((Td=(Sd=this.audioProducerToStatsMap.get(S))==null?void 0:Sd.remoteData)==null?void 0:Td.packetsLost)||0)}),jitter:((yd=Te.remoteData)==null?void 0:yd.jitter)||0,isScreenShare:this.screenShareProducers.has(S)}),this.audioProducerToStatsMap.set(S,Te)}}),g.forEach(A=>{const S=u.find($=>$.id===A.localCandidateId?(A.localCandidateId=$.id,$):null),w=h.find($=>$.id===A.remoteCandidateId?(A.remoteCandidateId=$.id,$):null);S&&(A.localCandidateType=S.type,A.localCandidateAddress=Un(S.address),A.localCandidatePort=S.port,A.localCandidateProtocol=S.protocol,A.localCandidateUrl=S.url,A.localCandidateNetworkType=S.networkType,A.localCandidateRelatedAddress=Un(S.relatedAddress),A.localCandidateRelatedPort=S.relatedPort),w&&(A.remoteCandidateType=w.type,A.remoteCandidateAddress=Un(w.address),A.remoteCandidatePort=w.port,A.remoteCandidateProtocol=w.protocol,A.remoteCandidateUrl=w.url)}),d.candidatePair&&(d.transport?(d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.availableIncomingBitrate=d.candidatePair.availableIncomingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:d.candidatePair.availableIncomingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=g),d.transport&&!d.transport.roundTripTime){let A=0,S=0;d.remoteInboundRtp.forEach((w,$)=>{w.roundTripTime&&w.roundTripTime>A&&(A=w.roundTripTime,S=w.totalRoundTripTime)}),d.transport.roundTripTime=A,d.transport.totalRoundTripTime=S}if(y.size>0)try{this.observer.emit("consumer_score",y)}catch(A){}if(v.size>0)try{this.observer.emit("producer_score",v)}catch(A){}return d}async getProducersReport(e){const r=e.map(i=>this.generateProducerStreamMap(i,!0));return r.length>0?Promise.all(r):void 0}async getConsumersReport(e){const r=e.map(i=>this.generateConsumerStreamMap(i,!0));return r.length>0?Promise.all(r):void 0}async getTransportReport(e){return e.getStats()}async getProcessedStats(e,r,i){const n=await this.getTransportReport(e),o={producing:i,consuming:r,id:e.id},c=n,d=this.parseRTCReport(c,["transport","candidate-pair","inbound-rtp","outbound-rtp","remote-inbound-rtp","local-candidate","remote-candidate"],!1,void 0,o);if(!d)return;const l={stats:d.transport,transportId:e.id,consuming:r,producing:i},u=d.staleProducerStreamMap?void 0:this.getProducerStatsFromReport(d),h=d.staleConsumerStreamMap?void 0:this.getConsumerStatsFromReport(d);return{transportReport:l,producerReport:u,consumerReport:h}}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((i,n)=>{var o,c;r.push({producerId:n,videoStats:i.outboundVideoRtpId.map(d=>e.outboundVideoRtp.get(d)),audioStats:i.outboundAudioRtpId.map(d=>e.outboundAudioRtp.get(d)),appData:((c=(o=this.callStatsInstance.producers)==null?void 0:o.get(n))==null?void 0:c.appData)||null})})}catch(i){this.callStatsInstance.logger.error("callStats::measurements::getProducerStatsFromReport",{error:{reason:i.reason,message:i.message}})}return r}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((i,n)=>{const{peerId:o,producerId:c,appData:d}=this.consumerPeerIdMap.get(n);r.push({consumerId:n,peerId:o,producerId:c,appData:d,videoStats:i.inboundVideoRtpId.map(l=>e.inboundVideoRtp.get(l)),audioStats:i.inboundAudioRtpId.map(l=>e.inboundAudioRtp.get(l))})})}catch(i){console.error("getConsumersReport: ",i,e)}return r}async getUserLocation(){return new Promise((e,r)=>{try{navigator.geolocation?navigator.geolocation.getCurrentPosition(i=>{e(i)}):r()}catch(i){r(i)}})}async getConnectivity(e){try{const r={iceServers:e||rg},i=new Promise((u,h)=>{try{const g=new Iy(r);g.addListener("done",u),g.addListener("failed",()=>{u({connectivity:!1})}),g.start(2e3)}catch(g){h(g)}}),n=new Promise((u,h)=>{try{const g=new Ay(r);g.addListener("done",u),g.addListener("failed",()=>{u({connectivity:!1})}),g.start(2e3)}catch(g){h(g)}}),o=new Promise((u,h)=>{try{const g=new My(r);g.addListener("done",u),g.addListener("failed",()=>{u({connectivity:!1})}),g.start(2e3)}catch(g){h(g)}}),[c,d,l]=await Promise.all([i,n,o]);return{host:c==null?void 0:c.connectivity,relay:d==null?void 0:d.connectivity,reflexive:l==null?void 0:l.connectivity}}catch(r){return{host:!1,relay:!1,reflexive:!1}}}async getThroughput(e){try{const i=await new Promise((n,o)=>{try{const c={iceServers:e||rg},d=new Ry(c);d.addListener("done",n),d.addListener("failed",o),d.start(1e4)}catch(c){o(c)}});return{throughput:i.throughput,fractionalLoss:0,RTT:i.RTT,jitter:0,backendRTT:i.backendRTT}}catch(r){return}}async getNetworkQuality(e){const[r,i]=await Promise.all([this.getConnectivity(e),this.getThroughput(e)]);return{connectivity:r,throughput:i==null?void 0:i.throughput,fractionalLoss:i==null?void 0:i.fractionalLoss,RTT:i==null?void 0:i.RTT,jitter:i==null?void 0:i.jitter,backendRTT:i==null?void 0:i.backendRTT}}async getNetworkInfo(e,r=!1){var o,c;if(r)return{effectiveNetworkType:(o=navigator.connection)==null?void 0:o.effectiveType};const[i,n]=await Promise.all([this.getConnectivity(e),this.getThroughput(e)]);return{effectiveNetworkType:(c=navigator.connection)==null?void 0:c.effectiveType,turnConnectivity:i?i.host||i.relay||i.reflexive:!1,connectivity:i,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}}}class Oy extends ng{}class ag extends ng{constructor(){super(...arguments);p(this,"producerMap",new Map);p(this,"consumerMap",new Map)}async registerProducer(e){this.producerMap.set(e.id,e),await this.generateProducerStreamMap(e),e.on("close",this.deregisterProducer.bind(this,e)),e.on("pause",this.pauseProducer.bind(this,e.id)),e.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)}async registerConsumer(e){this.consumerMap.set(e.id,e),await this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.on("close",this.deregisterConsumer.bind(this,e)),e.on("pause",this.pauseConsumer.bind(this,e.id)),e.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)}async generateConsumerStreamMap(e,r=!1){const i=await e.getStats(),n=this.parseRTCReport(i,["inbound-rtp"],!1,e.id),o=[...n.consumerStreamMap.values()][0],c=r?this.getConsumerStatsFromParsedConsumerStats(n,o,e.id):void 0;for(const d of i.values())switch(d.type){case"inbound-rtp":{this.inboundConsumerMap.set(d.id,e.id);break}}return c}deregisterProducer(e){this.producerMap.delete(e.id),this.outboundProducerMap.forEach((r,i)=>{r===e.id&&this.outboundProducerMap.delete(i)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.consumerMap.delete(e.id),this.inboundConsumerMap.forEach((r,i)=>{r===e.id&&this.inboundConsumerMap.delete(i)}),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=[],i=!1,n=void 0,o=void 0){var k,I,D,N,B,U,j,Z,re,F,ee,we,vt;const c=e,d=new ig,l=r.length?new Set(r):void 0,u=[],h=[],g=[],v=new Map,y=new Map;for(const A of c.values()){if(l){if(l.size===0)break;if(l.has(A.type))i&&l.delete(A.type);else continue}switch(A.type){case"local-candidate":{u.push(this.getIceCandidateStats(A));break}case"remote-candidate":{h.push(this.getIceCandidateStats(A));break}case"candidate-pair":{const{nominated:S}=A,{selected:w}=A,$=A,ce={nominated:S!=null?S:w,currentRoundTripTime:$.currentRoundTripTime,totalRoundTripTime:$.totalRoundTripTime,bytesReceived:$.bytesReceived,bytesSent:$.bytesSent,availableOutgoingBitrate:$.availableOutgoingBitrate,availableIncomingBitrate:$.availableIncomingBitrate,lastPacketReceivedTimestamp:$.lastPacketReceivedTimestamp,lastPacketSentTimestamp:$.lastPacketSentTimestamp,localCandidateId:$.localCandidateId,remoteCandidateId:$.remoteCandidateId,bytesDiscardedOnSend:$.bytesDiscardedOnSend,packetsSent:$.packetsSent,packetsReceived:$.packetsReceived,packetsDiscardedOnSend:$.packetsDiscardedOnSend};g.push(ce),(A.nominated===!0||A.selected===!0)&&(d.candidatePair=ce);break}case"transport":{const S=A;o&&(o.producing&&(this.overallProducingTransportsStatsMap[o.id]||(this.overallProducingTransportsStatsMap[o.id]={totalPacketsSent:0})),o.consuming&&(this.overallConsumingTransportsStatsMap[o.id]||(this.overallConsumingTransportsStatsMap[o.id]={totalPacketsReceived:0})));const w={bytesReceived:S.bytesReceived,bytesSent:S.bytesSent,packetsSent:S.packetsSent,packetsReceived:S.packetsReceived,dtlsCipher:S.dtlsCipher,dtlsState:S.dtlsState,iceRole:S.iceRole};if(d.transport=w,o){if(o.producing){const $=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,$,w)}if(o.consuming){const $=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,$,w)}}break}case"remote-inbound-rtp":{const S=A,w={jitter:S.jitter,fractionLost:S.fractionLost,roundTripTime:S.roundTripTime,roundTripTimeMeasurements:S.roundTripTimeMeasurements,totalRoundTripTime:S.totalRoundTripTime,packetsLost:S.packetsLost};d.remoteInboundRtp.set(S.localId,w);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(A.id))break;const S=A,w=n||this.outboundProducerMap.get(A.id),$=this.pausedProducerMap.get(w);if($){if($.lastReportCalculated===!0)break;this.pausedProducerMap.set(w,{lastReportCalculated:!0})}this.overallProducersStatsMap[w]||(this.overallProducersStatsMap[w]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const ce=this.overallProducersStatsMap[w];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.outboundProducerMap.has(A.id)){d.staleProducerStreamMap=!0;break}const fe=this.callStatsInstance.producers.get(w);if(((k=fe==null?void 0:fe.track)==null?void 0:k.readyState)==="ended")break;d.producerStreamMap.has(w)||d.producerStreamMap.set(w,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const V={bytesSent:S.bytesSent,packetsSent:S.packetsSent,nackCount:S.nackCount,ssrc:S.ssrc,mid:S.mid,active:S.active,codecId:S.codecId,headerBytesSent:S.headerBytesSent||0,totalPacketSendDelay:S.totalPacketSendDelay||0};if(S.mediaType==="video"||S.kind==="video"){const _=S,He={frameHeight:_.frameHeight,frameWidth:_.frameWidth,framesEncoded:_.framesEncoded,framesDropped:_.framesDropped?_.framesDropped:_.droppedFrames,framesPerSecond:_.framesPerSecond?_.framesPerSecond:_.framerateMean,framesSent:_.framesSent,keyFramesEncoded:_.keyFramesEncoded,firCount:_.firCount,encoderImplementation:_.encoderImplementation,hugeFramesSent:_.hugeFramesSent,pliCount:_.pliCount,qpSum:_.qpSum,qualityLimitationReason:_.qualityLimitationReason,qualityLimitationDurations:_.qualityLimitationDurations,qualityLimitationResolutionChanges:_.qualityLimitationResolutionChanges,totalEncodeTime:_.totalEncodeTime,totalPacketSendDelay:_.totalEncodeTime,retransmittedBytesSent:_.retransmittedBytesSent,retransmittedPacketsSent:_.retransmittedPacketsSent,scalabilityMode:_.scalabilityMode,powerEfficientEncoder:_.powerEfficientEncoder,...V};d.outboundVideoRtp.set(A.id,He),d.producerStreamMap.get(w).outboundVideoRtpId.push(A.id),this.processOutboundProducerVideoStats(w,ce,He)}else if(S.mediaType==="audio"||S.kind==="audio"){const _=S,He={retransmittedBytesSent:_.retransmittedBytesSent,retransmittedPacketsSent:_.retransmittedPacketsSent,...V};d.outboundAudioRtp.set(A.id,He),d.producerStreamMap.get(w).outboundAudioRtpId.push(A.id),this.processOutboundProducerAudioStats(w,ce,He)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(A.id))break;const S=A,w=n||this.inboundConsumerMap.get(A.id),$=this.pausedConsumerMap.get(w);if($){if($.lastReportCalculated===!0)break;this.pausedConsumerMap.set(w,{lastReportCalculated:!0})}if(S.ssrc===1234)break;this.overallConsumersStatsMap[w]||(this.overallConsumersStatsMap[w]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const ce=this.overallConsumersStatsMap[w];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.inboundConsumerMap.has(A.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(w)||d.consumerStreamMap.set(w,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const fe={bytesReceived:S.bytesReceived,packetsReceived:S.packetsReceived,packetsLost:S.packetsLost>=0?S.packetsLost:0,jitter:S.jitter,nackCount:S.nackCount,jitterBufferDelay:S.jitterBufferDelay,jitterBufferEmittedCount:S.jitterBufferEmittedCount,lastPacketReceivedTimestamp:S.lastPacketReceivedTimestamp,ssrc:S.ssrc,mid:S.mid,codecId:S.codecId,headerBytesReceived:S.headerBytesReceived||0,packetsDiscarded:S.packetsDiscarded||0,jitterBufferMinimumDelay:S.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:S.jitterBufferTargetDelay||0};if(S.mediaType==="video"||S.kind==="video"){const V=S,_={frameHeight:V.frameHeight,frameWidth:V.frameWidth,framesDecoded:V.framesDecoded,framesDropped:V.framesDropped?V.framesDropped:V.droppedFrames,framesPerSecond:V.framesPerSecond?V.framesPerSecond:V.framerateMean,framesReceived:V.framesReceived,keyFramesDecoded:V.keyFramesDecoded,firCount:V.firCount,decoderImplementation:V.decoderImplementation,pliCount:V.pliCount,totalProcessingDelay:V.totalProcessingDelay,qpSum:V.qpSum||0,totalAssemblyTime:V.totalAssemblyTime||0,totalDecodeTime:V.totalDecodeTime||0,totalFreezesDuration:V.totalFreezesDuration||0,totalInterFrameDelay:V.totalInterFrameDelay||0,totalPausesDuration:V.totalPausesDuration||0,totalSquaredInterFrameDelay:V.totalSquaredInterFrameDelay||0,freezeCount:V.freezeCount||0,pauseCount:V.pauseCount||0,powerEfficientDecoder:V.powerEfficientDecoder,...fe};_.score=tg({frameWidth:_.frameWidth||0,framesDecoded:(_.framesDecoded||0)-(((I=this.videoConsumerToStatsMap.get(w))==null?void 0:I.framesDecoded)||0),framesPerSecond:_.framesPerSecond||0,packetsLost:(_.packetsLost||0)-(((D=this.videoConsumerToStatsMap.get(w))==null?void 0:D.packetsLost)||0),packetsReceived:(_.packetsReceived||0)-(((N=this.videoConsumerToStatsMap.get(w))==null?void 0:N.packetsReceived)||0),jitter:_.jitter||0,isScreenShare:this.screenShareConsumers.has(w)}),y.set(w,{score:+(_.score*10).toFixed(),frameWidth:_.frameWidth||0,frameHeight:_.frameHeight||0,framesPerSecond:_.framesPerSecond||0,packetsLostPercentage:Dd({packetsLost:(_.packetsLost||0)-(((B=this.videoConsumerToStatsMap.get(w))==null?void 0:B.packetsLost)||0),packetsReceived:(_.packetsReceived||0)-(((U=this.videoConsumerToStatsMap.get(w))==null?void 0:U.packetsReceived)||0)}),jitter:_.jitter||0,isScreenShare:this.screenShareConsumers.has(w),bitrate:((_.bytesReceived||0)-(((j=this.videoConsumerToStatsMap.get(w))==null?void 0:j.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(w,_),d.inboundVideoRtp.set(A.id,_),d.consumerStreamMap.get(w).inboundVideoRtpId.push(A.id),this.processInboundConsumerVideoStats(w,ce,_)}else if(S.mediaType==="audio"||S.kind==="audio"){const V=S,_={audioLevel:V.audioLevel,concealedSamples:V.concealedSamples,concealmentEvents:V.concealmentEvents,totalAudioEnergy:V.totalAudioEnergy,totalSamplesDuration:V.totalSamplesDuration,totalSamplesReceived:V.totalSamplesReceived,fecPacketsDiscarded:V.fecPacketsDiscarded||0,fecPacketsReceived:V.fecPacketsReceived||0,insertedSamplesForDeceleration:V.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:V.removedSamplesForAcceleration||0,silentConcealedSamples:V.silentConcealedSamples||0,playoutId:V.playoutId,...fe};_.score=eg({concealmentEvents:(_.concealmentEvents||0)-(((Z=this.audioConsumerToStatsMap.get(w))==null?void 0:Z.concealmentEvents)||0),packetsLost:(_.packetsLost||0)-(((re=this.audioConsumerToStatsMap.get(w))==null?void 0:re.packetsLost)||0),packetsReceived:(_.packetsReceived||0)-(((F=this.audioConsumerToStatsMap.get(w))==null?void 0:F.packetsReceived)||0),jitter:_.jitter||0}),y.set(w,{score:+(_.score*10).toFixed(),packetsLostPercentage:Dd({packetsLost:(_.packetsLost||0)-(((ee=this.audioConsumerToStatsMap.get(w))==null?void 0:ee.packetsLost)||0),packetsReceived:(_.packetsReceived||0)-(((we=this.audioConsumerToStatsMap.get(w))==null?void 0:we.packetsReceived)||0)}),jitter:_.jitter||0,isScreenShare:this.screenShareConsumers.has(w),bitrate:((_.bytesReceived||0)-(((vt=this.audioConsumerToStatsMap.get(w))==null?void 0:vt.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(w,_),d.inboundAudioRtp.set(A.id,_),d.consumerStreamMap.get(w).inboundAudioRtpId.push(A.id),this.processInboundConsumerAudioStats(w,ce,_)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}}}if(d.producerStreamMap.forEach((A,S)=>{var w,$,ce,fe,V,_,He,nd,ad,od,cd,dd,ld,ud,hd,pd,md,gd,fd,vd,Sd,Td,yd;if(A.outboundVideoRtpId.length>0){const Te=[];A.outboundVideoRtpId.forEach(jp=>{Te.push(d.outboundVideoRtp.get(jp))});const se=this.getWorkingSimulcastVideoStats(Te);se.score=Xm({frameWidth:se.frameWidth||0,framesPerSecond:se.framesPerSecond||0,jitter:((w=se.remoteData)==null?void 0:w.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsSent:(se.packetsSent||0)-((($=this.videoProducerToStatsMap.get(S))==null?void 0:$.packetsSent)||0),packetsLost:(((ce=se.remoteData)==null?void 0:ce.packetsLost)||0)-(((V=(fe=this.videoProducerToStatsMap.get(S))==null?void 0:fe.remoteData)==null?void 0:V.packetsLost)||0),framesEncoded:(se.framesEncoded||0)-(((_=this.videoProducerToStatsMap.get(S))==null?void 0:_.framesEncoded)||0)}),v.set(S,{score:+(se.score*10).toFixed(),frameWidth:se.frameWidth||0,frameHeight:se.frameHeight||0,framesPerSecond:se.framesPerSecond||0,jitter:((He=se.remoteData)==null?void 0:He.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsLostPercentage:Od({packetsSent:(se.packetsSent||0)-(((nd=this.videoProducerToStatsMap.get(S))==null?void 0:nd.packetsSent)||0),packetsLost:(((ad=se.remoteData)==null?void 0:ad.packetsLost)||0)-(((cd=(od=this.videoProducerToStatsMap.get(S))==null?void 0:od.remoteData)==null?void 0:cd.packetsLost)||0)}),bitrate:((se.bytesSent||0)-(((dd=this.videoProducerToStatsMap.get(S))==null?void 0:dd.bytesSent)||0))*8/7,cpuLimitations:se.qualityLimitationReason==="cpu",bandwidthLimitations:se.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(S,se)}else if(A.outboundAudioRtpId.length>0){const Te=d.outboundAudioRtp.get(A.outboundAudioRtpId[0]);Te.score=Qm({packetsSent:(Te.packetsSent||0)-(((ld=this.audioProducerToStatsMap.get(S))==null?void 0:ld.packetsSent)||0),packetsLost:(((ud=Te.remoteData)==null?void 0:ud.packetsLost)||0)-(((pd=(hd=this.audioProducerToStatsMap.get(S))==null?void 0:hd.remoteData)==null?void 0:pd.packetsLost)||0),jitter:((md=Te.remoteData)==null?void 0:md.jitter)||0}),v.set(S,{score:+(Te.score*10).toFixed(),bitrate:((Te.bytesSent||0)-(((gd=this.audioProducerToStatsMap.get(S))==null?void 0:gd.bytesSent)||0))*8/7,packetsLostPercentage:Od({packetsSent:(Te.packetsSent||0)-(((fd=this.audioProducerToStatsMap.get(S))==null?void 0:fd.packetsSent)||0),packetsLost:(((vd=Te.remoteData)==null?void 0:vd.packetsLost)||0)-(((Td=(Sd=this.audioProducerToStatsMap.get(S))==null?void 0:Sd.remoteData)==null?void 0:Td.packetsLost)||0)}),jitter:((yd=Te.remoteData)==null?void 0:yd.jitter)||0,isScreenShare:this.screenShareProducers.has(S)}),this.audioProducerToStatsMap.set(S,Te)}}),g.forEach(A=>{const S=u.find($=>$.id===A.localCandidateId?(A.localCandidateId=$.id,$):null),w=h.find($=>$.id===A.remoteCandidateId?(A.remoteCandidateId=$.id,$):null);S&&(A.localCandidateType=S.type,A.localCandidateAddress=Un(S.address),A.localCandidatePort=S.port,A.localCandidateProtocol=S.protocol,A.localCandidateUrl=S.url,A.localCandidateNetworkType=S.networkType,A.localCandidateRelatedAddress=Un(S.relatedAddress),A.localCandidateRelatedPort=S.relatedPort),w&&(A.remoteCandidateType=w.type,A.remoteCandidateAddress=Un(w.address),A.remoteCandidatePort=w.port,A.remoteCandidateProtocol=w.protocol,A.remoteCandidateUrl=w.url)}),d.candidatePair&&(d.transport?(d.transport.bytesReceived=d.candidatePair.bytesReceived,d.transport.bytesSent=d.candidatePair.bytesSent,d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.availableIncomingBitrate=d.candidatePair.availableIncomingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:d.candidatePair.availableIncomingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=g),d.transport&&!d.transport.roundTripTime){let A=0,S=0;d.remoteInboundRtp.forEach((w,$)=>{w.roundTripTime&&w.roundTripTime>A&&(A=w.roundTripTime,S=w.totalRoundTripTime)}),d.transport.roundTripTime=A,d.transport.totalRoundTripTime=S}if(y.size>0)try{this.observer.emit("consumer_score",y)}catch(A){}if(v.size>0)try{this.observer.emit("producer_score",v)}catch(A){}return d}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((i,n)=>{const o=this.producerMap.get(n),c=o.track.getSettings(),d=i.outboundVideoRtpId.map(u=>{const h=e.outboundVideoRtp.get(u);return h.frameHeight||(h.frameHeight=c.height,h.frameWidth=c.width,h.framesPerSecond=c.frameRate),h}),l={producerId:n,appData:o.appData,videoStats:d,audioStats:i.outboundAudioRtpId.map(u=>e.outboundAudioRtp.get(u))};r.push(l)})}catch(i){console.error("getProducersReport: ",i,e)}return r}getConsumerStatsFromParsedConsumerStats(e,r,i){let n;try{const{peerId:o,producerId:c,appData:d}=this.consumerPeerIdMap.get(i),l=r==null?void 0:r.inboundVideoRtpId.map(u=>{const g=this.consumerMap.get(i).track.getSettings(),v=e.inboundVideoRtp.get(u);return v.frameHeight||(v.frameHeight=g.height,v.frameWidth=g.width,v.framesPerSecond=g.frameRate),v});n={consumerId:i,peerId:o,producerId:c,appData:d,videoStats:l,audioStats:r==null?void 0:r.inboundAudioRtpId.map(u=>e.inboundAudioRtp.get(u))}}catch(o){console.error("getConsumerStatsFromParsedConsumerStats: ",o,e)}return n}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((i,n)=>{r.push(this.getConsumerStatsFromParsedConsumerStats(e,i,n))})}catch(i){console.error("getConsumerStatsFromReport: ",i,e)}return r}}class Dy extends ag{}function xd(s,t,e,r){if(s!=null&&s.logger&&s.logger.error("Callstats::handleError",{error:r}),typeof e=="function"&&r instanceof t)e.call(null,r,s);else throw r}function og(s,t,e){const r=s.value;return s.value=function(...i){try{const n=r.apply(this,i);return n&&n instanceof Promise?n.catch(o=>{xd(this,t,e,o)}):n}catch(n){xd(this,t,e,n)}return null},s}const Y=(s,t)=>(e,r,i)=>{const n=i.value;return i.value=function(...o){try{const c=n.apply(this,o);return c&&c instanceof Promise?c.catch(d=>{xd(this,s,t,d)}):c}catch(c){xd(this,s,t,c)}return null},i},Ny=(s,t)=>(e,r,i)=>{if(i)return og(i,s,t);for(const n of Reflect.ownKeys(e.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(e.prototype,n);o.value instanceof Function&&Object.defineProperty(e.prototype,n,og(o,s,t))}};var J=globalThis&&globalThis.__decorate||function(s,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(s,t,e,r);else for(var c=s.length-1;c>=0;c--)(o=s[c])&&(n=(i<3?o(n):i>3?o(t,e,n):o(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n};const K=console;let q=class extends Tt{constructor(e="https://api.testingv3.dyte.in",r="Blink",i=qm.PROD,n,o,c,d,l){super();p(this,"observer");p(this,"eventHandler");p(this,"measurements");p(this,"producingTransport");p(this,"consumingTransport");p(this,"producers",new Map);p(this,"consumers",new Map);p(this,"iceServers");p(this,"connectionInfoPromise");p(this,"pingStatsTimeout");p(this,"logger");p(this,"env");p(this,"apiHostnames");p(this,"peerId");p(this,"consumerSharedMediaStatesMap",new Map);p(this,"currentUserMediaStates",{});if(!l)throw Error("authToken is missing but required to initialize CallStats!");switch(this.env=i,this.apiHostnames=d,this.logger=o,this.peerId=c,this.eventHandler=new Ty({logger:o,peerId:c,apiHostnames:d,authToken:l}),this.logger.debug("callStats::engineName: ",{engineName:r}),r){case"Blink":this.measurements=new Oy;break;case"Gecko":this.measurements=new ag;break;case"WebKit":this.measurements=new Dy;break;default:throw Error(`Unknown engineName! ${r}`)}this.measurements.callStatsInstance=this,this.registerProducer=this.registerProducer.bind(this),this.registerConsumer=this.registerConsumer.bind(this),this.observer=new Tt,this.measurements.observer.on("consumer_score",u=>{o.debug(`callStats::consumer_score ${[...u.entries()]}`),this.eventHandler.emit("consumer_score",u)}),this.measurements.observer.on("producer_score",u=>{o.debug(`callStats::producer_score ${[...u.entries()]}`),this.eventHandler.emit("producer_score",u)})}registerIceServers(e){this.iceServers=e}registerConsumer(e){var r;this.consumerSharedMediaStatesMap.has(e.id)||this.consumerSharedMediaStatesMap.set(e.id,{}),this.consumers.set(e.id,e),this.measurements.registerConsumer(e),this.logger.debug("callStats::registerConsumer",{consumerId:e.id,consumerkind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)}),e.on("close",this.deRegisterConsumer.bind(this,e))}registerProducer(e){var r;this.producers.set(e.id,e),this.measurements.registerProducer(e),this.logger.debug("callStats::registerProducer",{producerId:e.id,producerKind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)}),e.on("close",this.deRegisterProducer.bind(this,e))}sendConsumerSharedMediaStateEvent(e,r){this.consumerSharedMediaStatesMap.has(e)||this.consumerSharedMediaStatesMap.set(e,{});const i=this.consumerSharedMediaStatesMap.get(e);this.consumerSharedMediaStatesMap.set(e,Object.assign(i,r))}registerProducingTransport(e){var i;this.producingTransport=e,e.on("close",this.disconnectProducingTransport.bind(this,e)),e.on("disconnect",this.disconnectProducingTransport.bind(this,e)),Array.from(((i=e._producers)==null?void 0:i.values())||[]).forEach(n=>{this.registerProducer(n)}),e.on("newproducer",this.registerProducer)}registerConsumingTransport(e){var i;this.consumingTransport=e,e.on("close",this.disconnectConsumingTransport.bind(this,e)),e.on("disconnect",this.disconnectConsumingTransport.bind(this,e)),Array.from(((i=e._consumers)==null?void 0:i.values())||[]).forEach(n=>{this.registerConsumer(n)}),e.on("newconsumer",this.registerConsumer)}deRegisterConsumer(e){this.consumers.delete(e.id)}deRegisterProducer(e){var r;this.producers.delete(e.id),this.logger.debug("callStats::deRegisterProducer",{producerId:e.id,producerKind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)})}disconnectConsumingTransport(){this.consumingTransport=void 0}disconnectProducingTransport(){this.producingTransport=void 0}callEvent(e){this.eventHandler.callEvent(e)}sendPreCallTestBeginEvent(e=!1,r){this.connectionInfoPromise=this.measurements.getNetworkInfo(this.iceServers,e),this.eventHandler.callEvent({event:L.PRECALL_TEST_BEGIN,timestamp:r}),this.connectionInfoPromise.then(i=>{this.eventHandler.callEvent({event:L.PRECALL_TEST_COMPLETE,metaData:{connectionInfo:i},timestamp:r})})}sendScreenShareToggleEvent(e,r=null,i){this.currentUserMediaStates.screen=e,this.eventHandler.callEvent({event:e?L.SCREENSHARE_STARTED:L.SCREENSHARE_STOPPED,metaData:{ssrc:r},timestamp:i})}sendScreenShareRequestedEvent(e){this.eventHandler.callEvent({event:L.SCREENSHARE_START_REQUESTED,timestamp:e})}sendActiveSpeakerEvent(e,r){this.eventHandler.callEvent({event:L.DOMINANT_SPEAKER,metaData:{peerId:e},timestamp:r})}devices(e,r,i){this.eventHandler.callEvent({event:e===ts.AUDIO&&L.AUDIO_DEVICES_UPDATES||e===ts.VIDEO&&L.VIDEO_DEVICES_UPDATES||e===ts.SPEAKER&&L.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:r},timestamp:i})}selectedDevice(e,r,i){this.eventHandler.callEvent({event:e===ts.AUDIO&&L.SELECTED_MICROHPONE_UPDATE||e===ts.VIDEO&&L.SELECTED_CAMERA_UPDATE||e===ts.SPEAKER&&L.SELECTED_SPEAKER_UPDATE,metaData:{device:r},timestamp:i})}mediaPermission(e,r,i){this.eventHandler.callEvent({event:L.MEDIA_PERMISSION,metaData:{deviceType:e,permission:r},timestamp:i})}mediaPlaybackFailed(e,r){this.eventHandler.callEvent({event:e===ts.AUDIO&&L.AUDIO_PLAY_FAILED||e===ts.VIDEO&&L.VIDEO_PLAY_FAILED,metaData:{deviceType:e},timestamp:r})}mediaTrackMuted(e,r){this.eventHandler.callEvent({event:e===ts.AUDIO&&L.AUDIO_TRACK_MUTED||e===ts.VIDEO&&L.VIDEO_TRACK_MUTED,metaData:{deviceType:e},timestamp:r})}tabChanged(e,r){this.eventHandler.callEvent({event:L.TAB_CHANGE,metaData:{isMeetingsTabActive:e},timestamp:r})}browserBackgrounded(e){this.eventHandler.callEvent({event:L.BROWSER_BACKGROUNDED,timestamp:e})}browserForegrounded(e){this.eventHandler.callEvent({event:L.BROWSER_FOREGROUNDED,timestamp:e})}legacySwitch(e,r){this.eventHandler.callEvent({event:L.LEGACY_SWITCH,metadata:{on:e},timestamp:r})}async getPreCallTestResults(){return this.connectionInfoPromise}sendCallJoinBeginEvent(e,r){e={...e,meetingEnv:this.env},e.deviceInfo={...e.deviceInfo,userAgent:navigator.userAgent,cpus:navigator.hardwareConcurrency,memory:navigator.deviceMemory},this.eventHandler.callEvent({event:L.CALL_JOIN_BEGIN,metaData:{peerMetaData:e},timestamp:r})}sendNetworkQualityTestBeginEvent(e,r){this.eventHandler.callEvent({event:L.NET_QUALITY_TEST_BEGIN,timestamp:r}),new Promise(async(n,o)=>{const c=[];try{for(const d of e)try{if(d.iceServers&&d.iceServers.length>0){const l=await this.measurements.getNetworkQuality(d.iceServers);c.push({...d,networkResults:l})}}catch(l){console.warn("Error handling ",l)}n({regionData:c})}catch(d){console.warn("Error in callstats, ",d),o(d)}}).then(n=>{this.eventHandler.callEvent({event:L.NET_QUALITY_TEST_END,timestamp:r,metaData:n})})}sendWebSocketConnectedEvent(e){this.eventHandler.callEvent({event:L.WEBSOCKET_CONNECTED,timestamp:e})}sendTransportConnectedEvent(e){this.eventHandler.callEvent({event:L.TRANSPORT_CONNECTED,timestamp:e})}sendAudioToggleEvent(e,r){this.currentUserMediaStates.audio=e;let i;e?i=L.AUDIO_ON:i=L.AUDIO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendVideoToggleEvent(e,r){this.currentUserMediaStates.video=e;let i;e?i=L.VIDEO_ON:i=L.VIDEO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendParticipantRoleToggleEvent(e,r){this.eventHandler.callEvent({event:L.PARTICIPANT_ROLE,timestamp:r,metaData:e})}startPingStats(e=7e3){this.sendPingStatsEvent(!1,new Date),this.pingStatsTimeout=setInterval(this.sendPingStatsEvent.bind(this),e)}stopPingStats(){clearInterval(this.pingStatsTimeout)}async sendPingStatsEvent(e=!0,r){var c,d;let i,n;if(this.producingTransport&&(i=await this.measurements.getProcessedStats(this.producingTransport,!1,!0),!i||!((c=i==null?void 0:i.producerReport)!=null&&c.length))){this.logger.debug("callStats::sendPingStatsEvent::staleProducingTransport",{disclaimer:"Stale producer? Regenerating Stream Maps!"});const l=await this.measurements.getProducersReport([...this.producers.values()]);i&&l?i.producerReport=l:(i=await this.measurements.getProcessedStats(this.producingTransport,!1,!0),(!i||!(i!=null&&i.producerReport))&&this.logger.debug("callStats::sendPingStatsEvent::noProducingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}if(this.consumingTransport){const l=new Set(this.measurements.inboundConsumerMap.values()),u=[...this.consumers.values()].filter(g=>!g.paused&&!l.has(g.id));if((await Promise.allSettled(u.map(g=>this.measurements.generateConsumerStreamMap(g)))).forEach((g,v)=>{g.status==="rejected"&&this.logger.error("callStats::sendPingStatsEvent::consumerGetStatsFailed",{consumerId:u[v].id,error:g.reason instanceof Error?g.reason.message:String(g.reason),stack:g.reason instanceof Error?g.reason.stack:void 0})}),n=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),!n||!((d=n.consumerReport)!=null&&d.length)){this.logger.debug("callStats::sendPingStatsEvent::staleConsumingTransport",{disclaimer:"Stale consumer? Regenerating Stream Maps!"});const g=await this.measurements.getConsumersReport([...this.consumers.values()]);n&&g?n.consumerReport=g:(n=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),(!n||!n.consumerReport)&&this.logger.debug("callStats::sendPingStatsEvent::noConsumingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}}const o={producingTransportStats:i?i==null?void 0:i.transportReport:void 0,consumingTransportStats:n?n==null?void 0:n.transportReport:void 0,producerStats:[].concat((i==null?void 0:i.producerReport)||[]).concat((n==null?void 0:n.producerReport)||[]),consumerStats:[].concat((n==null?void 0:n.consumerReport)||[]).concat((i==null?void 0:i.consumerReport)||[])};if(e&&o.producerStats.length===0&&o.consumerStats.length===0){await this.eventHandler.flush();return}this.eventHandler.callEvent({event:L.PING_STAT,metaData:o,timestamp:r})}sendIVSPlayerRebufferEvent(e){this.eventHandler.callEvent({event:L.IVS_PLAYER_REBUFFERING,timestamp:e})}sendIVSPlayerAudioBlockEvent(e){this.eventHandler.callEvent({event:L.IVS_PLAYER_AUDIO_BLOCKED,timestamp:e})}sendIVSPlayerPlaybackBlockedEvent(e){this.eventHandler.callEvent({event:L.IVS_PLAYER_PLAYBACK_BLOCKED,timestamp:e})}sendIVSPlayerNetworkUnavailableEvent(e){this.eventHandler.callEvent({event:L.IVS_PLAYER_NETWORK_UNAVAILABLE,timestamp:e})}sendIVSPlayerInitializedEvent(e){this.eventHandler.callEvent({event:L.IVS_PLAYER_INITIALIZED,timestamp:e})}sendIVSPlayerWorkerErrorEvent(e){this.eventHandler.callEvent({event:L.IVS_PLAYER_WORKER_ERROR,timestamp:e})}sendIVSPlayerErrorEvent(e,r){this.eventHandler.callEvent({event:L.IVS_PLAYER_ERROR,timestamp:r,metaData:e})}sendIVSPlayerRecoverableErrorEvent(e,r){this.eventHandler.callEvent({event:L.IVS_PLAYER_RECOVERABLE_ERROR,timestamp:r,metaData:e})}sendIVSPlayerAnalyticsEvent(e,r){this.eventHandler.callEvent({event:L.IVS_PLAYER_ANALYTICS_EVENT,timestamp:r,metaData:e})}sendIVSPlayerPlaybackRateChangedEvent(e,r){this.eventHandler.callEvent({event:L.IVS_PLAYER_PLAYBACK_RATE_CHANGED,timestamp:r,metaData:{updatedPlaybackRate:e}})}sendIVSPlayerQualityChanged(e,r){this.eventHandler.callEvent({event:L.IVS_PLAYER_QUALITY_CHANGED,timestamp:r,metaData:e})}sendPlayerLiveLatency(e,r){this.eventHandler.callEvent({event:L.LIVESTREAM_LATENCY,timestamp:r,metaData:{latency:e}})}sendDisconnectEvent(e){this.eventHandler.callEvent({event:L.DISCONNECT,timestamp:e})}sendReconnectEvent(e){this.eventHandler.callEvent({event:L.RECONNECT_ATTEMPT,timestamp:e})}expectedVideoResolution(e,r,i){this.eventHandler.callEvent({event:L.EXPECTED_VIDEO_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}expectedScreenshareResolution(e,r,i){this.eventHandler.callEvent({event:L.EXPECTED_SCREENSHARE_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}};J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"registerIceServers",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"registerConsumer",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"registerProducer",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendConsumerSharedMediaStateEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"registerProducingTransport",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"registerConsumingTransport",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"deRegisterConsumer",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"deRegisterProducer",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"disconnectConsumingTransport",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"disconnectProducingTransport",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendPreCallTestBeginEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendScreenShareToggleEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendScreenShareRequestedEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendActiveSpeakerEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"devices",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"selectedDevice",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"mediaPermission",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"mediaPlaybackFailed",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"mediaTrackMuted",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"tabChanged",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"browserBackgrounded",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"browserForegrounded",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"legacySwitch",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"getPreCallTestResults",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendCallJoinBeginEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendNetworkQualityTestBeginEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendWebSocketConnectedEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendTransportConnectedEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendAudioToggleEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendVideoToggleEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendParticipantRoleToggleEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"startPingStats",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"stopPingStats",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendPingStatsEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendIVSPlayerRebufferEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendIVSPlayerAudioBlockEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendIVSPlayerPlaybackBlockedEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendIVSPlayerNetworkUnavailableEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendIVSPlayerInitializedEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendIVSPlayerWorkerErrorEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendIVSPlayerErrorEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendIVSPlayerRecoverableErrorEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendIVSPlayerAnalyticsEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendIVSPlayerQualityChanged",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendPlayerLiveLatency",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendDisconnectEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendReconnectEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"expectedVideoResolution",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"expectedScreenshareResolution",null),q=J([Ny(TypeError,(s,t)=>K.error(t,s))],q);const Ly=q;class cg extends Tt{constructor(){super(...arguments);p(this,"stats");p(this,"peerId");p(this,"backend");p(this,"iceServers");p(this,"initialized",!1);p(this,"stalled",!1);p(this,"logger")}async initialize({peerId:e,engineName:r,env:i=qm.PROD,iceServers:n,apiBase:o="https://api.cluster.dyte.in",flags:c,logger:d=console,apiHostnames:l,skipConnectivityChecks:u=!1,authToken:h}){var g,v,y;try{if(this.peerId=e,this.logger=d,!h){this.logger.error("callStats::initialize",{event:"auth_token_missing",peerId:this.peerId}),this.stallCallStats();return}this.backend=new Ly(o,r,i,c,d,e,l,h),this.iceServers=n,(g=this.backend)==null||g.registerIceServers(this.iceServers),this.initialized=!0,this.startPreCallTest(u),(y=(v=this.backend)==null?void 0:v.eventHandler)==null||y.emit("initialized"),this.emit("initialized")}catch(k){this.logger.error("callStats::CallStatsIntegration",{peerId:this.peerId,error:k instanceof Error?k.message:String(k),stack:k instanceof Error?k.stack:void 0}),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)})}async candidateRegionalNetworkQualityTest(e){const r=new Date;this.onSafeInitialization(()=>{var i;try{(i=this.backend)==null||i.sendNetworkQualityTestBeginEvent(e,r)}catch(n){this.logger.error("callStats::sendNetworkQualityTestBeginEvent",{error:{reason:n.reason}})}})}async roomJoined(e){const r=new Date;this.onSafeInitialization(()=>{var i,n;(i=this.backend)==null||i.sendCallJoinBeginEvent(e,r),this.backend,(n=this.backend)==null||n.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,i;(r=this.backend)==null||r.stopPingStats(),(i=this.backend)==null||i.sendDisconnectEvent(e)})}screenShareStart(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendScreenShareToggleEvent(!0,e,r)})}consumerSharedMediaState(e,r){this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendConsumerSharedMediaStateEvent(e,r)})}screenShareStop(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.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 i;(i=this.backend)==null||i.sendActiveSpeakerEvent(e,r)})}devices(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.devices(e,r,i)})}selectedDevice(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.selectedDevice(e,r,i)})}mediaPermission(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.mediaPermission(e,r,i)})}mediaPlaybackFailed(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.mediaPlaybackFailed(e,r)})}mediaTrackMuted(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.mediaTrackMuted(e,r)})}tabChanged(e=!1){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.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 i;(i=this.backend)==null||i.legacySwitch(e,r)})}async startPreCallTest(e=!1){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendPreCallTestBeginEvent(e,r)})}onPreCallTestResults(e){return this.onSafeInitialization(()=>{var r,i;(i=(r=this.backend)==null?void 0:r.getPreCallTestResults())==null||i.then(n=>{n&&e({connectionInfo:n})},n=>{this.logger.error("callStats::onPreCallTestResults",{peerId:this.peerId,error:n instanceof Error?n.message:String(n),stack:n instanceof Error?n.stack:void 0})})}),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(!1);else if(!this.stalled){const r=()=>{e(!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 i=new Date;this.onSafeInitialization(()=>{var n,o,c,d,l,u,h,g,v,y,k;switch(e){case"PlayerRebuffering":(n=this.backend)==null||n.sendIVSPlayerRebufferEvent(i);break;case"PlayerAudioBlocked":(o=this.backend)==null||o.sendIVSPlayerAudioBlockEvent(i);break;case"PlayerPlaybackBlocked":(c=this.backend)==null||c.sendIVSPlayerPlaybackBlockedEvent(i);break;case"PlayerNetworkUnavailable":(d=this.backend)==null||d.sendIVSPlayerNetworkUnavailableEvent(i);break;case"PlayerInitialized":(l=this.backend)==null||l.sendIVSPlayerInitializedEvent(i);break;case"PlayerWorkerError":(u=this.backend)==null||u.sendIVSPlayerWorkerErrorEvent(i);break;case"PlayerError":(h=this.backend)==null||h.sendIVSPlayerErrorEvent(r,i);break;case"PlayerRecoverableError":(g=this.backend)==null||g.sendIVSPlayerRecoverableErrorEvent(r,i);break;case"PlayerAnalyticsEvent":(v=this.backend)==null||v.sendIVSPlayerAnalyticsEvent(r,i);break;case"PlayerPlaybackRateChanged":(y=this.backend)==null||y.sendIVSPlayerPlaybackRateChangedEvent(r,i);break;case"PlayerQualityChanged":(k=this.backend)==null||k.sendIVSPlayerQualityChanged(r,i);break}})}livestreamLatency(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendPlayerLiveLatency(e,r)})}expectedVideoResolution(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.expectedVideoResolution(e,r,i)})}expectedScreenshareResolution(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.expectedScreenshareResolution(e,r,i)})}}new cg().setMaxListeners(30);class Vy{constructor(){m(this,Ho,void 0)}get telemetry(){var t;return(t=a(this,Ho))==null?void 0:t.getValue("telemetry")}init(t){f(this,Ho,t)}info(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("info",t,e,r)}error(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("error",t,e,r)}debug(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("debug",t,e,r)}log(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("log",t,e,r)}warn(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("warn",t,e,r)}}Ho=new WeakMap;function dg(s,t,e,r){try{t==null||t.error(`EventEmitter listener error on event ${e.toString()}`,{error:r,eventListener:{eventName:e.toString(),listenerCount:s.listenerCount(e)}});return}catch(i){return}}function no(s,t,e,r){const i=s.rawListeners(t);return i.forEach(n=>{try{const o=Reflect.apply(n,s,e);o&&typeof o.then=="function"&&Promise.resolve(o).catch(c=>dg(s,r,t,c))}catch(o){dg(s,r,t,o)}}),i.length>0}class Bn extends Tt.EventEmitter{constructor(e){super();p(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return no(this,"*",[e,...r],this.logger),no(this,e,r,this.logger)}on(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.on(e,r)}addListener(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.addListener(e,r)}off(e,r){return super.off(e,r)}once(e,r){return super.once(e,r)}prependListener(e,r){return super.prependListener(e,r)}prependOnceListener(e,r){return super.prependOnceListener(e,r)}removeListener(e,r){return super.removeListener(e,r)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}class Bt extends Tt.EventEmitter{constructor(e){super();p(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return no(this,"*",[e,...r],this.logger),no(this,e,r,this.logger)}on(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.on(e,r)}addListener(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.addListener(e,r)}off(e,r){return super.off(e,r)}once(e,r){return super.once(e,r)}prependListener(e,r){return super.prependListener(e,r)}prependOnceListener(e,r){return super.prependOnceListener(e,r)}removeListener(e,r){return super.removeListener(e,r)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}class xy extends Tt.EventEmitter{constructor(e){super();m(this,fr,void 0);m(this,vr,void 0);p(this,"asyncPromiseTimeout");p(this,"logger");this.logger=e,f(this,fr,new Map),f(this,vr,new Map),this.asyncPromiseTimeout=8e3}emit(e,...r){return no(this,e,r,this.logger)}async emitAsync(e,...r){a(this,fr).set(e,[]);const i=a(this,vr).get(e).map(()=>new Promise(n=>{a(this,fr).get(e).push(n)}));this.emit(e,...r),await Promise.race([Promise.all(i),new Promise((n,o)=>setTimeout(()=>o(new Error(`emitAsync failed to resolve for event ${e}.`)),this.asyncPromiseTimeout))]),a(this,fr).delete(e)}onAsync(e,r){const i=a(this,fr),n=async(...o)=>{var d;try{await r(...o)}catch(l){this.logger.error("[onAsync]",{error:l})}const c=(d=i.get(e))==null?void 0:d.shift();c==null||c()};return a(this,vr).get(e)||a(this,vr).set(e,[]),a(this,vr).get(e).push(n),super.on(e,n)}reset(){f(this,fr,new Map),f(this,vr,new Map),super.removeAllListeners()}}fr=new WeakMap,vr=new WeakMap;var $y=typeof global=="object"&&global&&global.Object===Object&&global;const lg=$y;var Uy=typeof self=="object"&&self&&self.Object===Object&&self,By=lg||Uy||Function("return this")();const fs=By;var Fy=fs.Symbol;const Ms=Fy;var ug=Object.prototype,Hy=ug.hasOwnProperty,qy=ug.toString,ao=Ms?Ms.toStringTag:void 0;function jy(s){var t=Hy.call(s,ao),e=s[ao];try{s[ao]=void 0;var r=!0}catch(n){}var i=qy.call(s);return r&&(t?s[ao]=e:delete s[ao]),i}var Gy=Object.prototype,Wy=Gy.toString;function Jy(s){return Wy.call(s)}var Ky="[object Null]",zy="[object Undefined]",hg=Ms?Ms.toStringTag:void 0;function Ri(s){return s==null?s===void 0?zy:Ky:hg&&hg in Object(s)?jy(s):Jy(s)}function Os(s){return s!=null&&typeof s=="object"}var Yy="[object Symbol]";function $d(s){return typeof s=="symbol"||Os(s)&&Ri(s)==Yy}function Qy(s,t){for(var e=-1,r=s==null?0:s.length,i=Array(r);++e<r;)i[e]=t(s[e],e,s);return i}var Xy=Array.isArray;const Ft=Xy;var Zy=1/0,pg=Ms?Ms.prototype:void 0,mg=pg?pg.toString:void 0;function gg(s){if(typeof s=="string")return s;if(Ft(s))return Qy(s,gg)+"";if($d(s))return mg?mg.call(s):"";var t=s+"";return t=="0"&&1/s==-Zy?"-0":t}var eE=/\s/;function tE(s){for(var t=s.length;t--&&eE.test(s.charAt(t)););return t}var sE=/^\s+/;function rE(s){return s&&s.slice(0,tE(s)+1).replace(sE,"")}function ss(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var fg=0/0,iE=/^[-+]0x[0-9a-f]+$/i,nE=/^0b[01]+$/i,aE=/^0o[0-7]+$/i,oE=parseInt;function vg(s){if(typeof s=="number")return s;if($d(s))return fg;if(ss(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=ss(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=rE(s);var e=nE.test(s);return e||aE.test(s)?oE(s.slice(2),e?2:8):iE.test(s)?fg:+s}function ch(s){return s}var cE="[object AsyncFunction]",dE="[object Function]",lE="[object GeneratorFunction]",uE="[object Proxy]";function dh(s){if(!ss(s))return!1;var t=Ri(s);return t==dE||t==lE||t==cE||t==uE}var hE=fs["__core-js_shared__"];const lh=hE;var Sg=function(){var s=/[^.]+$/.exec(lh&&lh.keys&&lh.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function pE(s){return!!Sg&&Sg in s}var mE=Function.prototype,gE=mE.toString;function Ii(s){if(s!=null){try{return gE.call(s)}catch(t){}try{return s+""}catch(t){}}return""}var fE=/[\\^$.*+?()[\]{}|]/g,vE=/^\[object .+?Constructor\]$/,SE=Function.prototype,TE=Object.prototype,yE=SE.toString,EE=TE.hasOwnProperty,bE=RegExp("^"+yE.call(EE).replace(fE,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function wE(s){if(!ss(s)||pE(s))return!1;var t=dh(s)?bE:vE;return t.test(Ii(s))}function PE(s,t){return s==null?void 0:s[t]}function Ai(s,t){var e=PE(s,t);return wE(e)?e:void 0}var kE=Ai(fs,"WeakMap");const uh=kE;var Tg=Object.create,_E=function(){function s(){}return function(t){if(!ss(t))return{};if(Tg)return Tg(t);s.prototype=t;var e=new s;return s.prototype=void 0,e}}();const CE=_E;function RE(s,t,e){switch(e.length){case 0:return s.call(t);case 1:return s.call(t,e[0]);case 2:return s.call(t,e[0],e[1]);case 3:return s.call(t,e[0],e[1],e[2])}return s.apply(t,e)}function IE(){}function yg(s,t){var e=-1,r=s.length;for(t||(t=Array(r));++e<r;)t[e]=s[e];return t}var AE=800,ME=16,OE=Date.now;function DE(s){var t=0,e=0;return function(){var r=OE(),i=ME-(r-e);if(e=r,i>0){if(++t>=AE)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}function NE(s){return function(){return s}}var LE=function(){try{var s=Ai(Object,"defineProperty");return s({},"",{}),s}catch(t){}}();const Ud=LE;var VE=Ud?function(s,t){return Ud(s,"toString",{configurable:!0,enumerable:!1,value:NE(t),writable:!0})}:ch,xE=DE(VE);const $E=xE;function UE(s,t){for(var e=-1,r=s==null?0:s.length;++e<r&&t(s[e],e,s)!==!1;);return s}function BE(s,t,e,r){for(var i=s.length,n=e+(r?1:-1);r?n--:++n<i;)if(t(s[n],n,s))return n;return-1}function FE(s){return s!==s}function HE(s,t,e){for(var r=e-1,i=s.length;++r<i;)if(s[r]===t)return r;return-1}function qE(s,t,e){return t===t?HE(s,t,e):BE(s,FE,e)}function jE(s,t){var e=s==null?0:s.length;return!!e&&qE(s,t,0)>-1}var GE=9007199254740991,WE=/^(?:0|[1-9]\d*)$/;function hh(s,t){var e=typeof s;return t=t==null?GE:t,!!t&&(e=="number"||e!="symbol"&&WE.test(s))&&s>-1&&s%1==0&&s<t}function ph(s,t,e){t=="__proto__"&&Ud?Ud(s,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):s[t]=e}function oo(s,t){return s===t||s!==s&&t!==t}var JE=Object.prototype,KE=JE.hasOwnProperty;function Eg(s,t,e){var r=s[t];(!(KE.call(s,t)&&oo(r,e))||e===void 0&&!(t in s))&&ph(s,t,e)}function co(s,t,e,r){var i=!e;e||(e={});for(var n=-1,o=t.length;++n<o;){var c=t[n],d=r?r(e[c],s[c],c,e,s):void 0;d===void 0&&(d=s[c]),i?ph(e,c,d):Eg(e,c,d)}return e}var bg=Math.max;function zE(s,t,e){return t=bg(t===void 0?s.length-1:t,0),function(){for(var r=arguments,i=-1,n=bg(r.length-t,0),o=Array(n);++i<n;)o[i]=r[t+i];i=-1;for(var c=Array(t+1);++i<t;)c[i]=r[i];return c[t]=e(o),RE(s,this,c)}}function YE(s,t){return $E(zE(s,t,ch),s+"")}var QE=9007199254740991;function mh(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=QE}function lo(s){return s!=null&&mh(s.length)&&!dh(s)}function XE(s,t,e){if(!ss(e))return!1;var r=typeof t;return(r=="number"?lo(e)&&hh(t,e.length):r=="string"&&t in e)?oo(e[t],s):!1}function ZE(s){return YE(function(t,e){var r=-1,i=e.length,n=i>1?e[i-1]:void 0,o=i>2?e[2]:void 0;for(n=s.length>3&&typeof n=="function"?(i--,n):void 0,o&&XE(e[0],e[1],o)&&(n=i<3?void 0:n,i=1),t=Object(t);++r<i;){var c=e[r];c&&s(t,c,r,n)}return t})}var eb=Object.prototype;function Bd(s){var t=s&&s.constructor,e=typeof t=="function"&&t.prototype||eb;return s===e}function tb(s,t){for(var e=-1,r=Array(s);++e<s;)r[e]=t(e);return r}var sb="[object Arguments]";function wg(s){return Os(s)&&Ri(s)==sb}var Pg=Object.prototype,rb=Pg.hasOwnProperty,ib=Pg.propertyIsEnumerable,nb=wg(function(){return arguments}())?wg:function(s){return Os(s)&&rb.call(s,"callee")&&!ib.call(s,"callee")};const uo=nb;function ab(){return!1}var kg=typeof exports=="object"&&exports&&!exports.nodeType&&exports,_g=kg&&typeof module=="object"&&module&&!module.nodeType&&module,ob=_g&&_g.exports===kg,Cg=ob?fs.Buffer:void 0,cb=Cg?Cg.isBuffer:void 0,db=cb||ab;const Fn=db;var lb="[object Arguments]",ub="[object Array]",hb="[object Boolean]",pb="[object Date]",mb="[object Error]",gb="[object Function]",fb="[object Map]",vb="[object Number]",Sb="[object Object]",Tb="[object RegExp]",yb="[object Set]",Eb="[object String]",bb="[object WeakMap]",wb="[object ArrayBuffer]",Pb="[object DataView]",kb="[object Float32Array]",_b="[object Float64Array]",Cb="[object Int8Array]",Rb="[object Int16Array]",Ib="[object Int32Array]",Ab="[object Uint8Array]",Mb="[object Uint8ClampedArray]",Ob="[object Uint16Array]",Db="[object Uint32Array]",ke={};ke[kb]=ke[_b]=ke[Cb]=ke[Rb]=ke[Ib]=ke[Ab]=ke[Mb]=ke[Ob]=ke[Db]=!0,ke[lb]=ke[ub]=ke[wb]=ke[hb]=ke[Pb]=ke[pb]=ke[mb]=ke[gb]=ke[fb]=ke[vb]=ke[Sb]=ke[Tb]=ke[yb]=ke[Eb]=ke[bb]=!1;function Nb(s){return Os(s)&&mh(s.length)&&!!ke[Ri(s)]}function gh(s){return function(t){return s(t)}}var Rg=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ho=Rg&&typeof module=="object"&&module&&!module.nodeType&&module,Lb=ho&&ho.exports===Rg,fh=Lb&&lg.process,Vb=function(){try{var s=ho&&ho.require&&ho.require("util").types;return s||fh&&fh.binding&&fh.binding("util")}catch(t){}}();const Hn=Vb;var Ig=Hn&&Hn.isTypedArray,xb=Ig?gh(Ig):Nb;const Fd=xb;var $b=Object.prototype,Ub=$b.hasOwnProperty;function Ag(s,t){var e=Ft(s),r=!e&&uo(s),i=!e&&!r&&Fn(s),n=!e&&!r&&!i&&Fd(s),o=e||r||i||n,c=o?tb(s.length,String):[],d=c.length;for(var l in s)(t||Ub.call(s,l))&&!(o&&(l=="length"||i&&(l=="offset"||l=="parent")||n&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||hh(l,d)))&&c.push(l);return c}function Mg(s,t){return function(e){return s(t(e))}}var Bb=Mg(Object.keys,Object);const Fb=Bb;var Hb=Object.prototype,qb=Hb.hasOwnProperty;function Og(s){if(!Bd(s))return Fb(s);var t=[];for(var e in Object(s))qb.call(s,e)&&e!="constructor"&&t.push(e);return t}function Hd(s){return lo(s)?Ag(s):Og(s)}function jb(s){var t=[];if(s!=null)for(var e in Object(s))t.push(e);return t}var Gb=Object.prototype,Wb=Gb.hasOwnProperty;function Jb(s){if(!ss(s))return jb(s);var t=Bd(s),e=[];for(var r in s)r=="constructor"&&(t||!Wb.call(s,r))||e.push(r);return e}function po(s){return lo(s)?Ag(s,!0):Jb(s)}var Kb=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,zb=/^\w*$/;function vh(s,t){if(Ft(s))return!1;var e=typeof s;return e=="number"||e=="symbol"||e=="boolean"||s==null||$d(s)?!0:zb.test(s)||!Kb.test(s)||t!=null&&s in Object(t)}var Yb=Ai(Object,"create");const mo=Yb;function Qb(){this.__data__=mo?mo(null):{},this.size=0}function Xb(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var Zb="__lodash_hash_undefined__",ew=Object.prototype,tw=ew.hasOwnProperty;function sw(s){var t=this.__data__;if(mo){var e=t[s];return e===Zb?void 0:e}return tw.call(t,s)?t[s]:void 0}var rw=Object.prototype,iw=rw.hasOwnProperty;function nw(s){var t=this.__data__;return mo?t[s]!==void 0:iw.call(t,s)}var aw="__lodash_hash_undefined__";function ow(s,t){var e=this.__data__;return this.size+=this.has(s)?0:1,e[s]=mo&&t===void 0?aw:t,this}function Mi(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}Mi.prototype.clear=Qb,Mi.prototype.delete=Xb,Mi.prototype.get=sw,Mi.prototype.has=nw,Mi.prototype.set=ow;function cw(){this.__data__=[],this.size=0}function qd(s,t){for(var e=s.length;e--;)if(oo(s[e][0],t))return e;return-1}var dw=Array.prototype,lw=dw.splice;function uw(s){var t=this.__data__,e=qd(t,s);if(e<0)return!1;var r=t.length-1;return e==r?t.pop():lw.call(t,e,1),--this.size,!0}function hw(s){var t=this.__data__,e=qd(t,s);return e<0?void 0:t[e][1]}function pw(s){return qd(this.__data__,s)>-1}function mw(s,t){var e=this.__data__,r=qd(e,s);return r<0?(++this.size,e.push([s,t])):e[r][1]=t,this}function sr(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}sr.prototype.clear=cw,sr.prototype.delete=uw,sr.prototype.get=hw,sr.prototype.has=pw,sr.prototype.set=mw;var gw=Ai(fs,"Map");const go=gw;function fw(){this.size=0,this.__data__={hash:new Mi,map:new(go||sr),string:new Mi}}function vw(s){var t=typeof s;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?s!=="__proto__":s===null}function jd(s,t){var e=s.__data__;return vw(t)?e[typeof t=="string"?"string":"hash"]:e.map}function Sw(s){var t=jd(this,s).delete(s);return this.size-=t?1:0,t}function Tw(s){return jd(this,s).get(s)}function yw(s){return jd(this,s).has(s)}function Ew(s,t){var e=jd(this,s),r=e.size;return e.set(s,t),this.size+=e.size==r?0:1,this}function rr(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}rr.prototype.clear=fw,rr.prototype.delete=Sw,rr.prototype.get=Tw,rr.prototype.has=yw,rr.prototype.set=Ew;var bw="Expected a function";function Sh(s,t){if(typeof s!="function"||t!=null&&typeof t!="function")throw new TypeError(bw);var e=function(){var r=arguments,i=t?t.apply(this,r):r[0],n=e.cache;if(n.has(i))return n.get(i);var o=s.apply(this,r);return e.cache=n.set(i,o)||n,o};return e.cache=new(Sh.Cache||rr),e}Sh.Cache=rr;var ww=500;function Pw(s){var t=Sh(s,function(r){return e.size===ww&&e.clear(),r}),e=t.cache;return t}var kw=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,_w=/\\(\\)?/g,Cw=Pw(function(s){var t=[];return s.charCodeAt(0)===46&&t.push(""),s.replace(kw,function(e,r,i,n){t.push(i?n.replace(_w,"$1"):r||e)}),t});const Rw=Cw;function Iw(s){return s==null?"":gg(s)}function Dg(s,t){return Ft(s)?s:vh(s,t)?[s]:Rw(Iw(s))}var Aw=1/0;function Gd(s){if(typeof s=="string"||$d(s))return s;var t=s+"";return t=="0"&&1/s==-Aw?"-0":t}function Ng(s,t){t=Dg(t,s);for(var e=0,r=t.length;s!=null&&e<r;)s=s[Gd(t[e++])];return e&&e==r?s:void 0}function Mw(s,t,e){var r=s==null?void 0:Ng(s,t);return r===void 0?e:r}function Lg(s,t){for(var e=-1,r=t.length,i=s.length;++e<r;)s[i+e]=t[e];return s}var Ow=Mg(Object.getPrototypeOf,Object);const Th=Ow;var Dw="[object Object]",Nw=Function.prototype,Lw=Object.prototype,Vg=Nw.toString,Vw=Lw.hasOwnProperty,xw=Vg.call(Object);function $w(s){if(!Os(s)||Ri(s)!=Dw)return!1;var t=Th(s);if(t===null)return!0;var e=Vw.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&Vg.call(e)==xw}function Uw(){this.__data__=new sr,this.size=0}function Bw(s){var t=this.__data__,e=t.delete(s);return this.size=t.size,e}function Fw(s){return this.__data__.get(s)}function Hw(s){return this.__data__.has(s)}var qw=200;function jw(s,t){var e=this.__data__;if(e instanceof sr){var r=e.__data__;if(!go||r.length<qw-1)return r.push([s,t]),this.size=++e.size,this;e=this.__data__=new rr(r)}return e.set(s,t),this.size=e.size,this}function vs(s){var t=this.__data__=new sr(s);this.size=t.size}vs.prototype.clear=Uw,vs.prototype.delete=Bw,vs.prototype.get=Fw,vs.prototype.has=Hw,vs.prototype.set=jw;function Gw(s,t){return s&&co(t,Hd(t),s)}function Ww(s,t){return s&&co(t,po(t),s)}var xg=typeof exports=="object"&&exports&&!exports.nodeType&&exports,$g=xg&&typeof module=="object"&&module&&!module.nodeType&&module,Jw=$g&&$g.exports===xg,Ug=Jw?fs.Buffer:void 0,Bg=Ug?Ug.allocUnsafe:void 0;function Fg(s,t){if(t)return s.slice();var e=s.length,r=Bg?Bg(e):new s.constructor(e);return s.copy(r),r}function Kw(s,t){for(var e=-1,r=s==null?0:s.length,i=0,n=[];++e<r;){var o=s[e];t(o,e,s)&&(n[i++]=o)}return n}function Hg(){return[]}var zw=Object.prototype,Yw=zw.propertyIsEnumerable,qg=Object.getOwnPropertySymbols,Qw=qg?function(s){return s==null?[]:(s=Object(s),Kw(qg(s),function(t){return Yw.call(s,t)}))}:Hg;const yh=Qw;function Xw(s,t){return co(s,yh(s),t)}var Zw=Object.getOwnPropertySymbols,eP=Zw?function(s){for(var t=[];s;)Lg(t,yh(s)),s=Th(s);return t}:Hg;const jg=eP;function tP(s,t){return co(s,jg(s),t)}function Gg(s,t,e){var r=t(s);return Ft(s)?r:Lg(r,e(s))}function Eh(s){return Gg(s,Hd,yh)}function sP(s){return Gg(s,po,jg)}var rP=Ai(fs,"DataView");const bh=rP;var iP=Ai(fs,"Promise");const wh=iP;var nP=Ai(fs,"Set");const qn=nP;var Wg="[object Map]",aP="[object Object]",Jg="[object Promise]",Kg="[object Set]",zg="[object WeakMap]",Yg="[object DataView]",oP=Ii(bh),cP=Ii(go),dP=Ii(wh),lP=Ii(qn),uP=Ii(uh),Oi=Ri;(bh&&Oi(new bh(new ArrayBuffer(1)))!=Yg||go&&Oi(new go)!=Wg||wh&&Oi(wh.resolve())!=Jg||qn&&Oi(new qn)!=Kg||uh&&Oi(new uh)!=zg)&&(Oi=function(s){var t=Ri(s),e=t==aP?s.constructor:void 0,r=e?Ii(e):"";if(r)switch(r){case oP:return Yg;case cP:return Wg;case dP:return Jg;case lP:return Kg;case uP:return zg}return t});const jn=Oi;var hP=Object.prototype,pP=hP.hasOwnProperty;function mP(s){var t=s.length,e=new s.constructor(t);return t&&typeof s[0]=="string"&&pP.call(s,"index")&&(e.index=s.index,e.input=s.input),e}var gP=fs.Uint8Array;const Wd=gP;function Ph(s){var t=new s.constructor(s.byteLength);return new Wd(t).set(new Wd(s)),t}function fP(s,t){var e=t?Ph(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.byteLength)}var vP=/\w*$/;function SP(s){var t=new s.constructor(s.source,vP.exec(s));return t.lastIndex=s.lastIndex,t}var Qg=Ms?Ms.prototype:void 0,Xg=Qg?Qg.valueOf:void 0;function TP(s){return Xg?Object(Xg.call(s)):{}}function Zg(s,t){var e=t?Ph(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.length)}var yP="[object Boolean]",EP="[object Date]",bP="[object Map]",wP="[object Number]",PP="[object RegExp]",kP="[object Set]",_P="[object String]",CP="[object Symbol]",RP="[object ArrayBuffer]",IP="[object DataView]",AP="[object Float32Array]",MP="[object Float64Array]",OP="[object Int8Array]",DP="[object Int16Array]",NP="[object Int32Array]",LP="[object Uint8Array]",VP="[object Uint8ClampedArray]",xP="[object Uint16Array]",$P="[object Uint32Array]";function UP(s,t,e){var r=s.constructor;switch(t){case RP:return Ph(s);case yP:case EP:return new r(+s);case IP:return fP(s,e);case AP:case MP:case OP:case DP:case NP:case LP:case VP:case xP:case $P:return Zg(s,e);case bP:return new r;case wP:case _P:return new r(s);case PP:return SP(s);case kP:return new r;case CP:return TP(s)}}function ef(s){return typeof s.constructor=="function"&&!Bd(s)?CE(Th(s)):{}}var BP="[object Map]";function FP(s){return Os(s)&&jn(s)==BP}var tf=Hn&&Hn.isMap,HP=tf?gh(tf):FP;const qP=HP;var jP="[object Set]";function GP(s){return Os(s)&&jn(s)==jP}var sf=Hn&&Hn.isSet,WP=sf?gh(sf):GP;const JP=WP;var KP=1,zP=2,YP=4,rf="[object Arguments]",QP="[object Array]",XP="[object Boolean]",ZP="[object Date]",ek="[object Error]",nf="[object Function]",tk="[object GeneratorFunction]",sk="[object Map]",rk="[object Number]",af="[object Object]",ik="[object RegExp]",nk="[object Set]",ak="[object String]",ok="[object Symbol]",ck="[object WeakMap]",dk="[object ArrayBuffer]",lk="[object DataView]",uk="[object Float32Array]",hk="[object Float64Array]",pk="[object Int8Array]",mk="[object Int16Array]",gk="[object Int32Array]",fk="[object Uint8Array]",vk="[object Uint8ClampedArray]",Sk="[object Uint16Array]",Tk="[object Uint32Array]",ye={};ye[rf]=ye[QP]=ye[dk]=ye[lk]=ye[XP]=ye[ZP]=ye[uk]=ye[hk]=ye[pk]=ye[mk]=ye[gk]=ye[sk]=ye[rk]=ye[af]=ye[ik]=ye[nk]=ye[ak]=ye[ok]=ye[fk]=ye[vk]=ye[Sk]=ye[Tk]=!0,ye[ek]=ye[nf]=ye[ck]=!1;function fo(s,t,e,r,i,n){var o,c=t&KP,d=t&zP,l=t&YP;if(e&&(o=i?e(s,r,i,n):e(s)),o!==void 0)return o;if(!ss(s))return s;var u=Ft(s);if(u){if(o=mP(s),!c)return yg(s,o)}else{var h=jn(s),g=h==nf||h==tk;if(Fn(s))return Fg(s,c);if(h==af||h==rf||g&&!i){if(o=d||g?{}:ef(s),!c)return d?tP(s,Ww(o,s)):Xw(s,Gw(o,s))}else{if(!ye[h])return i?s:{};o=UP(s,h,c)}}n||(n=new vs);var v=n.get(s);if(v)return v;n.set(s,o),JP(s)?s.forEach(function(I){o.add(fo(I,t,e,I,s,n))}):qP(s)&&s.forEach(function(I,D){o.set(D,fo(I,t,e,D,s,n))});var y=l?d?sP:Eh:d?po:Hd,k=u?void 0:y(s);return UE(k||s,function(I,D){k&&(D=I,I=s[D]),Eg(o,D,fo(I,t,e,D,s,n))}),o}var yk=4;function Ek(s){return fo(s,yk)}var bk=1,wk=4;function kh(s){return fo(s,bk|wk)}var Pk="__lodash_hash_undefined__";function kk(s){return this.__data__.set(s,Pk),this}function _k(s){return this.__data__.has(s)}function vo(s){var t=-1,e=s==null?0:s.length;for(this.__data__=new rr;++t<e;)this.add(s[t])}vo.prototype.add=vo.prototype.push=kk,vo.prototype.has=_k;function Ck(s,t){for(var e=-1,r=s==null?0:s.length;++e<r;)if(t(s[e],e,s))return!0;return!1}function of(s,t){return s.has(t)}var Rk=1,Ik=2;function cf(s,t,e,r,i,n){var o=e&Rk,c=s.length,d=t.length;if(c!=d&&!(o&&d>c))return!1;var l=n.get(s),u=n.get(t);if(l&&u)return l==t&&u==s;var h=-1,g=!0,v=e&Ik?new vo:void 0;for(n.set(s,t),n.set(t,s);++h<c;){var y=s[h],k=t[h];if(r)var I=o?r(k,y,h,t,s,n):r(y,k,h,s,t,n);if(I!==void 0){if(I)continue;g=!1;break}if(v){if(!Ck(t,function(D,N){if(!of(v,N)&&(y===D||i(y,D,e,r,n)))return v.push(N)})){g=!1;break}}else if(!(y===k||i(y,k,e,r,n))){g=!1;break}}return n.delete(s),n.delete(t),g}function Ak(s){var t=-1,e=Array(s.size);return s.forEach(function(r,i){e[++t]=[i,r]}),e}function _h(s){var t=-1,e=Array(s.size);return s.forEach(function(r){e[++t]=r}),e}var Mk=1,Ok=2,Dk="[object Boolean]",Nk="[object Date]",Lk="[object Error]",Vk="[object Map]",xk="[object Number]",$k="[object RegExp]",Uk="[object Set]",Bk="[object String]",Fk="[object Symbol]",Hk="[object ArrayBuffer]",qk="[object DataView]",df=Ms?Ms.prototype:void 0,Ch=df?df.valueOf:void 0;function jk(s,t,e,r,i,n,o){switch(e){case qk:if(s.byteLength!=t.byteLength||s.byteOffset!=t.byteOffset)return!1;s=s.buffer,t=t.buffer;case Hk:return!(s.byteLength!=t.byteLength||!n(new Wd(s),new Wd(t)));case Dk:case Nk:case xk:return oo(+s,+t);case Lk:return s.name==t.name&&s.message==t.message;case $k:case Bk:return s==t+"";case Vk:var c=Ak;case Uk:var d=r&Mk;if(c||(c=_h),s.size!=t.size&&!d)return!1;var l=o.get(s);if(l)return l==t;r|=Ok,o.set(s,t);var u=cf(c(s),c(t),r,i,n,o);return o.delete(s),u;case Fk:if(Ch)return Ch.call(s)==Ch.call(t)}return!1}var Gk=1,Wk=Object.prototype,Jk=Wk.hasOwnProperty;function Kk(s,t,e,r,i,n){var o=e&Gk,c=Eh(s),d=c.length,l=Eh(t),u=l.length;if(d!=u&&!o)return!1;for(var h=d;h--;){var g=c[h];if(!(o?g in t:Jk.call(t,g)))return!1}var v=n.get(s),y=n.get(t);if(v&&y)return v==t&&y==s;var k=!0;n.set(s,t),n.set(t,s);for(var I=o;++h<d;){g=c[h];var D=s[g],N=t[g];if(r)var B=o?r(N,D,g,t,s,n):r(D,N,g,s,t,n);if(!(B===void 0?D===N||i(D,N,e,r,n):B)){k=!1;break}I||(I=g=="constructor")}if(k&&!I){var U=s.constructor,j=t.constructor;U!=j&&"constructor"in s&&"constructor"in t&&!(typeof U=="function"&&U instanceof U&&typeof j=="function"&&j instanceof j)&&(k=!1)}return n.delete(s),n.delete(t),k}var zk=1,lf="[object Arguments]",uf="[object Array]",Jd="[object Object]",Yk=Object.prototype,hf=Yk.hasOwnProperty;function Qk(s,t,e,r,i,n){var o=Ft(s),c=Ft(t),d=o?uf:jn(s),l=c?uf:jn(t);d=d==lf?Jd:d,l=l==lf?Jd:l;var u=d==Jd,h=l==Jd,g=d==l;if(g&&Fn(s)){if(!Fn(t))return!1;o=!0,u=!1}if(g&&!u)return n||(n=new vs),o||Fd(s)?cf(s,t,e,r,i,n):jk(s,t,d,e,r,i,n);if(!(e&zk)){var v=u&&hf.call(s,"__wrapped__"),y=h&&hf.call(t,"__wrapped__");if(v||y){var k=v?s.value():s,I=y?t.value():t;return n||(n=new vs),i(k,I,e,r,n)}}return g?(n||(n=new vs),Kk(s,t,e,r,i,n)):!1}function Kd(s,t,e,r,i){return s===t?!0:s==null||t==null||!Os(s)&&!Os(t)?s!==s&&t!==t:Qk(s,t,e,r,Kd,i)}var Xk=1,Zk=2;function e_(s,t,e,r){var i=e.length,n=i,o=!r;if(s==null)return!n;for(s=Object(s);i--;){var c=e[i];if(o&&c[2]?c[1]!==s[c[0]]:!(c[0]in s))return!1}for(;++i<n;){c=e[i];var d=c[0],l=s[d],u=c[1];if(o&&c[2]){if(l===void 0&&!(d in s))return!1}else{var h=new vs;if(r)var g=r(l,u,d,s,t,h);if(!(g===void 0?Kd(u,l,Xk|Zk,r,h):g))return!1}}return!0}function pf(s){return s===s&&!ss(s)}function t_(s){for(var t=Hd(s),e=t.length;e--;){var r=t[e],i=s[r];t[e]=[r,i,pf(i)]}return t}function mf(s,t){return function(e){return e==null?!1:e[s]===t&&(t!==void 0||s in Object(e))}}function s_(s){var t=t_(s);return t.length==1&&t[0][2]?mf(t[0][0],t[0][1]):function(e){return e===s||e_(e,s,t)}}function r_(s,t){return s!=null&&t in Object(s)}function i_(s,t,e){t=Dg(t,s);for(var r=-1,i=t.length,n=!1;++r<i;){var o=Gd(t[r]);if(!(n=s!=null&&e(s,o)))break;s=s[o]}return n||++r!=i?n:(i=s==null?0:s.length,!!i&&mh(i)&&hh(o,i)&&(Ft(s)||uo(s)))}function n_(s,t){return s!=null&&i_(s,t,r_)}var a_=1,o_=2;function c_(s,t){return vh(s)&&pf(t)?mf(Gd(s),t):function(e){var r=Mw(e,s);return r===void 0&&r===t?n_(e,s):Kd(t,r,a_|o_)}}function d_(s){return function(t){return t==null?void 0:t[s]}}function l_(s){return function(t){return Ng(t,s)}}function u_(s){return vh(s)?d_(Gd(s)):l_(s)}function h_(s){return typeof s=="function"?s:s==null?ch:typeof s=="object"?Ft(s)?c_(s[0],s[1]):s_(s):u_(s)}function p_(s){return function(t,e,r){for(var i=-1,n=Object(t),o=r(t),c=o.length;c--;){var d=o[s?c:++i];if(e(n[d],d,n)===!1)break}return t}}var m_=p_();const g_=m_;var f_=function(){return fs.Date.now()};const Rh=f_;var v_="Expected a function",S_=Math.max,T_=Math.min;function Ih(s,t,e){var r,i,n,o,c,d,l=0,u=!1,h=!1,g=!0;if(typeof s!="function")throw new TypeError(v_);t=vg(t)||0,ss(e)&&(u=!!e.leading,h="maxWait"in e,n=h?S_(vg(e.maxWait)||0,t):n,g="trailing"in e?!!e.trailing:g);function v(Z){var re=r,F=i;return r=i=void 0,l=Z,o=s.apply(F,re),o}function y(Z){return l=Z,c=setTimeout(D,t),u?v(Z):o}function k(Z){var re=Z-d,F=Z-l,ee=t-re;return h?T_(ee,n-F):ee}function I(Z){var re=Z-d,F=Z-l;return d===void 0||re>=t||re<0||h&&F>=n}function D(){var Z=Rh();if(I(Z))return N(Z);c=setTimeout(D,k(Z))}function N(Z){return c=void 0,g&&r?v(Z):(r=i=void 0,o)}function B(){c!==void 0&&clearTimeout(c),l=0,r=d=i=c=void 0}function U(){return c===void 0?o:N(Rh())}function j(){var Z=Rh(),re=I(Z);if(r=arguments,i=this,d=Z,re){if(c===void 0)return y(d);if(h)return clearTimeout(c),c=setTimeout(D,t),v(d)}return c===void 0&&(c=setTimeout(D,t)),o}return j.cancel=B,j.flush=U,j}function Ah(s,t,e){(e!==void 0&&!oo(s[t],e)||e===void 0&&!(t in s))&&ph(s,t,e)}function y_(s){return Os(s)&&lo(s)}function Mh(s,t){if(!(t==="constructor"&&typeof s[t]=="function")&&t!="__proto__")return s[t]}function E_(s){return co(s,po(s))}function b_(s,t,e,r,i,n,o){var c=Mh(s,e),d=Mh(t,e),l=o.get(d);if(l){Ah(s,e,l);return}var u=n?n(c,d,e+"",s,t,o):void 0,h=u===void 0;if(h){var g=Ft(d),v=!g&&Fn(d),y=!g&&!v&&Fd(d);u=d,g||v||y?Ft(c)?u=c:y_(c)?u=yg(c):v?(h=!1,u=Fg(d,!0)):y?(h=!1,u=Zg(d,!0)):u=[]:$w(d)||uo(d)?(u=c,uo(c)?u=E_(c):(!ss(c)||dh(c))&&(u=ef(d))):h=!1}h&&(o.set(d,u),i(u,d,r,n,o),o.delete(d)),Ah(s,e,u)}function gf(s,t,e,r,i){s!==t&&g_(t,function(n,o){if(i||(i=new vs),ss(n))b_(s,t,o,e,gf,r,i);else{var c=r?r(Mh(s,o),n,o+"",s,t,i):void 0;c===void 0&&(c=n),Ah(s,o,c)}},po)}function w_(s,t,e){for(var r=-1,i=s==null?0:s.length;++r<i;)if(e(t,s[r]))return!0;return!1}var P_="[object Map]",k_="[object Set]",__=Object.prototype,C_=__.hasOwnProperty;function R_(s){if(s==null)return!0;if(lo(s)&&(Ft(s)||typeof s=="string"||typeof s.splice=="function"||Fn(s)||Fd(s)||uo(s)))return!s.length;var t=jn(s);if(t==P_||t==k_)return!s.size;if(Bd(s))return!Og(s).length;for(var e in s)if(C_.call(s,e))return!1;return!0}function I_(s,t){return Kd(s,t)}var A_=ZE(function(s,t,e){gf(s,t,e)});const Ur=A_;var M_=1/0,O_=qn&&1/_h(new qn([,-0]))[1]==M_?function(s){return new qn(s)}:IE;const D_=O_;var N_=200;function L_(s,t,e){var r=-1,i=jE,n=s.length,o=!0,c=[],d=c;if(e)o=!1,i=w_;else if(n>=N_){var l=t?null:D_(s);if(l)return _h(l);o=!1,i=of,d=new vo}else d=t?[]:c;e:for(;++r<n;){var u=s[r],h=t?t(u):u;if(u=e||u!==0?u:0,o&&h===h){for(var g=d.length;g--;)if(d[g]===h)continue e;t&&d.push(h),c.push(u)}else i(d,h,e)||(d!==c&&d.push(h),c.push(u))}return c}function V_(s,t){return s&&s.length?L_(s,h_(t)):[]}function zd(s){const t={};return typeof(s==null?void 0:s.code)=="number"&&(t.code=s.code),typeof(s==null?void 0:s.code)=="string"&&(t.code=s.code.substring(0,100)),typeof(s==null?void 0:s.name)=="string"&&(t.name=s.name.substring(0,500)),typeof(s==null?void 0:s.message)=="string"&&(t.message=s.message.substring(0,500)),typeof(s==null?void 0:s.reason)=="string"&&(t.reason=s.reason.substring(0,500)),typeof(s==null?void 0:s.stack)=="string"&&(t.stack=s.stack.substring(0,500)),t}const x_={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},ff={STAGING:"staging",PROD:"prod"},$_={pip:!0,poll:!0,chat:!0,stage:!0,theme:!0,plugin:!0,tracing:!0,internals:!0,recording:!0,livestream:!0,participant:!0,connectedMeetings:!0,devTools:{logs:!1}};function So(s,t){const e=s.getValue("overrides");return e&&e[t]?e[t]:!1}function U_({baseURI:s}){return s.includes("staging.realtime")?ff.STAGING:ff.PROD}function vf({servicePrefix:s,baseURI:t}){return`${s}.${t}`}function Oh({servicePrefix:s,baseURI:t}){const e=s==="ws"?"wss":"https",r=vf({servicePrefix:"api",baseURI:t});return`${e}://${r}/${s}`}function B_(s){const t=s.getValue("baseURI");return{daCollector:Oh({servicePrefix:"telemetry",baseURI:t}).replace("https://","")}}const F_='<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>',H_='<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>',Yd=s=>{if(!s)return;if(!s.startsWith("<svg"))return new Promise(n=>{n(s)});const e=new Blob([s],{type:"image/svg+xml"}),r=new Image,i=window.URL.createObjectURL(e);return new Promise((n,o)=>{r.onload=()=>{n(r),window.URL.revokeObjectURL(i)},r.onerror=()=>{o(),window.URL.revokeObjectURL(i)},r.src=i})},Di={logs:"https://api.realtime.cloudflare.com/logs",mock:{url:"https://api.realtime.cloudflare.com/mock",domain:"mock.realtime.cloudflare.com",app:"https://examples.realtime.cloudflare.com/meeting",stagingApp:"https://examples.staging.realtime.cloudflare.com/meeting"},apiBase:{prod:"https://api.realtime.cloudflare.com",staging:"https://api.staging.realtime.cloudflare.com",prodAlternate:"https://api.realtime.cloudflare.com"},baseURI:{prod:"realtime.cloudflare.com",staging:"staging.realtime.cloudflare.com"}},q_=/\b(?:1[7-9](?:\.\d+)?|[2-9]\d(?:\.\d+)?|[1-9]\d{2,}(?:\.\d+)?)\b/,Dh="__rtk_plugins__",j_=[Dh];function Sf(s){var r,i,n;const t=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((r=window.location.host)==null?void 0:r.includes(Di.baseURI.staging)),e=!!((n=(i=s==null?void 0:s.getValue("modules"))==null?void 0:i.devTools)!=null&&n.logs);return t||e}function G_(s,t){var r;const e=(r=s==null?void 0:s.getValue("telemetry"))==null?void 0:r.logLevel;if(e==="off")return!1;if(e!=="all"){const i=["debug","log","info","warn","error"],n=i.indexOf(t.toLowerCase()),o=i.indexOf(e);if(n<o)return!1}return!0}function Tf(s,t,e={}){return Object.getOwnPropertyNames(s).forEach(r=>{var n;if([null,void 0,NaN].includes(s[r])||t&&(((n=t.match(/\./g))==null?void 0:n.length)||0)>=10)return;const i=t?`${t}.${r}`:r;typeof s[r]=="object"?Tf(s[r],i,e):["number","string","boolean"].includes(typeof s[r])&&(e[i]=s[r])}),e}function yf(s,t,e={},r=""){const i={};try{const n=JSON.stringify(e),o=JSON.parse(n),c=Tf(o,r),d=JSON.stringify(c);if(!(t==null?void 0:t.startsWith("[SDP]"))&&d.length>5e3){const u=`Log named: "${t}" is trying to log an flattened object of size
|
|
10
|
-
${d.length} chars that is beyond permitted limit of 5000 chars. Please optimize.`;throw
|
|
11
|
-
${this.message}`;try{let l=n&&!!i;r&&r.endsWith("00")&&i&&(l=!0),l&&i.error("ClientError",{error:{message:this.message,name:this.name,code:r}});const u=Br.getContext(Br.getMostRecentPeerId());if(u){const h=u.getValue("onError");try{h(this)}catch(g){}}typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("ClientError",{detail:this}))}catch(l){}}}function Xd(s,t,e,r){if(r instanceof C)throw r;if(r instanceof t){const i=new C(r.message,e);throw i.stack=r.stack,i}else throw r}function Ef(s,t,e){if(!s.value){const i=s.get,n=s.set;return i&&(s.get=function(){try{return i.apply(this)}catch(o){Xd(this,t,e,o)}}),n&&(s.set=function(o){try{return n.apply(this,[o])}catch(c){Xd(this,t,e,c)}}),s}const r=s.value;return s.value=function(...i){try{const n=r.apply(this,i);return n&&n instanceof Promise?n.catch(o=>{Xd(this,t,e,o)}):n}catch(n){Xd(this,t,e,n)}},s}function z_(s,t){return(e,r,i)=>{if(i)return Ef(i,s,t);for(const n of Reflect.ownKeys(e.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(e.prototype,n);(o.value instanceof Function||o.get instanceof Function||o.set instanceof Function)&&Object.defineProperty(e.prototype,n,Ef(o,s,t))}}}const pt=s=>z_(Error,s);var Ss=(s=>(s.GroupCall="GROUP_CALL",s.Webinar="WEBINAR",s.AudioRoom="AUDIO_ROOM",s.Livestream="LIVESTREAM",s.Chat="CHAT",s))(Ss||{}),G=(s=>(s.Allowed="ALLOWED",s.NotAllowed="NOT_ALLOWED",s.CanRequest="CAN_REQUEST",s))(G||{});typeof process!="undefined"&&(xS=process==null?void 0:process.env)!=null&&xS.FLAGSMITH_ENVIRONMENT_KEY&&process.env.FLAGSMITH_ENVIRONMENT_KEY;var bf=[-2,-1,0,1,2],Y_=[0,1,2,3,4];function Q_(s){s=s.trim();let t="0",e="0",r="0";return s.length==4?(t=`0x${s[1]}${s[1]}`,e=`0x${s[2]}${s[2]}`,r=`0x${s[3]}${s[3]}`):s.length>6&&(t=`0x${s[1]}${s[2]}`,e=`0x${s[3]}${s[4]}`,r=`0x${s[5]}${s[6]}`),[+t,+e,+r]}var X_=(s,t,e)=>{let r,i,n;if(t==0)r=i=n=e;else{const o=(l,u,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?l+(u-l)*6*h:h<.5?u:h<.6666666666666666?l+(u-l)*(.6666666666666666-h)*6:l),c=e<.5?e*(1+t):e+t-e*t,d=2*e-c;r=o(d,c,s+1/3),i=o(d,c,s),n=o(d,c,s-1/3)}return[Math.round(r*255),Math.round(i*255),Math.round(n*255)]},Z_=(s,t,e)=>{s/=255,t/=255,e/=255;const r=Math.max(s,t,e),i=Math.min(s,t,e);let n,o;const c=(r+i)/2;if(r==i)n=o=0;else{const d=r-i;switch(o=c>.5?d/(2-r-i):d/(r+i),r){case s:n=(t-e)/d+(t<e?6:0);break;case t:n=(e-s)/d+2;break;case e:n=(s-t)/d+4;break}n/=6}return[n,o,c]},eC=(s,t,e)=>{const r=i=>i.toString(16).padStart(2,"0");return`#${r(s)}${r(t)}${r(e)}`},wf=(s,t=bf,e=.4)=>{const r=[],[i,n,o]=Q_(s),[c,d,l]=Z_(i,n,o),u=Math.round(l*100);u>70?e=.8:u>60?e=.9:u<10?e=.075:u<42&&(e=.3);const h=t.findIndex(I=>I===0);if(h===-1)throw new Error("Invalid reducer provided, it must contain atleast one zero");const g=5-h,v=h+1,y=(100-u)/g,k=u/v;for(const I of t){let D;I<0?D=u+I*k*e:I>0?D=u+I*y*e:D=u;const[N,B,U]=X_(c,d,D/100);r.push(eC(N,B,U))}return r},Pf={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"}},tC=s=>{const[t,e,r,i,n]=wf(s,bf);return{300:t,400:e,500:r,600:i,700:n}},sC=s=>{if(s==="#FFFFFF")return Pf.light.background;if(s==="#000000")return Pf.dark.background;const[t,e,r,i,n]=wf(s,Y_);return{1e3:t,900:e,800:r,700:i,600:n}},rC={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:tC("#2160FD"),background:sC("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function kf(){return kh(rC)}var iC={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:kf(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:30,simulcast:!1},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"hybrid"};function nC(){return kh(iC)}var aC={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:kf(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:30,simulcast:!1},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"2.0.0"};function Nh(){return kh(aC)}function oC(){Pe.isElectron()&&window.electronGetDisplayMediaSource&&(navigator.mediaDevices.getDisplayMedia=async()=>{const s=await window.electronGetDisplayMediaSource({types:["window","screen"]});let t=[];if(s&&(Array.isArray(s)?t=s:t=[s]),!(t!=null&&t.length))throw new Error("Couldn't find any media source for screen share.");let e=t.find(n=>{var o;return(o=n.id)==null?void 0:o.includes("screen")});e=e!=null?e:t[0];const r={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e.id}}};return await navigator.mediaDevices.getUserMedia(r)})}var P=(s=>(s.NEW_PRODUCER="NEW_PRODUCER",s.PRODUCER_HANDOVER="PRODUCER_HANDOVER",s.ROOM_NODE_CONNECTION_ERROR="ROOM_NODE_CONNECTION_ERROR",s.SOCKET_SERVICE_ROOM_JOINED="SOCKET_SERVICE_ROOM_JOINED",s.SOCKET_SERVICE_RECONNECTED="SOCKET_SERVICE_RECONNECTED",s.SOCKET_SERVICE_DISCONNECTED="SOCKET_SERVICE_DISCONNECTED",s.SOCKET_SERVICE_FAILED="SOCKET_SERVICE_FAILED",s.SOCKET_STATE_UPDATE="SOCKET_STATE_UPDATE",s.ROOM_NODE_RECONNECTED="ROOM_NODE_RECONNECTED",s.ROOM_NODE_DISCONNECTED="ROOM_NODE_DISCONNECTED",s.ROOM_NODE_FAILED="ROOM_NODE_FAILED",s.MEDIA_ROOM_JOIN_FAILED="MEDIA_ROOM_JOIN_FAILED",s.TRANSPORT_STATE_UPDATE="TRANSPORT_STATE_UPDATE",s.PRODUCER_SCORE_UPDATE="PRODUCER_SCORE_UPDATE",s.CONSUMER_SCORE_UPDATE="CONSUMER_SCORE_UPDATE",s.PRODUCER_STATUS_UPDATE="PRODUCER_STATUS_UPDATE",s.CONSUMER_STATUS_UPDATE="CONSUMER_STATUS_UPDATE",s.LOW_CONSUMER_SCORE="LOW_CONSUMER_SCORE",s.MEDIA_PERMISSION_ERROR="MEDIA_PERMISSION_ERROR",s.MEDIA_PERMISSION_UPDATE="MEDIA_PERMISSION_UPDATE",s.MESSAGE="websocket/message",s.ROOM_MESSAGE="websocket/room-message",s.PEER_JOINED_INTERNAL="peer/joined-internal",s.PEER_CLOSED="websocket/peer-closed",s.CONSUMER_CLOSED="websocket/consumer-closed",s.CONSUMER_PAUSED="websocket/consumer-paused",s.CONSUMER_RESUMED="websocket/consumer-resumed",s.NEW_CONSUMER_CREATED="NEW_CONSUMER_CREATED",s.PRODUCER_CLOSED="websocket/producer-closed",s.PRODUCER_SCORE="websocket/producer-score",s.CONSUMER_SCORE="websocket/consumer-score",s.PRODUCER_TOGGLE="cf/producer-toggle",s.UPDATE_ACTIVE="media/update-active",s.RESET_PRODUCER_STATE="cf/reset-producer-state",s.ROOM_STATE="sockethub/room-state",s.GET_STAGE_REQUESTS="GET_STAGE_REQUESTS",s.UPDATE_STAGE_REQUESTS="UPDATE_STAGE_REQUESTS",s.KICK_PEER="KICK_PEER",s.UPDATE_PEER_STAGE_STATUS="UPDATE_PEER_STAGE_STATUS",s.JOIN_MEDIA_ROOM="JOIN_MEDIA_ROOM",s.LEAVE_MEDIA_ROOM="LEAVE_MEDIA_ROOM",s.PIP_HANGUP="PIP_HANGUP",s.E2EE_ACTIVE_PRODUCER="E2EE_ACTIVE_PRODUCER",s.E2EE_INACTIVE_PRODUCER="E2EE_INACTIVE_PRODUCER",s.E2EE_ACTIVE_CONSUMER="E2EE_ACTIVE_CONSUMER",s.E2EE_INACTIVE_CONSUMER="E2EE_INACTIVE_CONSUMER",s.ENABLE_E2EE_CRYPTOR_ON_NEW_CONSUMER="ENABLE_E2EE_CRYPTOR_ON_NEW_CONSUMER",s.SOCKET_PEERS="SOCKET_PEERS",s.UPDATE_PERMISSIONS="UPDATE_PERMISSIONS",s.MAX_SPATIAL_LAYER_CHANGE="MAX_SPATIAL_LAYER_CHANGE",s.MUTE_SELF="MUTE_SELF",s.MUTE_SELF_VIDEO="MUTE_SELF_VIDEO",s))(P||{});const _f=(s,t)=>!s.includes("currentColor")||!t?s:s.replace(/currentColor/g,t);function cC(s,t=2){return s.replace(/[^\u00BF-\u1FFF\u2C00-\uD7FF\w\s]/g,"").trim().split(/\s+/).slice(0,t).map(i=>i.charAt(0)).join("").toUpperCase()}const Cf=1080,Rf=1920,dC=(s,t,e,r,i,n)=>{let o=.5,c=.5;const d=i,l=n,u=Math.min(e/d,r/l);let h=d*u,g=l*u,v,y,k,I,D=1;return h<e&&(D=e/h),Math.abs(D-1)<1e-14&&g<r&&(D=r/g),h*=D,g*=D,k=d/(h/e),I=l/(g/r),v=(d-k)*o,y=(l-I)*c,v<0&&(v=0),y<0&&(y=0),k>d&&(k=d),I>l&&(I=l),[v,y,k,I,s,t,e,r]},Hp=class extends Bt{constructor(e,r,i,n){const o=e.getValue("logger");super(o);m(this,Lt,void 0);m(this,ei,void 0);m(this,gt,void 0);m(this,os,void 0);m(this,Le,{height:Cf,width:Rf});m(this,cs,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"});m(this,Sr,void 0);m(this,je,{});m(this,Ue,void 0);m(this,ia,void 0);m(this,na,void 0);m(this,aa,void 0);m(this,Tr,void 0);m(this,oa,!1);m(this,zl,e=>{const r=a(this,ia);if(f(this,ia,e),!r||r===e)return;const i=a(this,je)[r];i&&(delete a(this,je)[r],!a(this,je)[e]&&(a(this,je)[e]={...i,id:e}))});p(this,"cleanupEventListeners",()=>{a(this,ei).unsubscribe("stageStatus",this.handlePipMediaControls),a(this,Ue).removeListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,Ue).removeListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,Ue).removeListener("roomLeft",a(this,qo))});m(this,qo,({state:e})=>{e!=="disconnected"&&this.disable()});p(this,"enablePipMediaControls",()=>{this.mountAudioEvents(),this.mountVideoEvents()});p(this,"onSelfVideoUpdateListener",({videoEnabled:e})=>{this.updateMediaSession("CAMERA",e)});p(this,"onSelfAudioUpdateListener",({audioEnabled:e})=>{this.updateMediaSession("MIC",e)});p(this,"handlePipMediaControls",e=>{e==="ON_STAGE"?this.enablePipMediaControls():this.unmountEvents()});p(this,"eventCallback",e=>{e==="CAMERA"&&(a(this,Ue).videoEnabled?a(this,Ue).disableVideo():a(this,Ue).enableVideo(),this.emit("cameraToggled")),e==="MIC"&&(a(this,Ue).audioEnabled?a(this,Ue).disableAudio():a(this,Ue).enableAudio(),this.emit("micToggled")),e==="END"&&(a(this,ei).getValue("peerSessionStore").emit(P.PIP_HANGUP),this.cleanupEventListeners(),this.emit("hangup"),this.cleanup())});p(this,"unmountEvents",()=>{navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("togglemicrophone",void 0),navigator.mediaSession.setActionHandler("togglecamera",void 0))});p(this,"animate",()=>{if(!this.isActive&&a(this,Tr)==="active"){this.disable(!0);return}a(this,je)!==void 0&&this.paintCanvas(),a(this,Sr)!==void 0&&f(this,Sr,requestAnimationFrame(()=>this.animate()))});p(this,"disable",(e=!1)=>{f(this,Tr,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(a(this,Sr)),e!==!0&&document.body.removeChild(a(this,gt)),f(this,Sr,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()});f(this,ei,e),f(this,Tr,"idle"),f(this,Ue,r),f(this,ia,e.getValue("peerId")),a(this,ei).subscribe("peerId",a(this,zl)),f(this,cs,{brand:r.config.designTokens.colors.brand[500],background:r.config.designTokens.colors.background[1e3],text:r.config.designTokens.colors.text,videoBackground:r.config.designTokens.colors.videoBg,textOnBrand:r.config.designTokens.colors.textOnBrand}),i&&this.setupIcon("pin",i),n&&this.setupIcon("handRaise",n)}static async _init(e,r){var o,c,d;let i,n;try{const l=(d=(c=(o=r.config)==null?void 0:o.designTokens)==null?void 0:c.colors)==null?void 0:d.textOnBrand;i=await Yd(_f(F_,l)),n=await Yd(_f(H_,l))}catch(l){}return new Hp(e,r,i,n)}async setupIcon(e,r){switch(e){case"handRaise":f(this,aa,r);break;case"pin":f(this,na,r);break}}async overrideIcon(e,r){switch(e){case"handRaise":f(this,aa,await Yd(r));break;case"pin":f(this,na,await Yd(r));break}}constructImage(e){const r=new Image,i=new Blob([e],{type:"image/svg+xml"}),n=window.URL.createObjectURL(i);return new Promise(o=>{r.onload=()=>{o(r),window.URL.revokeObjectURL(n)},r.src=n})}createVideoContainer(){f(this,gt,document.createElement("div")),a(this,gt).style.width="0.1px",a(this,gt).style.height="0.1px",a(this,gt).style.overflow="hidden",a(this,gt).style.position="absolute",a(this,gt).style.bottom="0",a(this,gt).style.right="0",a(this,gt).style.opacity="0",a(this,gt).appendChild(a(this,os))}setupEventListeners(){a(this,ei).subscribe("stageStatus",this.handlePipMediaControls),a(this,Ue).addListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,Ue).addListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,Ue).addListener("roomLeft",a(this,qo))}createCanvas(){const e=document.createElement("canvas");e.height=a(this,Le).height,e.width=a(this,Le).width,f(this,Lt,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||a(this,Ue).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||a(this,Ue).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const r=Object.values(a(this,je)).reduce((i,n)=>(i[n.pinned?"pinned":"regular"].push(n),i),{pinned:[],regular:[]});return[...r.pinned,...r.regular]}drawEmptyTile(e,r,i,n){if(a(this,Lt)===void 0)return;const o=a(this,Lt).getContext("2d"),c=a(this,Lt).width,d=0,l=0,u=r-d*2,h=i-d*2,g=Math.floor(c/u),v=Math.floor(e/g),k=e%g*(u+d)+d,I=v*(h+d)+d,{displayText:D,image:N}=n!=null?n:{};o.fillStyle=D||N?a(this,cs).videoBackground:a(this,cs).background,o.strokeStyle=a(this,cs).brand,o.beginPath(),o.moveTo(k+l,I),o.arcTo(k+u,I,k+u,I+l,l),o.arcTo(k+u,I+h,k+u-l,I+h,l),o.arcTo(k,I+h,k,I+h-l,l),o.arcTo(k,I,k+l,I,l),o.closePath(),o.fill(),o.stroke();const B=u/6,U=u/2+k,j=h/2+I;o.save(),(D||N)&&(o.beginPath(),o.arc(U,j,B,0,Math.PI*2),o.fillStyle=a(this,cs).brand,o.fill(),N?(o.clip(),o.drawImage(N,U-B,j-B,B*2,B*2),o.restore()):D&&(o.fillStyle=a(this,cs).textOnBrand,o.font=`${B/2}px sans-serif`,o.textAlign="center",o.textBaseline="middle",o.fillText(D,U,j)),this.drawIcons(n,k,I,Math.max(u,h)))}drawIcons(e,r,i,n){const o=Math.min(Math.max(n*.15,100),200),c=o*.2,d=o*.2;let l=r+c;const u=i+c,h=g=>{const v=a(this,Lt).getContext("2d");v.save(),v.fillStyle=a(this,cs).background,v.beginPath(),v.moveTo(l+d,u),v.arcTo(l+o,u,l+o,u+d,d),v.arcTo(l+o,u+o,l+o-d,u+o,d),v.arcTo(l,u+o,l,u+o-d,d),v.arcTo(l,u,l+d,u,d),v.closePath(),v.fill(),typeof g=="string"?(v.font=`${o/1.5}px sans-serif`,v.fillStyle=a(this,cs).text,v.textAlign="center",v.textBaseline="top",v.fillText(g,o/2+l,u+c)):v.drawImage(g,l+c,u+c,o-c*2,o-c*2),l+=o+c,v.restore()};e.pinned&&h(a(this,na)),e.handRaised&&h(a(this,aa)),e.reaction&&h(e.reaction)}drawTile(e,r,i){var l,u;if(a(this,Lt)===void 0)return;const n=a(this,Lt).getContext("2d");n.fillStyle=a(this,cs).background,n.fillRect(0,0,a(this,Lt).width,a(this,Lt).height);const o=this.getSources();let c=0,d=0;for(;c<a(this,Le).height-5;){let h=0;for(;h<a(this,Le).width-5&&d<i;){if((l=o[d])!=null&&l.enabled){const g=o[d].element,[v,y,k,I,D,N,B,U]=dC(h,c,e,r,g.videoWidth,g.videoHeight);((u=g==null?void 0:g.classList)==null?void 0:u.contains("mirror"))?(n.save(),n.scale(-1,1),n.drawImage(g,v,y,k,I,-1*D,N,-1*B,U),n.restore()):n.drawImage(g,v,y,k,I,D,N,B,U),this.drawIcons(o[d],D,N,Math.max(B,U))}else this.drawEmptyTile(d,e,r,o[d]);d+=1,h+=e}c+=r}}calcGridElemSize(e){switch(e){case 0:case 1:return[a(this,Le).width,a(this,Le).height];case 2:return[Math.floor(a(this,Le).width/2),a(this,Le).height];case 3:case 4:return[Math.floor(a(this,Le).width/2),Math.floor(a(this,Le).height/2)];case 5:case 6:return[Math.floor(a(this,Le).width/3),Math.floor(a(this,Le).height/2)];case 7:case 8:case 9:return[Math.floor(a(this,Le).width/3),Math.floor(a(this,Le).height/3)];default:return[Math.floor(a(this,Le).width/3),Math.floor(a(this,Le).height/2)]}}paintCanvas(){let e=this.getSources().length;e!==1&&(e=e%2>0?e+1:e);const[r,i]=this.calcGridElemSize(e);this.drawTile(r,i,e)}isSupported(){var e;return!!window.chrome&&document.pictureInPictureEnabled&&((e=a(this,Ue).config)==null?void 0:e.viewType)!=="LIVESTREAM"}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(f(this,oa,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),a(this,gt))try{document.body.removeChild(a(this,gt))}catch(e){}this.removeAllSources(),f(this,Lt,void 0),f(this,os,void 0),f(this,Sr,void 0)}init({height:e,width:r}={}){if(!this.isSupported())throw this.logger.error("Pip.unsupported"),new Error("Picture-in-picture is not available in this environment");if(a(this,oa))return;f(this,oa,!0),this.createCanvas();const i=document.createElement("video");f(this,Le,{height:e!=null?e:Cf,width:r!=null?r:Rf}),i.height=a(this,Le).height,i.width=a(this,Le).width,i.autoplay=!0,i.muted=!0,i.srcObject=a(this,Lt).captureStream(24),f(this,os,i),a(this,os).onloadedmetadata=()=>{try{this.emit("pipStarted"),a(this,os).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch(n){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){a(this,je)[e]!==void 0&&(a(this,je)[e].enabled=!0)}disableSource(e){a(this,je)[e]!==void 0&&(a(this,je)[e].enabled=!1)}async generateAvatar(e,r){if(!r)return;const i=new Image;try{const n=await(await fetch(r)).blob(),o=window.URL.createObjectURL(n);i.onload=()=>{this.updateSource(e,{image:i}),window.URL.revokeObjectURL(o)},i.src=o}catch(n){this.logger.error("Pip::GenerateAvatar",{error:n})}}addSource(e,r,i,n=!1,o=void 0,c=void 0,d=!1){this.logger.debug("Pip::AddSource",{pip:{id:e,handRaised:d}}),a(this,je)[e]={id:e,element:r,enabled:i,pinned:n,displayText:o?cC(o):void 0,imageUrl:c,handRaised:d},c&&this.generateAvatar(e,c)}updateSource(e,r){this.logger.info("Pip::UpdateSource",{pip:{id:e,handRaised:r.handRaised,reaction:r.reaction}});const i=a(this,je)[e];i&&(a(this,je)[e]={...i,...r})}removeSource(e){delete a(this,je)[e]}removePinnedSource(){Object.values(a(this,je)).forEach(r=>{r.pinned&&this.removeSource(r.id)})}removeAllSources(){f(this,je,{})}enable(){f(this,Tr,"activating"),this.setupEventListeners(),this.setupMediaSessionEvents(),this.updateMediaSession("CAMERA",a(this,Ue).videoEnabled),this.updateMediaSession("MIC",a(this,Ue).audioEnabled),document.body.appendChild(a(this,gt)),f(this,Sr,requestAnimationFrame(()=>this.animate())),a(this,os).onloadedmetadata=()=>{a(this,os).requestPictureInPicture().then(()=>{f(this,Tr,"active")})},a(this,os).readyState===4&&a(this,os).requestPictureInPicture().then(()=>{f(this,Tr,"active")})}};let Lh=Hp;Lt=new WeakMap,ei=new WeakMap,gt=new WeakMap,os=new WeakMap,Le=new WeakMap,cs=new WeakMap,Sr=new WeakMap,je=new WeakMap,Ue=new WeakMap,ia=new WeakMap,na=new WeakMap,aa=new WeakMap,Tr=new WeakMap,oa=new WeakMap,zl=new WeakMap,qo=new WeakMap;function Vh(s){let t=typeof s;if(t=="object"){if(Array.isArray(s))return"array";if(s===null)return"null"}return t}function lC(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}let ir="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Zd=[];for(let s=0;s<ir.length;s++)Zd[ir[s].charCodeAt(0)]=s;Zd["-".charCodeAt(0)]=ir.indexOf("+"),Zd["_".charCodeAt(0)]=ir.indexOf("/");function uC(s){let t=s.length*3/4;s[s.length-2]=="="?t-=2:s[s.length-1]=="="&&(t-=1);let e=new Uint8Array(t),r=0,i=0,n,o=0;for(let c=0;c<s.length;c++){if(n=Zd[s.charCodeAt(c)],n===void 0)switch(s[c]){case"=":i=0;case`
|
|
12
|
-
`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(i){case 0:o=n,i=1;break;case 1:e[r++]=o<<2|(n&48)>>4,o=n,i=2;break;case 2:e[r++]=(o&15)<<4|(n&60)>>2,o=n,i=3;break;case 3:e[r++]=(o&3)<<6|n,i=0;break}}if(i==1)throw Error("invalid base64 string.");return e.subarray(0,r)}function hC(s){let t="",e=0,r,i=0;for(let n=0;n<s.length;n++)switch(r=s[n],e){case 0:t+=ir[r>>2],i=(r&3)<<4,e=1;break;case 1:t+=ir[i|r>>4],i=(r&15)<<2,e=2;break;case 2:t+=ir[i|r>>6],t+=ir[r&63],e=0;break}return e&&(t+=ir[i],t+="=",e==1&&(t+="=")),t}var el;(function(s){s.symbol=Symbol.for("protobuf-ts/unknown"),s.onRead=(e,r,i,n,o)=>{(t(r)?r[s.symbol]:r[s.symbol]=[]).push({no:i,wireType:n,data:o})},s.onWrite=(e,r,i)=>{for(let{no:n,wireType:o,data:c}of s.list(r))i.tag(n,o).raw(c)},s.list=(e,r)=>{if(t(e)){let i=e[s.symbol];return r?i.filter(n=>n.no==r):i}return[]},s.last=(e,r)=>s.list(e,r).slice(-1)[0];const t=e=>e&&Array.isArray(e[s.symbol])})(el||(el={}));var $e;(function(s){s[s.Varint=0]="Varint",s[s.Bit64=1]="Bit64",s[s.LengthDelimited=2]="LengthDelimited",s[s.StartGroup=3]="StartGroup",s[s.EndGroup=4]="EndGroup",s[s.Bit32=5]="Bit32"})($e||($e={}));function pC(){let s=0,t=0;for(let r=0;r<28;r+=7){let i=this.buf[this.pos++];if(s|=(i&127)<<r,!(i&128))return this.assertBounds(),[s,t]}let e=this.buf[this.pos++];if(s|=(e&15)<<28,t=(e&112)>>4,!(e&128))return this.assertBounds(),[s,t];for(let r=3;r<=31;r+=7){let i=this.buf[this.pos++];if(t|=(i&127)<<r,!(i&128))return this.assertBounds(),[s,t]}throw new Error("invalid varint")}function xh(s,t,e){for(let n=0;n<28;n=n+7){const o=s>>>n,c=!(!(o>>>7)&&t==0),d=(c?o|128:o)&255;if(e.push(d),!c)return}const r=s>>>28&15|(t&7)<<4,i=!!(t>>3);if(e.push((i?r|128:r)&255),!!i){for(let n=3;n<31;n=n+7){const o=t>>>n,c=!!(o>>>7),d=(c?o|128:o)&255;if(e.push(d),!c)return}e.push(t>>>31&1)}}const tl=(1<<16)*(1<<16);function If(s){let t=s[0]=="-";t&&(s=s.slice(1));const e=1e6;let r=0,i=0;function n(o,c){const d=Number(s.slice(o,c));i*=e,r=r*e+d,r>=tl&&(i=i+(r/tl|0),r=r%tl)}return n(-24,-18),n(-18,-12),n(-12,-6),n(-6),[t,r,i]}function $h(s,t){if(t>>>0<=2097151)return""+(tl*t+(s>>>0));let e=s&16777215,r=(s>>>24|t<<8)>>>0&16777215,i=t>>16&65535,n=e+r*6777216+i*6710656,o=r+i*8147497,c=i*2,d=1e7;n>=d&&(o+=Math.floor(n/d),n%=d),o>=d&&(c+=Math.floor(o/d),o%=d);function l(u,h){let g=u?String(u):"";return h?"0000000".slice(g.length)+g:g}return l(c,0)+l(o,c)+l(n,1)}function Af(s,t){if(s>=0){for(;s>127;)t.push(s&127|128),s=s>>>7;t.push(s)}else{for(let e=0;e<9;e++)t.push(s&127|128),s=s>>7;t.push(1)}}function mC(){let s=this.buf[this.pos++],t=s&127;if(!(s&128))return this.assertBounds(),t;if(s=this.buf[this.pos++],t|=(s&127)<<7,!(s&128))return this.assertBounds(),t;if(s=this.buf[this.pos++],t|=(s&127)<<14,!(s&128))return this.assertBounds(),t;if(s=this.buf[this.pos++],t|=(s&127)<<21,!(s&128))return this.assertBounds(),t;s=this.buf[this.pos++],t|=(s&15)<<28;for(let e=5;s&128&&e<10;e++)s=this.buf[this.pos++];if(s&128)throw new Error("invalid varint");return this.assertBounds(),t>>>0}let ve;function gC(){const s=new DataView(new ArrayBuffer(8));ve=globalThis.BigInt!==void 0&&typeof s.getBigInt64=="function"&&typeof s.getBigUint64=="function"&&typeof s.setBigInt64=="function"&&typeof s.setBigUint64=="function"?{MIN:BigInt("-9223372036854775808"),MAX:BigInt("9223372036854775807"),UMIN:BigInt("0"),UMAX:BigInt("18446744073709551615"),C:BigInt,V:s}:void 0}gC();function Mf(s){if(!s)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const Of=/^-?[0-9]+$/,sl=4294967296,rl=2147483648;class Df{constructor(t,e){this.lo=t|0,this.hi=e|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let t=this.hi*sl+(this.lo>>>0);if(!Number.isSafeInteger(t))throw new Error("cannot convert to safe number");return t}}class mt extends Df{static from(t){if(ve)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=ve.C(t);case"number":if(t===0)return this.ZERO;t=ve.C(t);case"bigint":if(!t)return this.ZERO;if(t<ve.UMIN)throw new Error("signed value for ulong");if(t>ve.UMAX)throw new Error("ulong too large");return ve.V.setBigUint64(0,t,!0),new mt(ve.V.getInt32(0,!0),ve.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!Of.test(t))throw new Error("string is no integer");let[e,r,i]=If(t);if(e)throw new Error("signed value for ulong");return new mt(r,i);case"number":if(t==0)return this.ZERO;if(!Number.isSafeInteger(t))throw new Error("number is no integer");if(t<0)throw new Error("signed value for ulong");return new mt(t,t/sl)}throw new Error("unknown value "+typeof t)}toString(){return ve?this.toBigInt().toString():$h(this.lo,this.hi)}toBigInt(){return Mf(ve),ve.V.setInt32(0,this.lo,!0),ve.V.setInt32(4,this.hi,!0),ve.V.getBigUint64(0,!0)}}mt.ZERO=new mt(0,0);class Ee extends Df{static from(t){if(ve)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=ve.C(t);case"number":if(t===0)return this.ZERO;t=ve.C(t);case"bigint":if(!t)return this.ZERO;if(t<ve.MIN)throw new Error("signed long too small");if(t>ve.MAX)throw new Error("signed long too large");return ve.V.setBigInt64(0,t,!0),new Ee(ve.V.getInt32(0,!0),ve.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!Of.test(t))throw new Error("string is no integer");let[e,r,i]=If(t);if(e){if(i>rl||i==rl&&r!=0)throw new Error("signed long too small")}else if(i>=rl)throw new Error("signed long too large");let n=new Ee(r,i);return e?n.negate():n;case"number":if(t==0)return this.ZERO;if(!Number.isSafeInteger(t))throw new Error("number is no integer");return t>0?new Ee(t,t/sl):new Ee(-t,-t/sl).negate()}throw new Error("unknown value "+typeof t)}isNegative(){return(this.hi&rl)!==0}negate(){let t=~this.hi,e=this.lo;return e?e=~e+1:t+=1,new Ee(e,t)}toString(){if(ve)return this.toBigInt().toString();if(this.isNegative()){let t=this.negate();return"-"+$h(t.lo,t.hi)}return $h(this.lo,this.hi)}toBigInt(){return Mf(ve),ve.V.setInt32(0,this.lo,!0),ve.V.setInt32(4,this.hi,!0),ve.V.getBigInt64(0,!0)}}Ee.ZERO=new Ee(0,0);const Nf={readUnknownField:!0,readerFactory:s=>new vC(s)};function fC(s){return s?Object.assign(Object.assign({},Nf),s):Nf}class vC{constructor(t,e){this.varint64=pC,this.uint32=mC,this.buf=t,this.len=t.length,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.textDecoder=e!=null?e:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let t=this.uint32(),e=t>>>3,r=t&7;if(e<=0||r<0||r>5)throw new Error("illegal tag: field no "+e+" wire type "+r);return[e,r]}skip(t){let e=this.pos;switch(t){case $e.Varint:for(;this.buf[this.pos++]&128;);break;case $e.Bit64:this.pos+=4;case $e.Bit32:this.pos+=4;break;case $e.LengthDelimited:let r=this.uint32();this.pos+=r;break;case $e.StartGroup:let i;for(;(i=this.tag()[1])!==$e.EndGroup;)this.skip(i);break;default:throw new Error("cant skip wire type "+t)}return this.assertBounds(),this.buf.subarray(e,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)}int64(){return new Ee(...this.varint64())}uint64(){return new mt(...this.varint64())}sint64(){let[t,e]=this.varint64(),r=-(t&1);return t=(t>>>1|(e&1)<<31)^r,e=e>>>1^r,new Ee(t,e)}bool(){let[t,e]=this.varint64();return t!==0||e!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new mt(this.sfixed32(),this.sfixed32())}sfixed64(){return new Ee(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 t=this.uint32(),e=this.pos;return this.pos+=t,this.assertBounds(),this.buf.subarray(e,e+t)}string(){return this.textDecoder.decode(this.bytes())}}function ne(s,t){if(!s)throw new Error(t)}const SC=34028234663852886e22,TC=-34028234663852886e22,yC=4294967295,EC=2147483647,bC=-2147483648;function To(s){if(typeof s!="number")throw new Error("invalid int 32: "+typeof s);if(!Number.isInteger(s)||s>EC||s<bC)throw new Error("invalid int 32: "+s)}function il(s){if(typeof s!="number")throw new Error("invalid uint 32: "+typeof s);if(!Number.isInteger(s)||s>yC||s<0)throw new Error("invalid uint 32: "+s)}function Uh(s){if(typeof s!="number")throw new Error("invalid float 32: "+typeof s);if(Number.isFinite(s)&&(s>SC||s<TC))throw new Error("invalid float 32: "+s)}const Lf={writeUnknownFields:!0,writerFactory:()=>new PC};function wC(s){return s?Object.assign(Object.assign({},Lf),s):Lf}class PC{constructor(t){this.stack=[],this.textEncoder=t!=null?t:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let t=0;for(let i=0;i<this.chunks.length;i++)t+=this.chunks[i].length;let e=new Uint8Array(t),r=0;for(let i=0;i<this.chunks.length;i++)e.set(this.chunks[i],r),r+=this.chunks[i].length;return this.chunks=[],e}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let t=this.finish(),e=this.stack.pop();if(!e)throw new Error("invalid state, fork stack empty");return this.chunks=e.chunks,this.buf=e.buf,this.uint32(t.byteLength),this.raw(t)}tag(t,e){return this.uint32((t<<3|e)>>>0)}raw(t){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(t),this}uint32(t){for(il(t);t>127;)this.buf.push(t&127|128),t=t>>>7;return this.buf.push(t),this}int32(t){return To(t),Af(t,this.buf),this}bool(t){return this.buf.push(t?1:0),this}bytes(t){return this.uint32(t.byteLength),this.raw(t)}string(t){let e=this.textEncoder.encode(t);return this.uint32(e.byteLength),this.raw(e)}float(t){Uh(t);let e=new Uint8Array(4);return new DataView(e.buffer).setFloat32(0,t,!0),this.raw(e)}double(t){let e=new Uint8Array(8);return new DataView(e.buffer).setFloat64(0,t,!0),this.raw(e)}fixed32(t){il(t);let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),this.raw(e)}sfixed32(t){To(t);let e=new Uint8Array(4);return new DataView(e.buffer).setInt32(0,t,!0),this.raw(e)}sint32(t){return To(t),t=(t<<1^t>>31)>>>0,Af(t,this.buf),this}sfixed64(t){let e=new Uint8Array(8),r=new DataView(e.buffer),i=Ee.from(t);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(e)}fixed64(t){let e=new Uint8Array(8),r=new DataView(e.buffer),i=mt.from(t);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(e)}int64(t){let e=Ee.from(t);return xh(e.lo,e.hi,this.buf),this}sint64(t){let e=Ee.from(t),r=e.hi>>31,i=e.lo<<1^r,n=(e.hi<<1|e.lo>>>31)^r;return xh(i,n,this.buf),this}uint64(t){let e=mt.from(t);return xh(e.lo,e.hi,this.buf),this}}const Vf={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},xf={ignoreUnknownFields:!1};function kC(s){return s?Object.assign(Object.assign({},xf),s):xf}function _C(s){return s?Object.assign(Object.assign({},Vf),s):Vf}const $f=Symbol.for("protobuf-ts/message-type");function Uf(s){let t=!1;const e=[];for(let r=0;r<s.length;r++){let i=s.charAt(r);i=="_"?t=!0:/\d/.test(i)?(e.push(i),t=!0):t?(e.push(i.toUpperCase()),t=!1):r==0?e.push(i.toLowerCase()):e.push(i)}return e.join("")}var O;(function(s){s[s.DOUBLE=1]="DOUBLE",s[s.FLOAT=2]="FLOAT",s[s.INT64=3]="INT64",s[s.UINT64=4]="UINT64",s[s.INT32=5]="INT32",s[s.FIXED64=6]="FIXED64",s[s.FIXED32=7]="FIXED32",s[s.BOOL=8]="BOOL",s[s.STRING=9]="STRING",s[s.BYTES=12]="BYTES",s[s.UINT32=13]="UINT32",s[s.SFIXED32=15]="SFIXED32",s[s.SFIXED64=16]="SFIXED64",s[s.SINT32=17]="SINT32",s[s.SINT64=18]="SINT64"})(O||(O={}));var Ds;(function(s){s[s.BIGINT=0]="BIGINT",s[s.STRING=1]="STRING",s[s.NUMBER=2]="NUMBER"})(Ds||(Ds={}));var nl;(function(s){s[s.NO=0]="NO",s[s.PACKED=1]="PACKED",s[s.UNPACKED=2]="UNPACKED"})(nl||(nl={}));function CC(s){var t,e,r,i;return s.localName=(t=s.localName)!==null&&t!==void 0?t:Uf(s.name),s.jsonName=(e=s.jsonName)!==null&&e!==void 0?e:Uf(s.name),s.repeat=(r=s.repeat)!==null&&r!==void 0?r:nl.NO,s.opt=(i=s.opt)!==null&&i!==void 0?i:s.repeat||s.oneof?!1:s.kind=="message",s}function RC(s){if(typeof s!="object"||s===null||!s.hasOwnProperty("oneofKind"))return!1;switch(typeof s.oneofKind){case"string":return s[s.oneofKind]===void 0?!1:Object.keys(s).length==2;case"undefined":return Object.keys(s).length==1;default:return!1}}class IC{constructor(t){var e;this.fields=(e=t.fields)!==null&&e!==void 0?e:[]}prepare(){if(this.data)return;const t=[],e=[],r=[];for(let i of this.fields)if(i.oneof)r.includes(i.oneof)||(r.push(i.oneof),t.push(i.oneof),e.push(i.oneof));else switch(e.push(i.localName),i.kind){case"scalar":case"enum":(!i.opt||i.repeat)&&t.push(i.localName);break;case"message":i.repeat&&t.push(i.localName);break;case"map":t.push(i.localName);break}this.data={req:t,known:e,oneofs:Object.values(r)}}is(t,e,r=!1){if(e<0)return!0;if(t==null||typeof t!="object")return!1;this.prepare();let i=Object.keys(t),n=this.data;if(i.length<n.req.length||n.req.some(o=>!i.includes(o))||!r&&i.some(o=>!n.known.includes(o)))return!1;if(e<1)return!0;for(const o of n.oneofs){const c=t[o];if(!RC(c))return!1;if(c.oneofKind===void 0)continue;const d=this.fields.find(l=>l.localName===c.oneofKind);if(!d||!this.field(c[c.oneofKind],d,r,e))return!1}for(const o of this.fields)if(o.oneof===void 0&&!this.field(t[o.localName],o,r,e))return!1;return!0}field(t,e,r,i){let n=e.repeat;switch(e.kind){case"scalar":return t===void 0?e.opt:n?this.scalars(t,e.T,i,e.L):this.scalar(t,e.T,e.L);case"enum":return t===void 0?e.opt:n?this.scalars(t,O.INT32,i):this.scalar(t,O.INT32);case"message":return t===void 0?!0:n?this.messages(t,e.T(),r,i):this.message(t,e.T(),r,i);case"map":if(typeof t!="object"||t===null)return!1;if(i<2)return!0;if(!this.mapKeys(t,e.K,i))return!1;switch(e.V.kind){case"scalar":return this.scalars(Object.values(t),e.V.T,i,e.V.L);case"enum":return this.scalars(Object.values(t),O.INT32,i);case"message":return this.messages(Object.values(t),e.V.T(),r,i)}break}return!0}message(t,e,r,i){return r?e.isAssignable(t,i):e.is(t,i)}messages(t,e,r,i){if(!Array.isArray(t))return!1;if(i<2)return!0;if(r){for(let n=0;n<t.length&&n<i;n++)if(!e.isAssignable(t[n],i-1))return!1}else for(let n=0;n<t.length&&n<i;n++)if(!e.is(t[n],i-1))return!1;return!0}scalar(t,e,r){let i=typeof t;switch(e){case O.UINT64:case O.FIXED64:case O.INT64:case O.SFIXED64:case O.SINT64:switch(r){case Ds.BIGINT:return i=="bigint";case Ds.NUMBER:return i=="number"&&!isNaN(t);default:return i=="string"}case O.BOOL:return i=="boolean";case O.STRING:return i=="string";case O.BYTES:return t instanceof Uint8Array;case O.DOUBLE:case O.FLOAT:return i=="number"&&!isNaN(t);default:return i=="number"&&Number.isInteger(t)}}scalars(t,e,r,i){if(!Array.isArray(t))return!1;if(r<2)return!0;if(Array.isArray(t)){for(let n=0;n<t.length&&n<r;n++)if(!this.scalar(t[n],e,i))return!1}return!0}mapKeys(t,e,r){let i=Object.keys(t);switch(e){case O.INT32:case O.FIXED32:case O.SFIXED32:case O.SINT32:case O.UINT32:return this.scalars(i.slice(0,r).map(n=>parseInt(n)),e,r);case O.BOOL:return this.scalars(i.slice(0,r).map(n=>n=="true"?!0:n=="false"?!1:n),e,r);default:return this.scalars(i,e,r,Ds.STRING)}}}function Ts(s,t){switch(t){case Ds.BIGINT:return s.toBigInt();case Ds.NUMBER:return s.toNumber();default:return s.toString()}}class AC{constructor(t){this.info=t}prepare(){var t;if(this.fMap===void 0){this.fMap={};const e=(t=this.info.fields)!==null&&t!==void 0?t:[];for(const r of e)this.fMap[r.name]=r,this.fMap[r.jsonName]=r,this.fMap[r.localName]=r}}assert(t,e,r){if(!t){let i=Vh(r);throw(i=="number"||i=="boolean")&&(i=r.toString()),new Error(`Cannot parse JSON ${i} for ${this.info.typeName}#${e}`)}}read(t,e,r){this.prepare();const i=[];for(const[n,o]of Object.entries(t)){const c=this.fMap[n];if(!c){if(!r.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${n}`);continue}const d=c.localName;let l;if(c.oneof){if(o===null&&(c.kind!=="enum"||c.T()[0]!=="google.protobuf.NullValue"))continue;if(i.includes(c.oneof))throw new Error(`Multiple members of the oneof group "${c.oneof}" of ${this.info.typeName} are present in JSON.`);i.push(c.oneof),l=e[c.oneof]={oneofKind:d}}else l=e;if(c.kind=="map"){if(o===null)continue;this.assert(lC(o),c.name,o);const u=l[d];for(const[h,g]of Object.entries(o)){this.assert(g!==null,c.name+" map value",null);let v;switch(c.V.kind){case"message":v=c.V.T().internalJsonRead(g,r);break;case"enum":if(v=this.enum(c.V.T(),g,c.name,r.ignoreUnknownFields),v===!1)continue;break;case"scalar":v=this.scalar(g,c.V.T,c.V.L,c.name);break}this.assert(v!==void 0,c.name+" map value",g);let y=h;c.K==O.BOOL&&(y=y=="true"?!0:y=="false"?!1:y),y=this.scalar(y,c.K,Ds.STRING,c.name).toString(),u[y]=v}}else if(c.repeat){if(o===null)continue;this.assert(Array.isArray(o),c.name,o);const u=l[d];for(const h of o){this.assert(h!==null,c.name,null);let g;switch(c.kind){case"message":g=c.T().internalJsonRead(h,r);break;case"enum":if(g=this.enum(c.T(),h,c.name,r.ignoreUnknownFields),g===!1)continue;break;case"scalar":g=this.scalar(h,c.T,c.L,c.name);break}this.assert(g!==void 0,c.name,o),u.push(g)}}else switch(c.kind){case"message":if(o===null&&c.T().typeName!="google.protobuf.Value"){this.assert(c.oneof===void 0,c.name+" (oneof member)",null);continue}l[d]=c.T().internalJsonRead(o,r,l[d]);break;case"enum":if(o===null)continue;let u=this.enum(c.T(),o,c.name,r.ignoreUnknownFields);if(u===!1)continue;l[d]=u;break;case"scalar":if(o===null)continue;l[d]=this.scalar(o,c.T,c.L,c.name);break}}}enum(t,e,r,i){if(t[0]=="google.protobuf.NullValue"&&ne(e===null||e==="NULL_VALUE",`Unable to parse field ${this.info.typeName}#${r}, enum ${t[0]} only accepts null.`),e===null)return 0;switch(typeof e){case"number":return ne(Number.isInteger(e),`Unable to parse field ${this.info.typeName}#${r}, enum can only be integral number, got ${e}.`),e;case"string":let n=e;t[2]&&e.substring(0,t[2].length)===t[2]&&(n=e.substring(t[2].length));let o=t[1][n];return typeof o=="undefined"&&i?!1:(ne(typeof o=="number",`Unable to parse field ${this.info.typeName}#${r}, enum ${t[0]} has no value for "${e}".`),o)}ne(!1,`Unable to parse field ${this.info.typeName}#${r}, cannot parse enum value from ${typeof e}".`)}scalar(t,e,r,i){let n;try{switch(e){case O.DOUBLE:case O.FLOAT:if(t===null)return 0;if(t==="NaN")return Number.NaN;if(t==="Infinity")return Number.POSITIVE_INFINITY;if(t==="-Infinity")return Number.NEGATIVE_INFINITY;if(t===""){n="empty string";break}if(typeof t=="string"&&t.trim().length!==t.length){n="extra whitespace";break}if(typeof t!="string"&&typeof t!="number")break;let o=Number(t);if(Number.isNaN(o)){n="not a number";break}if(!Number.isFinite(o)){n="too large or small";break}return e==O.FLOAT&&Uh(o),o;case O.INT32:case O.FIXED32:case O.SFIXED32:case O.SINT32:case O.UINT32:if(t===null)return 0;let c;if(typeof t=="number"?c=t:t===""?n="empty string":typeof t=="string"&&(t.trim().length!==t.length?n="extra whitespace":c=Number(t)),c===void 0)break;return e==O.UINT32?il(c):To(c),c;case O.INT64:case O.SFIXED64:case O.SINT64:if(t===null)return Ts(Ee.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return Ts(Ee.from(t),r);case O.FIXED64:case O.UINT64:if(t===null)return Ts(mt.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return Ts(mt.from(t),r);case O.BOOL:if(t===null)return!1;if(typeof t!="boolean")break;return t;case O.STRING:if(t===null)return"";if(typeof t!="string"){n="extra whitespace";break}try{encodeURIComponent(t)}catch(d){d="invalid UTF8";break}return t;case O.BYTES:if(t===null||t==="")return new Uint8Array(0);if(typeof t!="string")break;return uC(t)}}catch(o){n=o.message}this.assert(!1,i+(n?" - "+n:""),t)}}class MC{constructor(t){var e;this.fields=(e=t.fields)!==null&&e!==void 0?e:[]}write(t,e){const r={},i=t;for(const n of this.fields){if(!n.oneof){let l=this.field(n,i[n.localName],e);l!==void 0&&(r[e.useProtoFieldName?n.name:n.jsonName]=l);continue}const o=i[n.oneof];if(o.oneofKind!==n.localName)continue;const c=n.kind=="scalar"||n.kind=="enum"?Object.assign(Object.assign({},e),{emitDefaultValues:!0}):e;let d=this.field(n,o[n.localName],c);ne(d!==void 0),r[e.useProtoFieldName?n.name:n.jsonName]=d}return r}field(t,e,r){let i;if(t.kind=="map"){ne(typeof e=="object"&&e!==null);const n={};switch(t.V.kind){case"scalar":for(const[d,l]of Object.entries(e)){const u=this.scalar(t.V.T,l,t.name,!1,!0);ne(u!==void 0),n[d.toString()]=u}break;case"message":const o=t.V.T();for(const[d,l]of Object.entries(e)){const u=this.message(o,l,t.name,r);ne(u!==void 0),n[d.toString()]=u}break;case"enum":const c=t.V.T();for(const[d,l]of Object.entries(e)){ne(l===void 0||typeof l=="number");const u=this.enum(c,l,t.name,!1,!0,r.enumAsInteger);ne(u!==void 0),n[d.toString()]=u}break}(r.emitDefaultValues||Object.keys(n).length>0)&&(i=n)}else if(t.repeat){ne(Array.isArray(e));const n=[];switch(t.kind){case"scalar":for(let d=0;d<e.length;d++){const l=this.scalar(t.T,e[d],t.name,t.opt,!0);ne(l!==void 0),n.push(l)}break;case"enum":const o=t.T();for(let d=0;d<e.length;d++){ne(e[d]===void 0||typeof e[d]=="number");const l=this.enum(o,e[d],t.name,t.opt,!0,r.enumAsInteger);ne(l!==void 0),n.push(l)}break;case"message":const c=t.T();for(let d=0;d<e.length;d++){const l=this.message(c,e[d],t.name,r);ne(l!==void 0),n.push(l)}break}(r.emitDefaultValues||n.length>0||r.emitDefaultValues)&&(i=n)}else switch(t.kind){case"scalar":i=this.scalar(t.T,e,t.name,t.opt,r.emitDefaultValues);break;case"enum":i=this.enum(t.T(),e,t.name,t.opt,r.emitDefaultValues,r.enumAsInteger);break;case"message":i=this.message(t.T(),e,t.name,r);break}return i}enum(t,e,r,i,n,o){if(t[0]=="google.protobuf.NullValue")return!n&&!i?void 0:null;if(e===void 0){ne(i);return}if(!(e===0&&!n&&!i))return ne(typeof e=="number"),ne(Number.isInteger(e)),o||!t[1].hasOwnProperty(e)?e:t[2]?t[2]+t[1][e]:t[1][e]}message(t,e,r,i){return e===void 0?i.emitDefaultValues?null:void 0:t.internalJsonWrite(e,i)}scalar(t,e,r,i,n){if(e===void 0){ne(i);return}const o=n||i;switch(t){case O.INT32:case O.SFIXED32:case O.SINT32:return e===0?o?0:void 0:(To(e),e);case O.FIXED32:case O.UINT32:return e===0?o?0:void 0:(il(e),e);case O.FLOAT:Uh(e);case O.DOUBLE:return e===0?o?0:void 0:(ne(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e);case O.STRING:return e===""?o?"":void 0:(ne(typeof e=="string"),e);case O.BOOL:return e===!1?o?!1:void 0:(ne(typeof e=="boolean"),e);case O.UINT64:case O.FIXED64:ne(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let c=mt.from(e);return c.isZero()&&!o?void 0:c.toString();case O.INT64:case O.SFIXED64:case O.SINT64:ne(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let d=Ee.from(e);return d.isZero()&&!o?void 0:d.toString();case O.BYTES:return ne(e instanceof Uint8Array),e.byteLength?hC(e):o?"":void 0}}}function Bh(s,t=Ds.STRING){switch(s){case O.BOOL:return!1;case O.UINT64:case O.FIXED64:return Ts(mt.ZERO,t);case O.INT64:case O.SFIXED64:case O.SINT64:return Ts(Ee.ZERO,t);case O.DOUBLE:case O.FLOAT:return 0;case O.BYTES:return new Uint8Array(0);case O.STRING:return"";default:return 0}}class OC{constructor(t){this.info=t}prepare(){var t;if(!this.fieldNoToField){const e=(t=this.info.fields)!==null&&t!==void 0?t:[];this.fieldNoToField=new Map(e.map(r=>[r.no,r]))}}read(t,e,r,i){this.prepare();const n=i===void 0?t.len:t.pos+i;for(;t.pos<n;){const[o,c]=t.tag(),d=this.fieldNoToField.get(o);if(!d){let g=r.readUnknownField;if(g=="throw")throw new Error(`Unknown field ${o} (wire type ${c}) for ${this.info.typeName}`);let v=t.skip(c);g!==!1&&(g===!0?el.onRead:g)(this.info.typeName,e,o,c,v);continue}let l=e,u=d.repeat,h=d.localName;switch(d.oneof&&(l=l[d.oneof],l.oneofKind!==h&&(l=e[d.oneof]={oneofKind:h})),d.kind){case"scalar":case"enum":let g=d.kind=="enum"?O.INT32:d.T,v=d.kind=="scalar"?d.L:void 0;if(u){let I=l[h];if(c==$e.LengthDelimited&&g!=O.STRING&&g!=O.BYTES){let D=t.uint32()+t.pos;for(;t.pos<D;)I.push(this.scalar(t,g,v))}else I.push(this.scalar(t,g,v))}else l[h]=this.scalar(t,g,v);break;case"message":if(u){let I=l[h],D=d.T().internalBinaryRead(t,t.uint32(),r);I.push(D)}else l[h]=d.T().internalBinaryRead(t,t.uint32(),r,l[h]);break;case"map":let[y,k]=this.mapEntry(d,t,r);l[h][y]=k;break}}}mapEntry(t,e,r){let i=e.uint32(),n=e.pos+i,o,c;for(;e.pos<n;){let[d,l]=e.tag();switch(d){case 1:t.K==O.BOOL?o=e.bool().toString():o=this.scalar(e,t.K,Ds.STRING);break;case 2:switch(t.V.kind){case"scalar":c=this.scalar(e,t.V.T,t.V.L);break;case"enum":c=e.int32();break;case"message":c=t.V.T().internalBinaryRead(e,e.uint32(),r);break}break;default:throw new Error(`Unknown field ${d} (wire type ${l}) in map entry for ${this.info.typeName}#${t.name}`)}}if(o===void 0){let d=Bh(t.K);o=t.K==O.BOOL?d.toString():d}if(c===void 0)switch(t.V.kind){case"scalar":c=Bh(t.V.T,t.V.L);break;case"enum":c=0;break;case"message":c=t.V.T().create();break}return[o,c]}scalar(t,e,r){switch(e){case O.INT32:return t.int32();case O.STRING:return t.string();case O.BOOL:return t.bool();case O.DOUBLE:return t.double();case O.FLOAT:return t.float();case O.INT64:return Ts(t.int64(),r);case O.UINT64:return Ts(t.uint64(),r);case O.FIXED64:return Ts(t.fixed64(),r);case O.FIXED32:return t.fixed32();case O.BYTES:return t.bytes();case O.UINT32:return t.uint32();case O.SFIXED32:return t.sfixed32();case O.SFIXED64:return Ts(t.sfixed64(),r);case O.SINT32:return t.sint32();case O.SINT64:return Ts(t.sint64(),r)}}}class DC{constructor(t){this.info=t}prepare(){if(!this.fields){const t=this.info.fields?this.info.fields.concat():[];this.fields=t.sort((e,r)=>e.no-r.no)}}write(t,e,r){this.prepare();for(const n of this.fields){let o,c,d=n.repeat,l=n.localName;if(n.oneof){const u=t[n.oneof];if(u.oneofKind!==l)continue;o=u[l],c=!0}else o=t[l],c=!1;switch(n.kind){case"scalar":case"enum":let u=n.kind=="enum"?O.INT32:n.T;if(d)if(ne(Array.isArray(o)),d==nl.PACKED)this.packed(e,u,n.no,o);else for(const h of o)this.scalar(e,u,n.no,h,!0);else o===void 0?ne(n.opt):this.scalar(e,u,n.no,o,c||n.opt);break;case"message":if(d){ne(Array.isArray(o));for(const h of o)this.message(e,r,n.T(),n.no,h)}else this.message(e,r,n.T(),n.no,o);break;case"map":ne(typeof o=="object"&&o!==null);for(const[h,g]of Object.entries(o))this.mapEntry(e,r,n,h,g);break}}let i=r.writeUnknownFields;i!==!1&&(i===!0?el.onWrite:i)(this.info.typeName,t,e)}mapEntry(t,e,r,i,n){t.tag(r.no,$e.LengthDelimited),t.fork();let o=i;switch(r.K){case O.INT32:case O.FIXED32:case O.UINT32:case O.SFIXED32:case O.SINT32:o=Number.parseInt(i);break;case O.BOOL:ne(i=="true"||i=="false"),o=i=="true";break}switch(this.scalar(t,r.K,1,o,!0),r.V.kind){case"scalar":this.scalar(t,r.V.T,2,n,!0);break;case"enum":this.scalar(t,O.INT32,2,n,!0);break;case"message":this.message(t,e,r.V.T(),2,n);break}t.join()}message(t,e,r,i,n){n!==void 0&&(r.internalBinaryWrite(n,t.tag(i,$e.LengthDelimited).fork(),e),t.join())}scalar(t,e,r,i,n){let[o,c,d]=this.scalarInfo(e,i);(!d||n)&&(t.tag(r,o),t[c](i))}packed(t,e,r,i){if(!i.length)return;ne(e!==O.BYTES&&e!==O.STRING),t.tag(r,$e.LengthDelimited),t.fork();let[,n]=this.scalarInfo(e);for(let o=0;o<i.length;o++)t[n](i[o]);t.join()}scalarInfo(t,e){let r=$e.Varint,i,n=e===void 0,o=e===0;switch(t){case O.INT32:i="int32";break;case O.STRING:o=n||!e.length,r=$e.LengthDelimited,i="string";break;case O.BOOL:o=e===!1,i="bool";break;case O.UINT32:i="uint32";break;case O.DOUBLE:r=$e.Bit64,i="double";break;case O.FLOAT:r=$e.Bit32,i="float";break;case O.INT64:o=n||Ee.from(e).isZero(),i="int64";break;case O.UINT64:o=n||mt.from(e).isZero(),i="uint64";break;case O.FIXED64:o=n||mt.from(e).isZero(),r=$e.Bit64,i="fixed64";break;case O.BYTES:o=n||!e.byteLength,r=$e.LengthDelimited,i="bytes";break;case O.FIXED32:r=$e.Bit32,i="fixed32";break;case O.SFIXED32:r=$e.Bit32,i="sfixed32";break;case O.SFIXED64:o=n||Ee.from(e).isZero(),r=$e.Bit64,i="sfixed64";break;case O.SINT32:i="sint32";break;case O.SINT64:o=n||Ee.from(e).isZero(),i="sint64";break}return[r,i,n||o]}}function NC(s){const t=s.messagePrototype?Object.create(s.messagePrototype):Object.defineProperty({},$f,{value:s});for(let e of s.fields){let r=e.localName;if(!e.opt)if(e.oneof)t[e.oneof]={oneofKind:void 0};else if(e.repeat)t[r]=[];else switch(e.kind){case"scalar":t[r]=Bh(e.T,e.L);break;case"enum":t[r]=0;break;case"map":t[r]={};break}}return t}function Fh(s,t,e){let r,i=e,n;for(let o of s.fields){let c=o.localName;if(o.oneof){const d=i[o.oneof];if((d==null?void 0:d.oneofKind)==null)continue;if(r=d[c],n=t[o.oneof],n.oneofKind=d.oneofKind,r==null){delete n[c];continue}}else if(r=i[c],n=t,r==null)continue;switch(o.repeat&&(n[c].length=r.length),o.kind){case"scalar":case"enum":if(o.repeat)for(let l=0;l<r.length;l++)n[c][l]=r[l];else n[c]=r;break;case"message":let d=o.T();if(o.repeat)for(let l=0;l<r.length;l++)n[c][l]=d.create(r[l]);else n[c]===void 0?n[c]=d.create(r):d.mergePartial(n[c],r);break;case"map":switch(o.V.kind){case"scalar":case"enum":Object.assign(n[c],r);break;case"message":let l=o.V.T();for(let u of Object.keys(r))n[c][u]=l.create(r[u]);break}break}}}function LC(s,t,e){if(t===e)return!0;if(!t||!e)return!1;for(let r of s.fields){let i=r.localName,n=r.oneof?t[r.oneof][i]:t[i],o=r.oneof?e[r.oneof][i]:e[i];switch(r.kind){case"enum":case"scalar":let c=r.kind=="enum"?O.INT32:r.T;if(!(r.repeat?Ff(c,n,o):Bf(c,n,o)))return!1;break;case"map":if(!(r.V.kind=="message"?Hf(r.V.T(),al(n),al(o)):Ff(r.V.kind=="enum"?O.INT32:r.V.T,al(n),al(o))))return!1;break;case"message":let d=r.T();if(!(r.repeat?Hf(d,n,o):d.equals(n,o)))return!1;break}}return!0}const al=Object.values;function Bf(s,t,e){if(t===e)return!0;if(s!==O.BYTES)return!1;let r=t,i=e;if(r.length!==i.length)return!1;for(let n=0;n<r.length;n++)if(r[n]!=i[n])return!1;return!0}function Ff(s,t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(!Bf(s,t[r],e[r]))return!1;return!0}function Hf(s,t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(!s.equals(t[r],e[r]))return!1;return!0}const qf=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})),VC=qf[$f]={};class T{constructor(t,e,r){this.defaultCheckDepth=16,this.typeName=t,this.fields=e.map(CC),this.options=r!=null?r:{},VC.value=this,this.messagePrototype=Object.create(null,qf),this.refTypeCheck=new IC(this),this.refJsonReader=new AC(this),this.refJsonWriter=new MC(this),this.refBinReader=new OC(this),this.refBinWriter=new DC(this)}create(t){let e=NC(this);return t!==void 0&&Fh(this,e,t),e}clone(t){let e=this.create();return Fh(this,e,t),e}equals(t,e){return LC(this,t,e)}is(t,e=this.defaultCheckDepth){return this.refTypeCheck.is(t,e,!1)}isAssignable(t,e=this.defaultCheckDepth){return this.refTypeCheck.is(t,e,!0)}mergePartial(t,e){Fh(this,t,e)}fromBinary(t,e){let r=fC(e);return this.internalBinaryRead(r.readerFactory(t),t.byteLength,r)}fromJson(t,e){return this.internalJsonRead(t,kC(e))}fromJsonString(t,e){let r=JSON.parse(t);return this.fromJson(r,e)}toJson(t,e){return this.internalJsonWrite(t,_C(e))}toJsonString(t,e){var r;let i=this.toJson(t,e);return JSON.stringify(i,null,(r=e==null?void 0:e.prettySpaces)!==null&&r!==void 0?r:0)}toBinary(t,e){let r=wC(e);return this.internalBinaryWrite(t,r.writerFactory(),r).finish()}internalJsonRead(t,e,r){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let i=r!=null?r:this.create();return this.refJsonReader.read(t,i,e),i}throw new Error(`Unable to parse message ${this.typeName} from JSON ${Vh(t)}.`)}internalJsonWrite(t,e){return this.refJsonWriter.write(t,e)}internalBinaryWrite(t,e,r){return this.refBinWriter.write(t,e,r),e}internalBinaryRead(t,e,r,i){let n=i!=null?i:this.create();return this.refBinReader.read(t,n,r,e),n}}var nr;(function(s){s[s.PUBLISHER=0]="PUBLISHER",s[s.SUBSCRIBER=1]="SUBSCRIBER"})(nr||(nr={}));var Ns;(function(s){s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO"})(Ns||(Ns={}));class xC extends T{constructor(){super("media.Codec",[{no:1,name:"channels",kind:"scalar",opt:!0,T:5},{no:2,name:"clock_rate",kind:"scalar",T:5},{no:3,name:"mime_type",kind:"scalar",T:9},{no:4,name:"sdp_fmtp_line",kind:"scalar",opt:!0,T:9},{no:5,name:"payload_type",kind:"scalar",opt:!0,T:13}])}}const jf=new xC;class $C extends T{constructor(){super("media.HeaderExtension",[{no:1,name:"direction",kind:"scalar",opt:!0,T:9},{no:2,name:"uri",kind:"scalar",T:9}])}}const UC=new $C;class BC extends T{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new BC;class FC extends T{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",nr]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const ys=new FC;class HC extends T{constructor(){super("media.ProducerPayload",[{no:1,name:"kind",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8},{no:4,name:"msid",kind:"scalar",T:9},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"mime_type",kind:"scalar",opt:!0,T:9}])}}const qC=new HC;class jC extends T{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:()=>ys},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8},{no:5,name:"producers",kind:"message",repeat:1,T:()=>qC}])}}const GC=new jC;class WC extends T{constructor(){super("media.AudioActivityRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"energy",kind:"scalar",T:5},{no:3,name:"silent",kind:"scalar",T:8}])}}const JC=new WC;class KC extends T{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ys},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:4,name:"producer_ids",kind:"scalar",repeat:2,T:9}])}}const Gf=new KC;class zC extends T{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ys}])}}const YC=new zC;class QC extends T{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ys}])}}new QC;class XC extends T{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 ZC=new XC;class eR extends T{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 tR=new eR;class sR extends T{constructor(){super("media.ProducerEntry",[{no:1,name:"producing_transport_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9}])}}new sR;class rR extends T{constructor(){super("media.ConsumerEntry",[{no:1,name:"consuming_transport_id",kind:"scalar",T:9},{no:2,name:"consumer_id",kind:"scalar",T:9}])}}new rR;class iR extends T{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",Ns]},{no:3,name:"pause",kind:"scalar",T:8},{no:4,name:"screen_share",kind:"scalar",T:8},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9},{no:8,name:"codec",kind:"message",T:()=>jf}])}}const yo=new iR;class nR extends T{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>yo},{no:3,name:"producer_track",kind:"message",T:()=>tR},{no:4,name:"error_code",kind:"scalar",opt:!0,T:9}])}}const aR=new nR;class oR extends T{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>aR}}])}}const Wf=new oR;class cR extends T{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>zf},{no:2,name:"receiver",kind:"message",T:()=>zf}])}}const Jf=new cR;class dR extends T{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>jf},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>UC}])}}const Kf=new dR;class lR extends T{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>Kf},{no:2,name:"video",kind:"message",T:()=>Kf}])}}const zf=new lR;class uR extends T{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 hR=new uR;class pR extends T{constructor(){super("media.Simulcast",[{no:1,name:"preferred_rid",kind:"scalar",opt:!0,T:9},{no:2,name:"priority_ordering",kind:"scalar",opt:!0,T:9},{no:3,name:"rid_not_available",kind:"scalar",opt:!0,T:9}])}}const Yf=new pR;class mR extends T{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 gR=new mR;class fR extends T{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:()=>gR},{no:9,name:"capabilities",kind:"message",T:()=>Jf}])}}const vR=new fR;class SR extends T{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const TR=new SR;class yR extends T{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const ER=new yR;class bR extends T{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 bR;class wR extends T{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:()=>hR},{no:5,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:6,name:"simulcast",kind:"message",T:()=>Yf}])}}const PR=new wR;class kR extends T{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>PR},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const _R=new kR;class CR extends T{constructor(){super("media.edge.UpdateConsumerSimulcastConfigRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"simulcast",kind:"message",T:()=>Yf},{no:3,name:"producing_transport_id",kind:"scalar",T:9},{no:4,name:"mid",kind:"scalar",T:9}])}}const RR=new CR;class IR extends T{constructor(){super("media.edge.UpdateConsumersSimulcastConfigRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>RR},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const AR=new IR;class MR extends T{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:()=>ys},{no:5,name:"msid",kind:"scalar",T:9},{no:6,name:"app_data",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9},{no:8,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const OR=new MR;class DR extends T{constructor(){super("media.edge.SelectedPeersRequest",[])}}new DR;class NR extends T{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const LR=new NR;class VR extends T{constructor(){super("media.edge.ProducerToggleRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const ol=new VR;class xR extends T{constructor(){super("media.edge.ConsumerToggleRequest",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}new xR;class $R extends T{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ys},{no:3,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const UR=new $R;class BR extends T{constructor(){super("media.edge.ConsumerCloseRequest",[{no:1,name:"consumer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"description",kind:"message",T:()=>ys},{no:3,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const FR=new BR;class HR extends T{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new HR;class qR extends T{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const Qf=new qR;class jR extends T{constructor(){super("media.edge.PeerDisplayNameEditRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}const GR=new jR;class WR extends T{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 JR=new WR;class KR extends T{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 zR=new KR;class YR extends T{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 QR=new YR;class XR extends T{constructor(){super("media.edge.ErrorResponse",[{no:1,name:"error_message",kind:"scalar",T:9},{no:2,name:"event_id",kind:"scalar",T:5}])}}const ZR=new XR;class eI extends T{constructor(){super("media.edge.EmptyResponse",[])}}new eI;class tI extends T{constructor(){super("media.edge.RoomParticipants",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"producer_states",kind:"message",repeat:1,T:()=>yo},{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:()=>Jf}])}}const Xf=new tI;class sI extends T{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 Hh=new sI;class rI extends T{constructor(){super("media.edge.SelectedPeersDiffEntry",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"priority",kind:"scalar",T:5}])}}const iI=new rI;class nI extends T{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>iI}])}}const Zf=new nI;class aI extends T{constructor(){super("media.edge.PeerJoinResponse",[])}}new aI;class oI extends T{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>QR},{no:2,name:"participants",kind:"message",repeat:1,T:()=>Xf},{no:3,name:"selected_peers",kind:"message",T:()=>Hh},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const qh=new oI;class cI extends T{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}new cI;class dI extends T{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Wf}])}}new dI;class lI extends T{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Wf},{no:3,name:"description",kind:"message",T:()=>ys}])}}const uI=new lI;class hI extends T{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:()=>ys}])}}const pI=new hI;class mI extends T{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>ZC}])}}new mI;class gI extends T{constructor(){super("media.edge.ActiveSpeakerResponse",[{no:1,name:"responsepeer_id",kind:"scalar",T:9},{no:2,name:"volume",kind:"scalar",T:5}])}}new gI;class fI extends T{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new fI;class vI extends T{constructor(){super("media.edge.ProducerToggleResponse",[])}}new vI;class SI extends T{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new SI;class TI extends T{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>ys}])}}const yI=new TI;class EI extends T{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>ys}])}}const bI=new EI;class wI extends T{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new wI;class PI extends T{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new PI;class kI extends T{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new kI;class _I extends T{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const CI=new _I;class RI extends T{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const II=new RI;class AI extends T{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const MI=new AI;class OI extends T{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>Xf},{no:2,name:"producer_handover_from_peer_id",kind:"scalar",opt:!0,T:9}])}}const ev=new OI;class DI extends T{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const tv=new DI;class NI extends T{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>tv},{no:3,name:"screenshare",kind:"message",T:()=>tv}])}}const LI=new NI;class VI extends T{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>Gf},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>LI}])}}new VI;class xI extends T{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>yo},{no:3,name:"producer_handover_from_peer_id",kind:"scalar",opt:!0,T:9}])}}const $I=new xI;class UI extends T{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>yo},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const sv=new UI;class BI extends T{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>yo}])}}const FI=new BI;class HI extends T{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const jh=new HI;class qI extends T{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const rv=new qI;class jI extends T{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new jI;class GI extends T{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new GI;class WI extends T{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new WI;class JI extends T{constructor(){super("media.edge.PeerDisplayNameEditBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}new JI;class KI extends T{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new KI;class zI extends T{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new zI;class YI extends T{constructor(){super("socket.ai.TranscriptSpeaker",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"participant_id",kind:"scalar",T:9},{no:3,name:"custom_participant_id",kind:"scalar",T:9},{no:4,name:"display_name",kind:"scalar",T:9}])}}const QI=new YI;class XI extends T{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},{no:4,name:"sentence",kind:"scalar",T:9},{no:5,name:"speaker",kind:"message",T:()=>QI},{no:6,name:"started_at",kind:"scalar",T:4,L:2},{no:7,name:"ended_at",kind:"scalar",T:4,L:2},{no:8,name:"confidence",kind:"scalar",T:2}])}}const Gh=new XI;class ZI extends T{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 ZI;class e0 extends T{constructor(){super("socket.api.ErrorMessage",[{no:1,name:"code",kind:"scalar",opt:!0,T:5},{no:2,name:"message",kind:"scalar",T:9}])}}const t0=new e0;var Ni;(function(s){s[s.BROWSER=0]="BROWSER",s[s.TRACK=1]="TRACK",s[s.COMPOSITE=2]="COMPOSITE"})(Ni||(Ni={}));var ar;(function(s){s[s.UNSPECIFIED=0]="UNSPECIFIED",s[s.ON_STAGE=1]="ON_STAGE",s[s.APPROVED_STAGE=2]="APPROVED_STAGE",s[s.REQUESTED_STAGE=3]="REQUESTED_STAGE",s[s.OFF_STAGE=4]="OFF_STAGE"})(ar||(ar={}));var Wh;(function(s){s[s.NONE=0]="NONE",s[s.RECORDER=1]="RECORDER",s[s.LIVESTREAMER=2]="LIVESTREAMER"})(Wh||(Wh={}));var Jh;(function(s){s[s.PEERS=0]="PEERS",s[s.ROOMS=1]="ROOMS"})(Jh||(Jh={}));var cl;(function(s){s[s.HIVE=0]="HIVE",s[s.CHAT=1]="CHAT",s[s.PING=2]="PING"})(cl||(cl={}));class s0 extends T{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 r0=new s0;class i0 extends T{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",ar,"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:()=>r0}])}}const dl=new i0;class n0 extends T{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>dl}])}}const Gn=new n0;class a0 extends T{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",ar,"STAGE_TYPE_"]}])}}const iv=new a0;class o0 extends T{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 c0=new o0;class d0 extends T{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>dl}])}}const Kh=new d0;class l0 extends T{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const nv=new l0;class u0 extends T{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:()=>p0},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const av=new u0;class h0 extends T{constructor(){super("socket.room.ActiveRecording",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",Ni]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const p0=new h0;class m0 extends T{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>av}])}}const ov=new m0;class g0 extends T{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const cv=new g0;class f0 extends T{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 f0;class v0 extends T{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>dl},{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",cl,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const S0=new v0;class T0 extends T{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>dl},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const y0=new T0;class E0 extends T{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>av}])}}const ll=new E0;class b0 extends T{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new b0;class w0 extends T{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 zh=new w0;class P0 extends T{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 k0=new P0;class _0 extends T{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:()=>k0}])}}const dv=new _0;class C0 extends T{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>dv},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>dv}])}}const R0=new C0;class I0 extends T{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const A0=new I0;class M0 extends T{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>A0}])}}const O0=new M0;class D0 extends T{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:()=>zh}])}}const N0=new D0;class L0 extends T{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>N0}])}}const V0=new L0;class x0 extends T{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 $0=new x0;class U0 extends T{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>$0}])}}const B0=new U0;class F0 extends T{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const H0=new F0;class q0 extends T{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>H0}])}}const j0=new q0;class G0 extends T{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>K0}])}}const W0=new G0;class J0 extends T{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:()=>zh}])}}const K0=new J0;class z0 extends T{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 Y0=new z0;class Q0 extends T{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:()=>Y0}])}}const X0=new Q0;class Z0 extends T{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:()=>zh}])}}const lv=new Z0;class eA extends T{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>lv}])}}new eA;class tA extends T{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 sA=new tA;class rA extends T{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>aA}])}}const iA=new rA;class nA extends T{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 aA=new nA;class oA extends T{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const uv=new oA;class cA extends T{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",Jh,"BROADCAST_TYPE_"]}])}}const Eo=new cA;class dA extends T{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const lA=new dA;class uA extends T{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const hA=new uA;class pA extends T{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 mA=new pA;class gA extends T{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>mA}])}}const hv=new gA;class fA extends T{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 pv=new fA;var Yh;(function(s){s[s.NONE=0]="NONE",s[s.SKIP=1]="SKIP",s[s.ON_PRIVILEGED_USER_ENTRY=2]="ON_PRIVILEGED_USER_ENTRY",s[s.SKIP_ON_ACCEPT=3]="SKIP_ON_ACCEPT"})(Yh||(Yh={}));var Fr;(function(s){s[s.NONE=0]="NONE",s[s.ALLOWED=1]="ALLOWED",s[s.NOT_ALLOWED=2]="NOT_ALLOWED",s[s.CAN_REQUEST=3]="CAN_REQUEST"})(Fr||(Fr={}));class vA extends T{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 SA=new vA;class TA extends T{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 yA=new TA;class EA extends T{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 bA=new EA;class wA extends T{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 PA=new wA;class kA extends T{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>bA},{no:2,name:"private",kind:"message",T:()=>PA}])}}const _A=new kA;class CA extends T{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 RA=new CA;class IA extends T{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Fr,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Fr,"STREAM_PERMISSION_TYPE_"]}])}}const Qh=new IA;class AA extends T{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>Qh},{no:2,name:"audio",kind:"message",T:()=>Qh},{no:3,name:"screenshare",kind:"message",T:()=>Qh}])}}const MA=new AA;class OA extends T{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>SA},{no:2,name:"plugins",kind:"message",T:()=>yA},{no:3,name:"chat",kind:"message",T:()=>_A},{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",Yh,"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",Wh,"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:()=>RA},{no:23,name:"media",kind:"message",T:()=>MA}])}}const Xh=new OA;class DA extends T{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const NA=new DA;class LA extends T{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 VA=new LA;class xA extends T{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>VA}])}}const $A=new xA;class UA extends T{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>Xh}])}}const mv=new UA;class BA extends T{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>mv}])}}const FA=new BA;class HA extends T{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>mv}])}}const gv=new HA;class qA extends T{constructor(){super("socket.preset.PeerUserIDMap",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9}])}}const jA=new qA;class GA extends T{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>jA},{no:2,name:"patch",kind:"message",T:()=>Xh}])}}new GA;class WA extends T{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>Xh}])}}new WA;class JA extends T{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 Hr=new JA;class KA extends T{constructor(){super("socket.chat.GetPaginatedChatMessageFilters",[{no:1,name:"pinned",kind:"scalar",oneof:"filters",T:8},{no:2,name:"user_id",kind:"scalar",oneof:"filters",T:9}])}}const zA=new KA;class YA extends T{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},{no:6,name:"filters",kind:"message",T:()=>zA}])}}const QA=new YA;class XA extends T{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Hr},{no:2,name:"next",kind:"scalar",T:8}])}}const ZA=new XA;class eM extends T{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Hr}])}}const fv=new eM;class tM extends T{constructor(){super("socket.chat.SendChatMessageToRoomRequest",[{no:1,name:"payload_type",kind:"scalar",T:5},{no:2,name:"payload",kind:"scalar",T:9}])}}const sM=new tM;class rM extends T{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>Hr}])}}const Zh=new rM;class iM extends T{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 nM=new iM;class aM extends T{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>Hr}])}}const ep=new aM;class oM extends T{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}])}}new oM;class cM extends T{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>Hr}])}}new cM;class dM extends T{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 lM=new dM;class uM extends T{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 hM=new uM;class pM extends T{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},{no:4,name:"message",kind:"message",T:()=>Hr}])}}const ul=new pM;class mM extends T{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>Hr}])}}const hl=new mM;class gM extends T{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 fM=new gM;class vM extends T{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 pl=new vM;class SM extends T{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 TM=new SM;class yM extends T{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}])}}new yM;class EM extends T{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}new EM;class bM extends T{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}])}}new bM;class wM extends T{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}])}}new wM;class PM extends T{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new PM;class kM extends T{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new kM;class _M extends T{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>Hr},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const CM=new _M;class RM extends T{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:()=>CM},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const IM=new RM;class AM extends T{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>IM}])}}new AM;class MM extends T{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 OM=new MM;class DM extends T{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>OM}])}}new DM;class NM extends T{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}new NM;class LM extends T{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}new LM;class VM extends T{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}new VM;class xM extends T{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}new xM;class $M extends T{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}])}}new $M;class UM extends T{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}])}}new UM;class BM extends T{constructor(){super("socket.plugin.PluginEventToRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}new BM;class FM extends T{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}])}}new FM;class HM extends T{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 tp=new HM;class qM extends T{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:()=>tp}])}}const jM=new qM;class GM extends T{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:()=>tp}])}}const WM=new GM;class JM extends T{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:()=>tp}])}}const KM=new JM;class zM extends T{constructor(){super("socket.plugin.PluginStoreDeleteRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9}])}}new zM;class YM extends T{constructor(){super("socket.plugin.EnablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"enabled_by",kind:"scalar",T:9}])}}const QM=new YM;class XM extends T{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>QM}])}}new XM;class ZM extends T{constructor(){super("socket.plugin.DisablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"disabled_by",kind:"scalar",T:9}])}}new ZM;class eO extends T{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 tO=new eO;class sO extends T{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:()=>tO}])}}const vv=new sO;class rO extends T{constructor(){super("socket.plugin.PluginEventResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}new rO;class iO extends T{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 Sv=new iO;class nO extends T{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const Tv=new nO;class aO extends T{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 oO=new aO;class cO extends T{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>oO}])}}const sp=new cO;class dO extends T{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const lO=new dO;class uO extends T{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const hO=new uO;class pO extends T{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const yv=new pO;class mO extends T{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:()=>fO},{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 Ev=new mO;class gO extends T{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:()=>SO}])}}const fO=new gO;class vO extends T{constructor(){super("socket.polls.PollVote",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])}}const SO=new vO;class TO extends T{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 yO=new TO;class EO extends T{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 bO=new EO;class wO extends T{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>Ev}])}}const rp=new wO;class PO extends T{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>Ev}])}}const kO=new PO;class _O extends T{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",Ni]}])}}const bv=new _O;class CO extends T{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 t=this.create(),e=Date.now();return t.seconds=Ee.from(Math.floor(e/1e3)).toBigInt(),t.nanos=e%1e3*1e6,t}toDate(t){return new Date(Ee.from(t.seconds).toNumber()*1e3+Math.ceil(t.nanos/1e6))}fromDate(t){const e=this.create(),r=t.getTime();return e.seconds=Ee.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}internalJsonWrite(t,e){let r=Ee.from(t.seconds).toNumber()*1e3;if(r<Date.parse("0001-01-01T00:00:00Z")||r>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(t.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let i="Z";if(t.nanos>0){let n=(t.nanos+1e9).toString().substring(1);n.substring(3)==="000000"?i="."+n.substring(0,3)+"Z":n.substring(6)==="000"?i="."+n.substring(0,6)+"Z":i="."+n+"Z"}return new Date(r).toISOString().replace(".000Z",i)}internalJsonRead(t,e,r){if(typeof t!="string")throw new Error("Unable to parse Timestamp from JSON "+Vh(t)+".");let i=t.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 n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(n<Date.parse("0001-01-01T00:00:00Z")||n>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 r||(r=this.create()),r.seconds=Ee.from(n/1e3).toBigInt(),r.nanos=0,i[7]&&(r.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),r}}new CO;class RO extends T{constructor(){super("common.BaseHubMessage",[{no:1,name:"event",kind:"scalar",T:5},{no:2,name:"id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9},{no:4,name:"room_id",kind:"scalar",T:9},{no:5,name:"user_id",kind:"scalar",T:9},{no:6,name:"payload",kind:"scalar",T:12},{no:7,name:"error",kind:"scalar",opt:!0,T:8},{no:8,name:"sid",kind:"scalar",opt:!0,T:9},{no:9,name:"room_object_id",kind:"scalar",opt:!0,T:9},{no:10,name:"preset",kind:"scalar",opt:!0,T:9},{no:11,name:"use_start_session",kind:"scalar",opt:!0,T:8}])}}const ip=new RO;class IO extends T{constructor(){super("common.BulkedHubMessage",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>ip}])}}new IO;class AO extends T{constructor(){super("common.CFWorkersResponse",[{no:1,name:"responses",kind:"message",repeat:1,T:()=>ip},{no:2,name:"broadcast_responses",kind:"message",repeat:1,T:()=>ip}])}}new AO;const MO=0,OO=1,DO=2,NO=3,LO=5,VO={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,updateConnectedRooms:45},xO={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,searchChannelMessages:7,pinMessage:10},$O={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},UO={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},wv={unknown:0,createWebRTCTransport:1,produce:2,consume:3,toggleProducer:4,toggleConsumer:5,closeProducer:6,closeConsumer:7,updateConsumersSimulcastConfig:8,joinRoom:16,leaveRoom:17,selectedPeer:18,globalPinPeer:19,selfJoinComplete:20,peerJoinedBroadcast:25,peerLeaveBroadcast:26,peerProducerCreateBroadcast:27,peerProducerToggleBroadcast:28,peerProducerCloseBroadcast:29,globalPeerPinBroadcast:30,recordingStartedBroadcast:31,recordingStoppedBroadcast:32,peerDisplayNameEditBroadcast:33,mediaRoomTerminationBroadcastResponse:36,selectedPeerDiff:40,renegotiateSessionDescription:50,errorResponse:60,kickPeer:90,kickAll:91,changeDisplayName:92,hostControlPeer:93,hostControlAllPeers:94,audioActivity:100},BO={getUserPresets:0,updateUserPreset:1};function bo(s,t){return Object.keys(t).reduce((e,r)=>(e[r]=(s<<16)+t[r],e),{})}function Pv(s,t){return Object.keys(s).reduce((e,r)=>(e[r]=t|s[r],e),{})}const x=bo(MO,VO),Ke=bo(OO,xO),or=bo(DO,$O),cr=bo(NO,UO),qr=Pv(wv,16777216),Es=Pv(wv,50331648),ml=bo(LO,BO);var FO=Object.defineProperty,HO=Object.getOwnPropertyDescriptor,jr=(s,t,e,r)=>{for(var i=r>1?void 0:r?HO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&FO(t,e,i),i},rs=(s=>(s[s.TEXT=0]="TEXT",s[s.IMAGE=1]="IMAGE",s[s.FILE=2]="FILE",s[s.CUSTOM=3]="CUSTOM",s))(rs||{});class dr{constructor(t,e){m(this,Wt,void 0);m(this,ca,void 0);f(this,Wt,e),f(this,ca,t)}get telemetry(){return a(this,ca).getValue("telemetry")}get logger(){return a(this,ca).getValue("logger")}getChatMessages(){return a(this,Wt).sendMessagePromise(Ke.getMessages)}async getChatMessagesPaginated(t,e,r,i){const n={timeStamp:t,size:e,from:0,reversed:r,...i&&{filters:{filters:i}}},o=await a(this,Wt).sendMessagePromise(Ke.getPaginatedMessages,QA.toBinary(n));return o.payload?ZA.fromBinary(o.payload):{messages:[],next:!1}}sendMessageToRoom(t,e){const r={payloadType:e,payload:t};a(this,Wt).sendMessage(Ke.sendMessageToRoom,sM.toBinary(r))}sendMessageToPeers(t,e,r){const i={payloadType:e,peerIds:r,payload:t};a(this,Wt).sendMessage(Ke.sendMessageToPeers,nM.toBinary(i))}sendMessage(t,e,r){if(r&&r.length>0){this.sendMessageToPeers(t,e,r);return}this.sendMessageToRoom(t,e)}async editMessage(t,e,r,i){const n={chatId:t,payloadType:r,payload:e};i!==void 0&&(n.pinned=i);const o=await a(this,Wt).sendMessagePromise(Ke.editMessage,lM.toBinary(n));return hl.fromBinary(o.payload).message}async deleteMessage(t){const e={chatId:t},r=await a(this,Wt).sendMessagePromise(Ke.deleteMessage,fM.toBinary(e));return{id:pl.fromBinary(r.payload).chatId}}async searchMessages(t,e){var i,n,o,c;const r={searchTerm:t,timeStamp:(i=e.timestamp)!=null?i:Date.now(),size:(n=e.limit)!=null?n:75,from:(o=e.offset)!=null?o:0,reversed:(c=e.reversed)!=null?c:!0};try{const d=await a(this,Wt).sendMessagePromise(Ke.searchChannelMessages,TM.toBinary(r));return fv.fromBinary(d.payload).messages}catch(d){return[]}}async setPinState(t,e){const r={chatId:t,pinned:e},i=await a(this,Wt).sendMessagePromise(Ke.pinMessage,hM.toBinary(r));return ul.fromBinary(i.payload)}on(t,e){let r,i;switch(t){case Ke.sendMessageToRoom:{r=Zh.fromBinary.bind(Zh),i=Zh.create();break}case Ke.sendMessageToPeers:{r=ep.fromBinary.bind(ep),i=ep.create();break}case Ke.editMessage:{r=hl.fromBinary.bind(hl),i=hl.create();break}case Ke.pinMessage:{r=ul.fromBinary.bind(ul),i=ul.create();break}case Ke.deleteMessage:{r=pl.fromBinary.bind(pl),i=pl.create();break}}if(!r){this.logger.warn(`ChatSocketHandler::Event ${t} is not recognized`);return}a(this,Wt).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}Wt=new WeakMap,ca=new WeakMap,jr([E.trace("SocketService.getChatMessages")],dr.prototype,"getChatMessages",1),jr([E.trace("SocketService.getChatMessagesPaginated")],dr.prototype,"getChatMessagesPaginated",1),jr([E.trace("SocketService.sendMessageToRoom")],dr.prototype,"sendMessageToRoom",1),jr([E.trace("SocketService.sendMessageToPeers")],dr.prototype,"sendMessageToPeers",1),jr([E.trace("SocketService.sendMessage")],dr.prototype,"sendMessage",1),jr([E.trace("SocketService.editMessage")],dr.prototype,"editMessage",1),jr([E.trace("SocketService.deleteMessage")],dr.prototype,"deleteMessage",1),jr([E.trace("SocketService.searchMessages")],dr.prototype,"searchMessages",1);function qO(s){return s.replace(/([-_]\w)/g,t=>t[1].toUpperCase())}function Ls(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>Ls(e));const t={};return Object.keys(s).forEach(e=>{const r=ih(e)?e:qO(e);t[r]=Ls(s[e])}),t}function jO(s){return s.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function kv(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>kv(e));const t={};return Object.keys(s).forEach(e=>{const r=ih(e)?e:jO(e);t[r]=s[e]}),t}class gl extends Error{constructor(e){const r=e instanceof Error?e.message:`Request failed with status ${e.status}`;super(r);p(this,"status");p(this,"response");p(this,"isTimeout");e instanceof Error?(this.stack=e.stack,this.isTimeout=e.name==="AbortError"):(this.status=e.status,this.response=e,this.isTimeout=!1),this.name="RequestError"}get isHttpError(){return this.status!==void 0}get isNetworkError(){return this.status===void 0&&!this.isTimeout}}class _v{constructor(t){p(this,"defaults");this.defaults={baseURL:t.baseURL,headers:{common:{}},timeout:t.timeout,retry:t.retry,retryDelay:t.retryDelay}}buildURL(t,e){const{baseURL:r}=this.defaults,i=t.startsWith("http")?t:`${r}${t.startsWith("/")?t:`/${t}`}`;if(e){const n=new URLSearchParams;return Object.entries(e).forEach(([o,c])=>{n.append(o,c)}),`${i}${i.includes("?")?"&":"?"}${n.toString()}`}return i}async request(t){var h;const e=((h=t.method)==null?void 0:h.toUpperCase())||"GET",r=this.buildURL(t.url||"",t.params),i={...this.defaults.headers.common,...t.headers};e!=="GET"&&e!=="HEAD"&&t.data&&!i["Content-Type"]&&(i["Content-Type"]="application/json");const o=i["Content-Type"]==="application/json"?JSON.stringify(t.data):t.data,c={method:e,headers:i,body:e!=="GET"&&e!=="HEAD"&&t.data?o:void 0},d=t.timeout||this.defaults.timeout,l=t.retry!==void 0?t.retry:this.defaults.retry,u=t.retryDelay||this.defaults.retryDelay;try{const g=new AbortController,v=setTimeout(()=>g.abort(),d);c.signal=g.signal;const y=await fetch(r,c);clearTimeout(v);let k=null;const I=y.headers.get("content-type");I&&I.includes("application/json")?k=await y.json():k=await y.text();const D={};y.headers.forEach((B,U)=>{D[U]=B});const N={data:k,status:y.status,statusText:y.statusText,headers:D,config:t};if(!y.ok)throw N;return N}catch(g){if(g instanceof Error&&l>0)return await new Promise(v=>setTimeout(v,u)),this.defaults.baseURL===Di.apiBase.prod?this.defaults.baseURL=Di.apiBase.prodAlternate:this.defaults.baseURL===Di.apiBase.prodAlternate&&(this.defaults.baseURL=Di.apiBase.prod),this.request({...t,retry:l-1});throw g}}async get(t,e={}){return this.request({...e,method:"GET",url:t})}async post(t,e,r={}){return this.request({...r,method:"POST",url:t,data:e})}async put(t,e,r={}){return this.request({...r,method:"PUT",url:t,data:e})}}const GO=3,WO=30,JO=8e3;class KO{constructor(t,e){p(this,"fetchClient");p(this,"requests");p(this,"roomName");p(this,"roomUUID");p(this,"authToken");p(this,"organizationId");p(this,"iceServers");p(this,"userDetails");p(this,"roomDetails");p(this,"context");this.context=t;const{timeout:r=JO,retry:i=GO,retryDelay:n=WO,baseURL:o=Di.apiBase.prod,authToken:c,cachedUserDetails:d}=e||{};this.iceServers=d==null?void 0:d.iceServers,this.userDetails=d==null?void 0:d.userDetails,this.roomDetails=d==null?void 0:d.roomDetails,this.requests=new _v({baseURL:o,timeout:r,retry:i,retryDelay:n,responseType:"json"}),this.fetchClient=new _v({baseURL:"",timeout:r,retry:i,retryDelay:n,responseType:"json"}),this.setAuthToken(c,{bearer:!0});const l=this.requests.request.bind(this.requests);this.requests.request=async u=>{var g,v,y,k,I,D;const h=t.getValue("telemetry");try{h.injectContext(this.requests.defaults.headers.common);const N=await l(u);return u.url!==h.logsEndpoint&&this.logger.debug(`XHR - Fetched ${u.method}:${u.url} with status ${N.status}`,{networkCall:{status:N.status,statusText:N.statusText,baseURL:u.baseURL||this.requests.defaults.baseURL,url:u.url,method:u.method}}),N}catch(N){if(!N)throw new C("Unknown network error occurred","0011");if(N instanceof C||N instanceof gl)throw N;((g=N.config)==null?void 0:g.url)!==h.logsEndpoint&&this.logger.error(`XHR - Fetch failed on ${u.method}:${u.url} with status ${N.status}. Retry: ${(v=N.config)==null?void 0:v.retry}`,{error:N,networkCall:{status:N.status,statusText:N.statusText,baseURL:((y=N.config)==null?void 0:y.baseURL)||this.requests.defaults.baseURL,url:(k=N.config)==null?void 0:k.url,retries:(I=N.config)==null?void 0:I.retry,method:(D=N.config)==null?void 0:D.method,isOnline:navigator.onLine?"online":"offline"}});const B=N instanceof Error&&N.message||"Network request failed";throw new C(B,"0011"),new gl(N)}}}get peerId(){return this.context.getValue("peerId")}get logger(){return this.context.getValue("logger")}setAuthToken(t,e){const{bearer:r}=e||{};this.authToken=t,this.requests.defaults.headers.common.Authorization=r?`Bearer ${t}`:t}setHeader(t,e){this.requests.defaults.headers.common[t]=e}setRoomName(t){this.roomName=t}setRoomUUID(t){this.roomUUID=t}setOrganizationId(t){this.organizationId=t}}var zO=Object.defineProperty,YO=Object.getOwnPropertyDescriptor,lr=(s,t,e,r)=>{for(var i=r>1?void 0:r?YO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&zO(t,e,i),i};class Vs extends KO{constructor(e,r){super(e,r);p(this,"telemetry");this.telemetry=e.getValue("telemetry"),this.setHeader("x-realtimekit-version",e.getValue("sdkVersion"))}async getICEServers(){if(this.iceServers)return this.iceServers;const{success:e,iceServers:r}=(await this.requests.get("/iceservers")).data;if(e)return(r==null?void 0:r.length)>0&&(this.iceServers=r),r}async getPresignedUrls(e){const r=So(this.context,"chat_upload_expiry"),i={roomUUID:this.roomUUID,filename:e,expiry:typeof r=="number"?r:void 0},{get_location:n,put_location:o}=(await this.requests.post("/v2/meetings/chat-upload",i)).data.data;return{getLocation:n,putLocation:o}}async uploadFile(e,r){if(navigator.isReactNative&&"uri"in e)try{await fetch(r,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:{uri:e.uri,name:e.name}})}catch(i){this.logger.error(`sendFileMessage::${i}`)}else await this.fetchClient.put(r,e,{headers:{"Content-Type":e.type}})}async startLivestreaming({manualIngestion:e}){const r=Ls(await this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/livestreams`,{manual_ingest:!!e})).data.data;return{playbackUrl:r.playbackUrl,status:r.status,manualIngest:r.manualIngest,ingestionCredentials:r.streamKey?{ingestionServer:r.ingestServer,streamKey:r.streamKey}:null}}async stopLivestreaming(){return this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream/stop`)}async getActiveLivestream(){const e=Ls((await 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}}async getUserDetails(){if(this.userDetails)return this.userDetails;const e=(await this.requests.get("v2/internals/participant-details")).data.data;return Ls(e)}async startRecording(e,r){return(await this.requests.post("/v2/recordings",{...kv(e),meeting_id:this.context.getValue("meetingId"),allow_multiple_recordings:!!r})).data.data.id}async updateRecording(e,r){return this.requests.put(`v2/recordings/${e}`,{action:r})}async getActiveRecording(){const{status:e,id:r}=(await this.requests.get(`v2/recordings/active-recording/${this.context.getValue("meetingId")}`)).data.data;return{status:e,id:r}}async getActiveTranscript(){const{transcript_download_url:e}=(await this.requests.get(`v2/meetings/${this.context.getValue("meetingId")}/active-transcript`)).data.data;try{return{transcript:(await this.fetchClient.get(e)).data}}catch(r){throw new C("Cant fetch transcript s3 url","1801")}}}lr([E.trace("APIClient.getICEServers")],Vs.prototype,"getICEServers",1),lr([E.trace("APIClient.startLivestreaming")],Vs.prototype,"startLivestreaming",1),lr([E.trace("APIClient.stopLivestreaming")],Vs.prototype,"stopLivestreaming",1),lr([E.trace("APIClient.getActiveLivestream")],Vs.prototype,"getActiveLivestream",1),lr([E.trace("APIClient.getUserDetails")],Vs.prototype,"getUserDetails",1),lr([E.trace("APIClient.startRecording")],Vs.prototype,"startRecording",1),lr([E.trace("APIClient.stopRecording")],Vs.prototype,"updateRecording",1),lr([E.trace("APIClient.getActiveRecording")],Vs.prototype,"getActiveRecording",1),lr([E.trace("APIClient.getActiveTranscript")],Vs.prototype,"getActiveTranscript",1);let np;function QO(s,t){return np=new Vs(s,t),np}function Ht(){return np}const Wn={maxInvocations:5,period:1};function qt(s,t){return function(e,r,i){const n=i.value;let o=0,c=Date.now();return i.value=function(...d){const l=Date.now(),u=t?this[t]:s;if(l-c>u.period*1e3&&(c=l,o=0),o>=u.maxInvocations)throw new C(`Method rate limit ${u.maxInvocations} invocations/${u.period}sec exceeded`,"0013");return o+=1,n.apply(this,d)},i}}var XO=Object.defineProperty,ZO=Object.getOwnPropertyDescriptor,xs=(s,t,e,r)=>{for(var i=r>1?void 0:r?ZO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&XO(t,e,i),i};const eD=["text","image","file","custom","poll"],fl={maxInvocations:180,period:60};let is=($S=class extends Bt{constructor(t,e,r,i){const n=t.getValue("logger");super(n);m(this,Yl);m(this,jo);p(this,"messages");m(this,ie,void 0);m(this,Ji,void 0);m(this,ot,void 0);m(this,da,void 0);p(this,"maxTextLimit",2e3);f(this,da,t),f(this,ot,e),f(this,ie,r),f(this,Ji,i),this.messages=[]}get telemetry(){return a(this,da).getValue("telemetry")}setMaxTextLimit(t){this.maxTextLimit=t}async sendMessageInternal(t,e){switch(t.type){case"text":{await this.sendTextMessageInternal(t.message,e);break}case"image":await this.sendImageMessageInternal(t.image,e);break;case"file":await this.sendFileMessageInternal(t.file,e);break;default:this.logger.error("sendMessage::message_type_not_supported",{chat:{messageType:t.type}});break}}async sendTextMessageInternal(t,e){var i,n,o,c,d,l;if(t.length>this.maxTextLimit)throw new C("Max character limit breached","0503");if(e&&e.length>0){if(!((i=a(this,ie).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,ie).permissions)!=null&&n.chatPrivate.text))throw this.logger.error("sendTextMessage::private_chat_permission_denied"),new C("Could not send message to private chat.","0501")}else if(!((c=(o=a(this,ie).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,ie).permissions)==null?void 0:d.chatPublic)!=null&&l.text))throw this.logger.error("sendTextMessage::public_chat_permission_denied"),new C("Could not send message to public chat.","0501");if(!t)throw this.logger.error("sendTextMessage::message_can_not_be_empty"),new C("Message can not be empty.","0502");let r=[];e&&e.length>0&&(e.push(a(this,ie).id),r=a(this,Ji).joined.toArray().filter(u=>e.includes(u.id)).map(u=>u.userId),r.push(a(this,ie).userId)),a(this,ot).sendMessage(t,rs.TEXT,e)}async sendImageMessageInternal(t,e){var i,n,o,c,d,l;if(e&&e.length>0){if(!((i=a(this,ie).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,ie).permissions)!=null&&n.chatPrivate.files)){this.logger.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((c=(o=a(this,ie).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,ie).permissions)==null?void 0:d.chatPublic)!=null&&l.files)){this.logger.error("sendImageMessage::permission_denied");return}if(!t){this.logger.error("sendImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(t.type)){this.logger.error("sendImageMessage::image_type_not_supported",{chat:{imageType:t.type}});return}try{const u=Ht(),{getLocation:h,putLocation:g}=await u.getPresignedUrls(t.name);await u.uploadFile(t,g);let v=[];e&&e.length>0&&(e.push(a(this,ie).id),v=a(this,Ji).joined.toArray().filter(y=>e.includes(y.id)).map(y=>y.userId),v.push(a(this,ie).userId)),a(this,ot).sendMessage(h,rs.IMAGE,e)}catch(u){throw new C("Error sending image message.","0500",this.logger)}}async sendFileMessageInternal(t,e){var r,i,n,o,c,d;if(e&&e.length>0){if(!((r=a(this,ie).permissions)!=null&&r.chatPrivate.canSend)||!((i=a(this,ie).permissions)!=null&&i.chatPrivate.files)){this.logger.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((o=(n=a(this,ie).permissions)==null?void 0:n.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,ie).permissions)==null?void 0:c.chatPublic)!=null&&d.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!t){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const l=Ht(),{getLocation:u,putLocation:h}=await l.getPresignedUrls(t.name);await l.uploadFile(t,h);let g=[];e&&e.length>0&&(e.push(a(this,ie).id),g=a(this,Ji).joined.toArray().filter(y=>e.includes(y.id)).map(y=>y.userId),g.push(a(this,ie).userId));const v=JSON.stringify({link:u,name:t.name,size:"size"in t?t.size:0});a(this,ot).sendMessage(v,rs.FILE,e)}catch(l){throw new C("Error sending file message.","0500",this.logger)}}get rateLimits(){return fl}updateRateLimits(t,e){fl.maxInvocations=t,fl.period=e}async sendTextMessage(t,e){return this.sendTextMessageInternal(t,e)}async sendCustomMessage(t,e){var n,o,c,d,l,u,h,g,v,y,k,I,D,N,B;if(e&&e.length>0){if(!((n=a(this,ie).permissions)!=null&&n.chatPrivate.canSend)||!((o=a(this,ie).permissions)!=null&&o.chatPrivate.files)||!((c=a(this,ie).permissions)!=null&&c.chatPrivate.text)){this.logger.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((l=(d=a(this,ie).permissions)==null?void 0:d.chatPublic)!=null&&l.canSend)||!((h=(u=a(this,ie).permissions)==null?void 0:u.chatPublic)!=null&&h.files)||!((v=(g=a(this,ie).permissions)==null?void 0:g.chatPublic)!=null&&v.text)){this.logger.error("sendCustomMessage::permission_denied");return}const r=async U=>{try{if(typeof U=="string")return{link:U};const j=Ht(),{getLocation:Z,putLocation:re}=await j.getPresignedUrls(U.name);return await j.uploadFile(U,re),{link:Z,type:U.type,name:U.name,size:U.size}}catch(j){throw new C("Error sending image message.","0500",this.logger)}},i={...t,files:await Promise.all((k=(y=t.files)!=null?y:[])==null?void 0:k.map(async U=>r(U))),images:await Promise.all((D=(I=t.images)!=null?I:[])==null?void 0:D.map(async U=>r(U))),videos:await Promise.all((B=(N=t.videos)!=null?N:[])==null?void 0:B.map(async U=>r(U)))};a(this,ot).sendMessage(JSON.stringify(i),rs.CUSTOM,e)}async sendImageMessage(t,e){return this.sendImageMessageInternal(t,e)}async sendFileMessage(t,e){return this.sendFileMessageInternal(t,e)}async sendMessage(t,e){return this.sendMessageInternal(t,e)}async editTextMessage(t,e){var r,i,n,o;if(!((i=(r=a(this,ie).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(n=a(this,ie).permissions)==null?void 0:n.chatPublic)!=null&&o.text)){this.logger.error("editTextMessage::permission_denied");return}if(!e){this.logger.error("editTextMessage::message_can_not_be_empty");return}a(this,ot).editMessage(t,e,rs.TEXT)}async editImageMessage(t,e){var i,n,o,c;if(!((n=(i=a(this,ie).permissions)==null?void 0:i.chatPublic)!=null&&n.canSend)||!((c=(o=a(this,ie).permissions)==null?void 0:o.chatPublic)!=null&&c.files)){this.logger.error("editImageMessage::permission_denied");return}if(!e){this.logger.error("editImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(e.type)){this.logger.error("sendImageMessage::image_type_not_supported",{chat:{imageType:e.type}});return}try{const d=Ht(),{getLocation:l,putLocation:u}=await d.getPresignedUrls(e.name);await d.uploadFile(e,u),a(this,ot).editMessage(t,l,rs.IMAGE)}catch(d){throw new C("Error editing image message.","0500",this.logger)}}async editFileMessage(t,e){var r,i,n,o;if(!((i=(r=a(this,ie).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(n=a(this,ie).permissions)==null?void 0:n.chatPublic)!=null&&o.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!e){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const c=Ht(),{getLocation:d,putLocation:l}=await c.getPresignedUrls(e.name);await c.uploadFile(e,l),a(this,ot).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),rs.FILE)}catch(c){throw new C("Error editing file message.","0500",this.logger)}}async editMessage(t,e){switch(e.type){case"text":{this.editTextMessage(t,e.message);break}case"image":{this.editImageMessage(t,e.image);break}case"file":{this.editFileMessage(t,e.file);break}default:{this.logger.error("editMessage::message_type_not_supported",{chat:{messageType:e.type}});break}}}async deleteMessage(t){a(this,ot).deleteMessage(t)}async pin(t){if(!a(this,jo,Wp))throw new C("Can`t pin message without joining room","0505");try{await a(this,ot).setPinState(t,!0)}catch(e){throw new C(`No message found with id: ${t}`,"0504")}}async unpin(t){if(!a(this,jo,Wp))throw new C("Can`t unpin message without joining room","0505");try{await a(this,ot).setPinState(t,!1)}catch(e){throw new C(`No message found with id: ${t}`,"0504")}}async fetchPublicMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await a(this,ot).getChatMessagesPaginated(t,e,r==="before")).messages.map(o=>wo.formatSocketPeerMessage(o))}async fetchPrivateMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after",userId:i}){return(await a(this,ot).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"userId",userId:i})).messages.map(c=>wo.formatSocketPeerMessage(c))}async fetchPinnedMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await a(this,ot).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"pinned",pinned:!0})).messages.map(o=>wo.formatSocketPeerMessage(o))}},ie=new WeakMap,Ji=new WeakMap,ot=new WeakMap,da=new WeakMap,Yl=new WeakSet,sT=function(){return a(this,da).getValue("connectionHandler")},jo=new WeakSet,Wp=function(){return a(this,Yl,sT).socketJoined===!0},$S);xs([E.trace("Chat.sendTextMessage"),qt(fl)],is.prototype,"sendTextMessage",1),xs([E.trace("Chat.sendImageMessage"),qt({maxInvocations:20,period:60})],is.prototype,"sendImageMessage",1),xs([E.trace("Chat.sendFileMessage"),qt({maxInvocations:20,period:60})],is.prototype,"sendFileMessage",1),xs([E.trace("Chat.sendMessage"),qt({maxInvocations:180,period:60})],is.prototype,"sendMessage",1),xs([E.trace("Chat.editTextMessage")],is.prototype,"editTextMessage",1),xs([E.trace("Chat.editImageMessage")],is.prototype,"editImageMessage",1),xs([E.trace("Chat.editFileMessage")],is.prototype,"editFileMessage",1),xs([E.trace("Chat.editMessage")],is.prototype,"editMessage",1),xs([E.trace("Chat.deleteMessage")],is.prototype,"deleteMessage",1),is=xs([pt("0500")],is);var tD=Object.defineProperty,sD=Object.getOwnPropertyDescriptor,rD=(s,t,e,r)=>{for(var i=r>1?void 0:r?sD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&tD(t,e,i),i};const Gr=(US=class{constructor(s,t,e,r){p(this,"chat");p(this,"chatSocketHandler");p(this,"self");m(this,Ki,void 0);f(this,Ki,s),this.chatSocketHandler=t,this.chat=new is(s,t,e,r),this.self=e,this.setupEvents()}get telemetry(){return a(this,Ki).getValue("telemetry")}get logger(){return a(this,Ki).getValue("logger")}static async init(s,t,e,r){return new Gr(s,t,e,r)}static formatMessage(s){return{...s,time:new Date(s.time),type:eD[s.type]}}static formatSocketPeerMessage(s){const t=s.createdAt*1e3,e={displayName:s.displayName,id:s.chatId,time:t,timeMs:s.createdAtMs,type:s.payloadType,isEdited:s.isEdited,userId:s.userId,targetUserIds:s.targetUserIds,message:"",link:"",name:"",html:"",images:[],videos:[],files:[],size:0,pinned:s.pinned};switch(e.type){case rs.TEXT:{e.message=s.payload;break}case rs.IMAGE:{e.link=s.payload;break}case rs.FILE:{const{link:r,name:i,size:n}=JSON.parse(s.payload);e.link=r,e.name=i,e.size=n;break}case rs.CUSTOM:{const{html:r,images:i,message:n,videos:o,files:c}=JSON.parse(s.payload);e.message=n,e.html=r,e.images=i,e.videos=o,e.files=c;break}}return Gr.formatMessage(e)}async getChatMessages(){if(this.self.config.viewType==="LIVESTREAM")return;const s=await this.chatSocketHandler.getChatMessages();if(!(s!=null&&s.payload))return;const t=fv.fromBinary(s.payload).messages;this.chat.messages=t.map(e=>Gr.formatSocketPeerMessage(e))}setupEvents(){a(this,Ki).getValue("peerSessionStore").on(P.SOCKET_SERVICE_ROOM_JOINED,async()=>{this.getChatMessages()}),this.chatSocketHandler.on(Ke.sendMessageToRoom,s=>{if(!s.message)return;const t=Gr.formatSocketPeerMessage(s.message);this.chat.messages=[...this.chat.messages,t],this.chat.emit("chatUpdate",{action:"add",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(Ke.sendMessageToPeers,s=>{const t=Gr.formatSocketPeerMessage(s.message);this.chat.messages=[...this.chat.messages,t],this.chat.emit("chatUpdate",{action:"add",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(Ke.editMessage,s=>{if(!s.message)return;const t=Gr.formatSocketPeerMessage(s.message),e=this.chat.messages.findIndex(r=>r.id===t.id);e!==-1&&(this.chat.messages[e]=t),this.chat.emit("chatUpdate",{action:"edit",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(Ke.deleteMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId);let e={id:s.chatId};t!==-1&&([e]=this.chat.messages.splice(t,1)),this.chat.emit("chatUpdate",{action:"delete",message:e,messages:this.chat.messages})}),this.chatSocketHandler.on(Ke.pinMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId),e=Gr.formatSocketPeerMessage(s.message);t!==-1&&(this.chat.messages[t]=e),this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages}),s.pinned?this.chat.emit("pinMessage",{message:e,messages:this.chat.messages}):this.chat.emit("unpinMessage",{message:e,messages:this.chat.messages})})}},Ki=new WeakMap,US);let wo=Gr;rD([E.trace("ChatController.setupEvents")],wo.prototype,"setupEvents",1);var iD=Object.defineProperty,nD=Object.getOwnPropertyDescriptor,aD=(s,t,e,r)=>{for(var i=r>1?void 0:r?nD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&iD(t,e,i),i};let ap=(BS=class extends Bt{constructor(t,e,r){const i=t.getValue("logger");super(i);m(this,Ql);m(this,Xl);p(this,"items");m(this,la,void 0);m(this,ua,void 0);m(this,Go,void 0);f(this,Go,t),f(this,la,e),f(this,ua,r),this.items=[]}async create(t,e,r=!1,i=!1){if(!a(this,Xl,iT))throw new C("Can't create polls without joining room","0705");if(!a(this,la).permissions.polls.canCreate){this.logger.error("Polls::create::permission_denied");return}if(!t||!e){this.logger.error("Polls::question_and_options_can_not_be_empty",{polls:{hasQuestion:!!t,optionsLength:e==null?void 0:e.length}});return}if(e.length<2){this.logger.error("Polls::there_must_be_at_least_two_options",{polls:{hasQuestion:!!t,optionsLength:e.length}});return}await a(this,ua).createPoll(t,e,r,i)}async vote(t,e){if(!a(this,la).permissions.polls.canVote){this.logger.error("Polls::vote::permission_denied");return}await a(this,ua).votePoll(t,e)}},Ql=new WeakSet,rT=function(){return a(this,Go).getValue("connectionHandler")},Xl=new WeakSet,iT=function(){var t;return((t=a(this,Ql,rT))==null?void 0:t.socketJoined)===!0},la=new WeakMap,ua=new WeakMap,Go=new WeakMap,BS);ap=aD([pt("0700")],ap);var oD=Object.defineProperty,cD=Object.getOwnPropertyDescriptor,dD=(s,t,e,r)=>{for(var i=r>1?void 0:r?cD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&oD(t,e,i),i};const Jn=(FS=class{constructor(s,t,e){p(this,"polls");m(this,ti,void 0);m(this,ha,void 0);m(this,zi,void 0);this.polls=new ap(s,t,e),f(this,ha,t),f(this,ti,s),f(this,zi,e),this.setupEvents()}get telemetry(){return a(this,ti).getValue("telemetry")}get logger(){return a(this,ti).getValue("logger")}static async init(s,t,e){return new Jn(s,t,e)}canViewPolls(){return a(this,ha).permissions.polls.canView}setupEvents(){const s={[cr.createPoll]:r=>{r.poll&&this.updatePoll(Jn.formatSocketServicePoll(r.poll))},[cr.updatePoll]:r=>{r.poll&&this.updatePoll(Jn.formatSocketServicePoll(r.poll))},[cr.votePoll]:r=>{r.poll&&this.updatePoll(Jn.formatSocketServicePoll(r.poll))}},t=()=>{a(this,ti).getValue("peerSessionStore").on(P.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,zi).on(r,s[r])})},e=()=>{a(this,ti).getValue("peerSessionStore").on(P.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,zi).removeListeners(r)})};a(this,ha).permissions.on("permissionsUpdate",async r=>{var i;r!=null&&r.polls&&((i=r==null?void 0:r.polls)!=null&&i.canView?(await this.getPolls(),t()):(this.polls.items=[],e()))}),this.canViewPolls()&&t()}updatePoll(s){if(!this.canViewPolls())return;const t=this.polls.items.findIndex(e=>e.id===s.id);if(t>-1){const e=JSON.stringify(this.polls.items[t]);this.polls.items[t]=s,e!==JSON.stringify(s)&&this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!1});return}this.polls.items=[...this.polls.items,s],this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!0})}async getPolls(){const s=await a(this,zi).getPolls();if(!(s!=null&&s.payload))return;const{polls:t}=kO.fromBinary(s.payload);this.polls.items=t.map(e=>Jn.formatSocketServicePoll(e))}static formatSocketServicePoll(s){const t=s.options.map(e=>({count:e.count,text:e.text,votes:e.votes.map(r=>({id:r.userId,name:r.name}))}));return{anonymous:s.anonymous,createdBy:s.createdBy,createdByUserId:s.createdByUserId,hideVotes:s.hideVotes,id:s.pollId,options:t,question:s.question,voted:s.votes}}},ti=new WeakMap,ha=new WeakMap,zi=new WeakMap,FS);let Cv=Jn;dD([E.trace("PollController.setupEvents")],Cv.prototype,"setupEvents",1);var lD=Object.defineProperty,uD=Object.getOwnPropertyDescriptor,hD=(s,t,e,r)=>{for(var i=r>1?void 0:r?uD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&lD(t,e,i),i};const vl=Symbol("ApplyRemoteTitleSync");var Rv=(s=>(s[s.User=0]="User",s[s.Meeting=1]="Meeting",s))(Rv||{});let op=(HS=class extends Bt{constructor(t,e,r,i,n){const o=t.getValue("logger");super(o);m(this,Wo);p(this,"selfActiveTab");p(this,"broadcastTabChanges");m(this,Yi,void 0);m(this,yr,void 0);m(this,pa,void 0);p(this,"viewType");p(this,"meetingStartedTimestamp");p(this,"meetingTitle");p(this,"sessionId");f(this,Yi,t),f(this,yr,e),this.viewType=r,f(this,pa,i),this.meetingTitle=n,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return a(this,Wo,Jp).socketState}get mediaState(){return a(this,Wo,Jp).mediaState}[vl](t){this.meetingTitle=t,this.emit("meetingTitleUpdate",{meetingTitle:t})}get meetingId(){return a(this,Yi).getValue("meetingId")}async setMeetingTitle(t){var i,n,o;const e=(i=a(this,Yi).getValue("meeting"))==null?void 0:i.connectedMeetings;if(((n=e==null?void 0:e.parentMeeting)==null?void 0:n.id)&&(e!=null&&e.isActive)){if(!((o=a(this,yr).permissions.connectedMeetings)!=null&&o.canAlterConnectedMeetings))throw this.logger.error("Meta::setMeetingTitle::permission_denied"),new C("User does not have permission to edit the meeting title","0801");await e.updateMeetings([{id:this.meetingId,title:t}]);return}if(!a(this,yr).permissions.canEditMeetingTitle)throw this.logger.error("Meta::setMeetingTitle::permission_denied"),new C("User does not have permission to edit the meeting title","0801");await a(this,pa).updateRoomTitle(t)}setBroadcastTabChanges(t){if(!a(this,yr).permissions.canSpotlight)throw this.logger.error("Spotlight::setSpotlighted::permission_denied"),new C("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;this.logger.info("Spotlight::setActiveTab",{spotlight:{currentTab:{id:t.id,type:t.type}}}),this.selfActiveTab=t,e===0&&this.emit("selfTabUpdate",t),(r=a(this,yr).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){a(this,pa).broadcastMessage("spotlight",{userId:a(this,yr).userId,currentTab:this.selfActiveTab})}},Yi=new WeakMap,Wo=new WeakSet,Jp=function(){return a(this,Yi).getValue("connectionHandler")},yr=new WeakMap,pa=new WeakMap,HS);op=hD([pt("0800")],op);function pD(s){let t="",e=[""];const r=[e];let i=0,n=0,o=!0,c;for(c of s)c==='"'?(o&&c===t&&(e[i]+=c),o=!o):c===","&&o?c=e[++i]="":c===`
|
|
13
|
-
`&&o?(t==="\r"&&(e[i]=e[i].slice(0,-1)),e=r[++n]=[c=""],i=0):e[i]+=c,t=c;return r}var
|
|
14
|
-
`).map(e=>Li.parseTranscript(e,!1)).filter(Boolean):[]}async getActiveTranscript(){try{const t=Ht(),{transcript:e}=await t.getActiveTranscript();this.transcripts=Li.parseTranscripts(e)}catch(t){}}async onTranscript(t){var r;const e=this.transcripts.filter(({peerId:i})=>i===t.peerId);if((r=e==null?void 0:e.at(-1))!=null&&r.isPartialTranscript){const i=e.at(-1);i.transcript=t.transcript,i.isPartialTranscript=t.isPartialTranscript,this.emit("transcript",i);return}this.transcripts=[...this.transcripts,t],this.emit("transcript",t)}},Jo=new WeakMap,qS);Iv([E.trace("Ai.getActiveTranscript")],Li.prototype,"getActiveTranscript",1),Li=Iv([pt("0000")],Li);var fD=Object.defineProperty,vD=Object.getOwnPropertyDescriptor,SD=(s,t,e,r)=>{for(var i=r>1?void 0:r?vD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&fD(t,e,i),i};const cp=(jS=class{constructor(s,t,e,r,i,n){p(this,"meta");p(this,"ai");m(this,si,void 0);m(this,Qi,void 0);p(this,"aiSocketHandler");m(this,Jt,void 0);f(this,Jt,s),this.meta=new op(s,t,t.config.viewType,e,n),this.ai=r,f(this,si,t),f(this,Qi,e),this.aiSocketHandler=i,this.setupEvents()}get telemetry(){return a(this,Jt).getValue("telemetry")}get logger(){return a(this,Jt).getValue("logger")}static async init(s,t,e,r,i){const n=await Li.init(s,t.permissions.transcriptionEnabled);return new cp(s,t,e,n,r,i)}conditionallySetActiveTab(s){var t;s!=null&&s.currentTab&&((t=this.meta.selfActiveTab)==null?void 0:t.id)!==s.currentTab.id&&(this.meta.setSelfActiveTab(s.currentTab,Rv.Meeting),this.meta.emit("activeTabUpdate",s.currentTab))}setupEvents(){a(this,Jt).getValue("peerSessionStore").on(P.TRANSPORT_STATE_UPDATE,s=>{this.meta.emit("mediaConnectionUpdate",s)}),a(this,Jt).getValue("peerSessionStore").on(P.SOCKET_STATE_UPDATE,s=>{this.meta.emit("socketConnectionUpdate",s)}),a(this,Jt).getValue("peerSessionStore").on(P.ROOM_STATE,({createdAt:s,roomUuid:t,title:e})=>{e&&e!==this.meta.meetingTitle&&this.meta[vl](e);const r=this.meta.meetingStartedTimestamp;if(t&&(this.meta.sessionId=t),s&&!r){const i=new Date(s*1e3);this.meta.meetingStartedTimestamp=i,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),a(this,Jt).getValue("peerSessionStore").on(P.PRODUCER_SCORE_UPDATE,({score:s})=>{s<5&&this.meta.emit("poorConnection",{score:s})}),a(this,si).permissions.canSpotlight&&this.meta.selfActiveTab&&(this.logger.info("Asserting Spotlight status to other peers."),a(this,Qi).broadcastMessage("spotlight",{userId:a(this,si).userId,currentTab:this.meta.selfActiveTab})),a(this,Jt).getValue("peerSessionStore").on(P.PEER_JOINED_INTERNAL,async s=>{a(this,si).permissions.canSpotlight&&this.meta.selfActiveTab&&a(this,Qi).broadcastToPeers("spotlight",[s.id],{userId:a(this,si).userId,currentTab:this.meta.selfActiveTab})}),a(this,Jt).getValue("peerSessionStore").on(P.ROOM_MESSAGE,s=>{var e,r;let t;if("type"in s){if(s.type!=="spotlight")return;t={...s,...s.payload}}else if("roomMessageType"in s){if(s.roomMessageType!=="spotlight")return;t=s}else return;this.logger.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:t.userId},currentTab:{id:(e=t.currentTab)==null?void 0:e.id,type:(r=t.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(t)}),a(this,Jt).getValue("peerSessionStore").on(P.MESSAGE,s=>{var e,r;let t;if("type"in s){if(s.type!=="spotlight")return;t={...s,...s.payload}}else if("roomMessageType"in s){if(s.roomMessageType!=="spotlight")return;t=s}else return;this.logger.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:t.userId},currentTab:{id:(e=t.currentTab)==null?void 0:e.id,type:(r=t.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(t)}),a(this,Qi).on(x.updateRoomInfo,s=>{var e;const t=(e=s==null?void 0:s.room)==null?void 0:e.title;!t||t===this.meta.meetingTitle||this.meta[vl](t)}),this.aiSocketHandler.on(x.transcript,s=>{let t;try{t=cp.extractSocketTranscript(s)}catch(e){this.logger.error("Failed to parse transcript socket message.",{error:e});return}if(!t){this.logger.warn("Received empty transcript data");return}this.ai.onTranscript(t)})}static extractSocketTranscript(s){return s?{id:Ci(),name:s.speaker.displayName,peerId:s.speaker.peerId,userId:s.speaker.participantId,customParticipantId:s.speaker.customParticipantId,transcript:s.sentence,isPartialTranscript:s.isPartial||!1,date:new Date(s.startedAt*1e3)}:void 0}},si=new WeakMap,Qi=new WeakMap,Jt=new WeakMap,jS);let Av=cp;SD([E.trace("MetaController.setupEvents")],Av.prototype,"setupEvents",1);const Po={},ur={executeWithLock({methodName:s,lockName:t,timeout:e}){return(r,i,n)=>{const o=n.value;return n.value=function(...d){var y,k;const l=(k=(this==null?void 0:this.peerId)||((y=d[0])==null?void 0:y.authToken))!=null?k:"",u=`${t}-${l}`,h=this==null?void 0:this.logger;if(Po[u]){const I=new Error(`Unsupported concurrent calls on method: ${s}.`);throw I.name="UnsupportedConcurrentMethodExecution",h==null||h.error("Locker::UnsupportedConcurrentMethodExecution",{error:{stack:I.stack},locker:{methodName:s,lockName:u}}),I}Po[u]=!0;const g=setTimeout(()=>delete Po[u],e),v=o.apply(this,d);return Promise.resolve(v).then(()=>{delete Po[u],clearTimeout(g)}).catch(()=>{delete Po[u],clearTimeout(g)}),v},n}}};var TD=Object.defineProperty,yD=Object.getOwnPropertyDescriptor,Vi=(s,t,e,r)=>{for(var i=r>1?void 0:r?yD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&TD(t,e,i),i};class Wr extends Bt{constructor(e,r,i,n,o){const c=e.getValue("logger");super(c);m(this,zo);m(this,ma);m(this,ds,void 0);m(this,Zl,void 0);m(this,le,void 0);m(this,Ko,void 0);m(this,Us,void 0);m(this,Qe,void 0);f(this,Qe,e),f(this,ds,n),f(this,Zl,o),f(this,le,r),f(this,Ko,i),f(this,Us,[]),this.setupEvents()}get telemetry(){return a(this,Qe).getValue("telemetry")}get status(){return a(this,Qe).getValue("stageStatus")}setupEvents(){const e={[P.GET_STAGE_REQUESTS]:async n=>{f(this,Us,n)},[P.UPDATE_STAGE_REQUESTS]:async({add:n})=>{const o=a(this,Us).length,{stageRequests:c}=this.getAccessRequests();(n||c.length>o)&&this.emit("newStageRequest",{count:c.length}),this.emit("stageAccessRequestUpdate",c)}},r=()=>{Object.entries(e).forEach(([n,o])=>{a(this,Qe).getValue("peerSessionStore").onAsync(n,o)})},i=()=>{Object.entries(e).forEach(([n,o])=>{a(this,Qe).getValue("peerSessionStore").removeListener(n,o)})};a(this,le).permissions.on("permissionsUpdate",n=>{const{canAcceptProductionRequests:o}=n;o!==void 0&&(a(this,le).permissions.acceptStageRequests?(r(),a(this,ds).getStageRequests()):(i(),f(this,Us,[]),this.emit("stageAccessRequestUpdate",a(this,Us))))}),a(this,le).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!a(this,le).permissions.acceptStageRequests)throw this.logger.error("Stage::get_access_request::permission_denied"),new C("You do not have permission to perform this action","2001");const e=a(this,Ko).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return f(this,Us,e),{stageRequests:a(this,Us)}}async requestAccess(){if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(this.status!=="OFF_STAGE")throw new C(`Unable to request access you are currently ${this.status}`,"2006");if(a(this,le).permissions.stageAccess===G.Allowed){R(this,ma,eh).call(this,"ACCEPTED_TO_JOIN_STAGE");return}a(this,ds).requestAccess(),R(this,ma,eh).call(this,"REQUESTED_TO_JOIN_STAGE")}async cancelRequestAccess(){if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");a(this,ds).cancelRequestAccess(),R(this,ma,eh).call(this,"OFF_STAGE")}grantAccess(e){if(!a(this,le).roomJoined)throw new C("Can`t grant for participant without joining room");if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!a(this,le).permissions.acceptStageRequests)throw this.logger.error("Stage::grant_access::permission_denied"),new C("You do not have permission to perform this action","2001");return a(this,ds).grantAccess(e)}denyAccess(e){if(!a(this,le).roomJoined)throw new C("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!a(this,le).permissions.acceptStageRequests)throw this.logger.error("Stage::deny_access::permission_denied"),new C("You do not have permission to perform this action","2001");return a(this,ds).denyAccess(e)}get peerId(){return a(this,Qe).getValue("peerId")}async join(){const e=a(this,Qe).getValue("viewType");if(this.status==="ON_STAGE")throw new C("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||a(this,le).permissions.stageAccess===G.NotAllowed)throw new C(`Unable to join stage you are currently ${this.status}`,"2006");if(a(this,Qe).setValue("stageStatus","ON_STAGE",!1),await a(this,ds).joinStage(),e===Ss.Livestream){await a(this,Qe).getValue("selfController").joinRoom();return}a(this,Qe).notify("stageStatus"),a(this,le).audioEnabled&&a(this,zo,Kp).shareMic(a(this,le).audioTrack),a(this,le).videoEnabled&&a(this,zo,Kp).shareWebcam(a(this,le).videoTrack)}async leave(){if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new C(`Unable to leave stage you are currently ${this.status}`,"2006");a(this,le).setIsPinned(!1),a(this,Qe).setValue("stageStatus","OFF_STAGE",!1),await a(this,ds).leaveStage(a(this,le).userId);try{await a(this,Qe).getValue("peerSessionStore").emitAsync(P.LEAVE_MEDIA_ROOM,"stageLeft")}catch(e){this.logger.error("Stage::leave::emitAsync::failed",{error:e})}a(this,Qe).notify("stageStatus")}async kick(e){if(!a(this,le).roomJoined)throw new C("Can`t kick participant without joining room","2005");if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!a(this,le).permissions.acceptStageRequests)throw this.logger.error("Stage::kick::permission_denied"),new C("You do not have permissions for kick","2001");return a(this,ds).kick(e)}}ds=new WeakMap,Zl=new WeakMap,le=new WeakMap,Ko=new WeakMap,Us=new WeakMap,Qe=new WeakMap,zo=new WeakSet,Kp=function(){return a(this,Qe).getValue("roomNodeClient")},ma=new WeakSet,eh=async function(e){this.status!==e&&a(this,Qe).setValue("stageStatus",e)},Vi([E.trace("Stage.getStageRequests")],Wr.prototype,"getAccessRequests",1),Vi([E.trace("Stage.requestAccess")],Wr.prototype,"requestAccess",1),Vi([E.trace("Stage.cancelRequestAccess")],Wr.prototype,"cancelRequestAccess",1),Vi([E.trace("Stage.grantAccess")],Wr.prototype,"grantAccess",1),Vi([E.trace("Stage.denyAccess")],Wr.prototype,"denyAccess",1),Vi([ur.executeWithLock({methodName:"joinStage",lockName:"Stage.join",timeout:5e3}),E.trace("Stage.joinStage")],Wr.prototype,"join",1),Vi([E.trace("Stage.leaveStage")],Wr.prototype,"leave",1);function ED(s){return!(s.viewType==="LIVESTREAM"||s.viewType==="CHAT")}function dp(s){switch(s){case ar.UNSPECIFIED:return"OFF_STAGE";case ar.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case ar.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case ar.OFF_STAGE:return"OFF_STAGE";case ar.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var bD=Object.defineProperty,wD=Object.getOwnPropertyDescriptor,PD=(s,t,e,r)=>{for(var i=r>1?void 0:r?wD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&bD(t,e,i),i};class Mv{constructor(t,e,r,i,n){p(this,"stage");m(this,ri,void 0);m(this,Ps,void 0);m(this,ii,void 0);m(this,Yo,0);m(this,Et,void 0);f(this,Et,t),this.stage=new Wr(t,i,n,e,r),f(this,ii,e),f(this,ri,i),f(this,Ps,n),this.setupEvents()}get telemetry(){return a(this,Et).getValue("telemetry")}get logger(){return a(this,Et).getValue("logger")}setupEvents(){a(this,Et).subscribe("stageStatus",t=>{this.stage.emit("stageStatusUpdate",t)}),a(this,ii).on(x.grantStageAccess,()=>{a(this,ri).permissions.stageAccess!==G.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),a(this,ii).on(x.peerStageStatusUpdate,t=>{t!==void 0&&(t.peerId===a(this,ri).id?this.selfStageStatusHandler(t):this.peerStageStatusHandler(t))}),a(this,ii).on(x.denyStageAccess,()=>{a(this,ri).permissions.stageAccess!==G.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),a(this,ii).on(x.getStageRequests,async t=>{var r;if(a(this,ri).permissions.stageAccess!==G.Allowed)return;const e=(r=t==null?void 0:t.stageRequests)!=null?r:[];await a(this,Et).getValue("peerSessionStore").emitAsync(P.GET_STAGE_REQUESTS,e),a(this,Yo)<e.length&&e.length>0&&this.stage.emit("newStageRequest",{count:e.length}),f(this,Yo,e.length),this.stage.emit("stageAccessRequestUpdate",e)})}getCurrentStageRequests(){return a(this,Ps).joined.toArray().filter(e=>e.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(e=>({displayName:e.name,userId:e.userId,peerId:e.id}))}async setStageStatus(t){this.stage.status!==t&&a(this,Et).setValue("stageStatus",t)}selfStageStatusHandler(t){const e=dp(t.stageType),r=a(this,Et).getValue("stageStatus");if(r!==e)switch(t.stageType){case 1:a(this,Et).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(r);break;case 0:case 4:default:a(this,Et).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}async peerStageStatusHandler(t){const e=a(this,Ps).joined.get(t.peerId),r=a(this,Ps).viewMode==="ACTIVE_GRID";if(!e){this.logger.warn("err::peerStageStatusUpdate: participant not found");return}switch(t.stageType){case 1:e.setStageStatus("ON_STAGE"),r&&a(this,Et).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:a(this,Ps).viewMode,page:a(this,Ps).currentPage});break;case 2:e.setStageStatus("ACCEPTED_TO_JOIN_STAGE");break;case 3:e.setStageStatus("REQUESTED_TO_JOIN_STAGE");break;case 0:case 4:default:e.setStageStatus("OFF_STAGE"),r&&a(this,Et).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:a(this,Ps).viewMode,page:a(this,Ps).currentPage});break}a(this,Et).getValue("peerSessionStore").emit(P.UPDATE_PEER_STAGE_STATUS,{id:e.id,status:e.stageStatus})}}ri=new WeakMap,Ps=new WeakMap,ii=new WeakMap,Yo=new WeakMap,Et=new WeakMap,PD([E.trace("Stage.setupEvents")],Mv.prototype,"setupEvents",1);var kD=Object.defineProperty,_D=Object.getOwnPropertyDescriptor,lp=(s,t,e,r)=>{for(var i=r>1?void 0:r?_D(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&kD(t,e,i),i};let ko=(GS=class extends Bn{constructor(t,e,r,i){const n=t.getValue("logger");super(n);p(this,"name");p(this,"icon");p(this,"id");p(this,"permissions");m(this,Xi,void 0);m(this,Er,void 0);m(this,Qo,void 0);m(this,Xo,void 0);m(this,Zi,void 0);p(this,"active");p(this,"enabledBy");f(this,Qo,t);const o=t.getValue("meetingId");this.id=`${o}:${e.id}`,this.name=e.name,this.icon=e.icon,f(this,Xo,e.component),this.permissions=e.permissions,f(this,Xi,i),f(this,Er,r),this.active=!1,this.enabledBy=""}get component(){return a(this,Xo)}get telemetry(){return a(this,Qo).getValue("telemetry")}set activePluginsStore(t){f(this,Er,t)}activateForSelf(){f(this,Zi,new Date),this.active=!0,this.emit("stateUpdate",{active:this.active,pluginId:this.id}),this.emit("enabled")}deactivateForSelf(){f(this,Zi,void 0),this.active=!1,this.emit("stateUpdate",{active:this.active,pluginId:this.id}),this.emit("closed")}async activate(){var t;if(!this.active&&(t=this.permissions)!=null&&t.canActivate){if(!a(this,Er))throw new C("Cannot activate plugin: active plugins store is not available yet.","0604");await a(this,Er).set(this.id,{name:this.name,icon:this.icon,id:this.id,enabledBy:a(this,Xi).id}),this.enabledBy=a(this,Xi).id,this.activateForSelf(),this.logger.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}})}}async deactivate(){var e;if(!this.active||!((e=this.permissions)!=null&&e.canDeactivate)&&this.enabledBy!==a(this,Xi).id)return;if(!a(this,Er))throw new C("Cannot deactivate plugin: active plugins store is not available yet.","0604");const t=a(this,Zi)?new Date().getTime()-a(this,Zi).getTime():0;await a(this,Er).set(this.id,null),this.deactivateForSelf(),this.logger.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:t}})}},Xi=new WeakMap,Er=new WeakMap,Qo=new WeakMap,Xo=new WeakMap,Zi=new WeakMap,GS);lp([E.trace("Plugin.activatePlugin")],ko.prototype,"activate",1),lp([E.trace("Plugin.deactivatePlugin")],ko.prototype,"deactivate",1),ko=lp([pt("0600")],ko);class Ov extends Map{constructor(e,r=void 0){const{onAddEvent:i,onDeleteEvent:n,onClearEvent:o}=e;super();m(this,Be,void 0);m(this,en,void 0);p(this,"onAddEvent");p(this,"onDeleteEvent");p(this,"onClearEvent");f(this,Be,new Bn(r)),this.onAddEvent=i,this.onDeleteEvent=n,this.onClearEvent=o,f(this,en,new Map)}emit(e,...r){return a(this,Be).emit(e,...r)}on(e,r){return a(this,Be).on(e,r)}addListener(e,r){return a(this,Be).addListener(e,r)}off(e,r){return a(this,Be).off(e,r)}once(e,r){return a(this,Be).once(e,r)}prependListener(e,r){return a(this,Be).prependListener(e,r)}prependOnceListener(e,r){return a(this,Be).prependOnceListener(e,r)}removeListener(e,r){return a(this,Be).removeListener(e,r)}removeAllListeners(e){return a(this,Be).removeAllListeners(e)}listeners(e){return a(this,Be).listeners(e)}listenerCount(e){return a(this,Be).listenerCount(e)}getMaxListeners(){return a(this,Be).getMaxListeners()}setMaxListeners(e){return a(this,Be).setMaxListeners(e)}eventNames(){return a(this,Be).eventNames()}add(e,r=!0){return this.set(e.id,e,r)}set(e,r,i=!0){const n=super.set(e,r),o=(c,...d)=>{this.emit(c,r,...d)};return a(this,en).set(e,o),r.on("*",o),i&&a(this,Be).emit(this.onAddEvent,r),n}delete(e,r=!0,i=!1){const n=this.get(e);if(!n)return!1;n.removeListener("*",a(this,en).get(e));const o=super.delete(e);return i&&n.removeAllListeners(),r&&a(this,Be).emit(this.onDeleteEvent,n),o}clear(e=!0,r=!1){this.forEach(n=>{n.removeListener("*",a(this,en).get(n.id)),r&&n.removeAllListeners()});const i=super.clear();return e&&a(this,Be).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}Be=new WeakMap,en=new WeakMap;class Dv extends Ov{constructor(t){super({onAddEvent:"pluginAdded",onDeleteEvent:"pluginDeleted"},t)}add(t,e=!0){return super.add(t,e)}delete(t,e=!0,r=!1){return super.delete(t,e,r)}}var CD=Object.defineProperty,RD=Object.getOwnPropertyDescriptor,ID=(s,t,e,r)=>{for(var i=r>1?void 0:r?RD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&CD(t,e,i),i};let up=class{constructor(s){p(this,"all");p(this,"active");this.all=new Dv(s),this.active=new Dv(s)}};up=ID([pt("0600")],up);var AD=Object.defineProperty,MD=Object.getOwnPropertyDescriptor,OD=(s,t,e,r)=>{for(var i=r>1?void 0:r?MD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&AD(t,e,i),i};const Nv=(WS=class{constructor(s,t,e,r){m(this,eu);m(this,Zo);m(this,ec);m(this,tc);p(this,"plugins");m(this,ks,void 0);m(this,ga,void 0);m(this,ni,void 0);m(this,tn,null);f(this,ni,s),this.plugins=t,f(this,ga,e),f(this,ks,r),this.setupEvents()}get telemetry(){return a(this,ni).getValue("telemetry")}get logger(){return a(this,ni).getValue("logger")}static async init(s,t,e,r){var l,u;const i=s.getValue("logger"),n=s.getValue("connectionHandler"),o=new up(i);let c;n.socketState.state==="connected"?(i.info("Creating active plugins store immediately. Socket is already connected."),c=await r.create(Dh,!0)):i.info("Deferring active plugins store creation until socket connects."),t.forEach(h=>{const g=new ko(s,h,c,e);o.all.add(g)});const d=new Nv(s,o,r,c);return c?R(l=d,tc,Qp).call(l):R(u=d,eu,nT).call(u),d}cleanup(){R(this,Zo,zp).call(this)}setupEvents(){this.plugins.all.on("stateUpdate",({active:s,id:t})=>{if(s){this.plugins.active.add(this.plugins.all.get(t));return}this.plugins.active.delete(t)}),a(this,ni).getValue("peerSessionStore").onAsync(P.SOCKET_SERVICE_ROOM_JOINED,async()=>{var t,e;if(((e=(t=this.plugins.active)==null?void 0:t.toArray())!=null?e:[]).forEach(r=>{r.deactivateForSelf()}),!a(this,ks)){this.logger.warn("Active plugins store not available yet on ROOM_JOINED. Sync will be performed when store is created.");return}await R(this,ec,Yp).call(this),this.logger.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to sync active plugins.")})}},ks=new WeakMap,ga=new WeakMap,ni=new WeakMap,tn=new WeakMap,eu=new WeakSet,nT=function(){const s=a(this,ni).getValue("peerSessionStore"),t=async e=>{if(e.state==="connected"&&!a(this,ks))try{f(this,ks,await a(this,ga).create(Dh,!0)),R(this,Zo,zp).call(this),this.plugins.all.toArray().forEach(r=>{r.activePluginsStore=a(this,ks)}),R(this,tc,Qp).call(this),this.logger.info("Active plugins store created after socket connected"),await R(this,ec,Yp).call(this)}catch(r){this.logger.error("Failed to create active plugins store after socket connected, will retry on next reconnect",{error:r})}};s.on(P.SOCKET_STATE_UPDATE,t),f(this,tn,()=>{s.off(P.SOCKET_STATE_UPDATE,t)})},Zo=new WeakSet,zp=function(){a(this,tn)&&(a(this,tn).call(this),f(this,tn,null))},ec=new WeakSet,Yp=async function(){try{await a(this,ga).refresh(a(this,ks).name)}catch(t){this.logger.error("Failed to refresh active plugins store, syncing from stale data.",{error:t})}const s=a(this,ks).getAll();Object.entries(s).forEach(([t,e])=>{if(!e)return;const r=this.plugins.all.get(t);if(!r){this.logger.warn(`Plugin '${t}' not found in plugins.all, ignoring store entry.`);return}r.active||(r.enabledBy=e.enabledBy,r.activateForSelf())})},tc=new WeakSet,Qp=function(){a(this,ks).subscribe("*",s=>{Object.entries(s).forEach(([t,e])=>{const r=this.plugins.all.get(t);if(!r){this.logger.warn(`Plugin '${t}' not found in plugins.all, ignoring store update.`);return}!e&&r.active&&r.deactivateForSelf(),e&&!r.active&&(r.enabledBy=e.enabledBy,r.activateForSelf())})})},WS);let Lv=Nv;OD([E.trace("PluginController.setupEvents")],Lv.prototype,"setupEvents",1);class DD{constructor(t){p(this,"mediaJoined");p(this,"socketJoined");p(this,"socketJoinAttempted");p(this,"mediaJoinAttempted");p(this,"socketState");p(this,"mediaState");m(this,sc,void 0);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},f(this,sc,t)}get joinAttempted(){return this.mediaJoinAttempted||this.socketJoinAttempted}get roomJoined(){return this.mediaJoined&&this.socketJoined}updateSocketConnectionState(t,e){let r;const{reconnected:i}=this.socketState;switch(t){case"connected":r={state:"connected",reconnected:i,reconnectionAttempt:void 0};break;case"disconnected":r={state:"disconnected",reconnected:!1,reconnectionAttempt:0},this.socketJoined=!1;break;case"reconnected":r={state:"connected",reconnected:!0,reconnectionAttempt:void 0};break;case"reconnecting":r={state:"reconnecting",reconnected:i,reconnectionAttempt:0};break;case"reconnectAttempt":r={state:"reconnecting",reconnected:i,reconnectionAttempt:e};break;case"failed":r={state:"failed",reconnected:i,reconnectionAttempt:void 0},this.socketJoined=!1;break}r&&(this.socketState=r,a(this,sc).getValue("peerSessionStore").emit(P.SOCKET_STATE_UPDATE,r))}}sc=new WeakMap;var ND=Object.defineProperty,LD=Object.getOwnPropertyDescriptor,_o=(s,t,e,r)=>{for(var i=r>1?void 0:r?LD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ND(t,e,i),i};const Vv="Cannot start recording: another recording is already in progress.";let xi=(JS=class extends Bt{constructor(t,e){const r=t.getValue("logger");super(r);m(this,Sa);m(this,fa,void 0);m(this,va,void 0);p(this,"recordingPeerIds",[]);p(this,"recordings",[]);f(this,va,t),f(this,fa,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"}get telemetry(){return a(this,va).getValue("telemetry")}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}async start(t){if(!a(this,fa).permissions.canRecord)throw this.logger.error("Recording::start::permission_denied"),new C("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 this.logger.error("Recording::start::recording_in_progress",{recording:{state:this.recordingState}}),new C(Vv,"1005");try{const e=Ht(),{recording:r={}}=a(this,va).getValue("defaults"),i=await e.startRecording(r,t==null?void 0:t.allowMultiple);this.updateRecordings([...this.recordings,{id:i,state:"STARTING",type:"BROWSER"}])}catch(e){throw this.logger.error("Recording::start::recording_failed_to_start",{error:e}),e instanceof gl&&e.status===409?new C(Vv,"1005"):new C("Error while starting recording","1000",this.logger)}}async stop(t){await R(this,Sa,th).call(this,"stop",["RECORDING","PAUSED"],t)}async pause(t){await R(this,Sa,th).call(this,"pause",["RECORDING"],t)}async resume(t){await R(this,Sa,th).call(this,"resume",["PAUSED"],t)}},fa=new WeakMap,va=new WeakMap,Sa=new WeakSet,th=async function(t,e,r){if(!a(this,fa).permissions.canRecord)throw this.logger.error("Recording::stop::permission_denied"),new C("User does not have permission to stop recording","1001");let i=[];if(r!==void 0){const n=this.recordings.find(o=>o.id===r);if(n===void 0)throw new C("Could not find the specified recording","1004");if(e.includes(n.state)){this.logger.error("Recording::stop::recording_not_in_expected_state",{recording:{state:n.state}});return}i.push(n)}else i=this.recordings.filter(n=>e.includes(n.state));i.forEach(async n=>{const o=n.state;t==="stop"&&(n.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{await Ht().updateRecording(n.id,t)}catch(c){throw this.logger.error("Recording::stop::recording_failed_to_stop",{error:c}),n.state!==o&&(n.state=o,this.emit("recordingUpdate",o)),new C("Error while stopping recording","1000",this.logger)}})},JS);_o([E.trace("Recording.start")],xi.prototype,"start",1),_o([E.trace("Recording.stop")],xi.prototype,"stop",1),_o([E.trace("Recording.stop")],xi.prototype,"pause",1),_o([E.trace("Recording.stop")],xi.prototype,"resume",1),xi=_o([pt("1000")],xi);var VD=Object.defineProperty,xD=Object.getOwnPropertyDescriptor,$D=(s,t,e,r)=>{for(var i=r>1?void 0:r?xD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&VD(t,e,i),i};class xv{constructor(t,e,r){p(this,"recording");p(this,"room");m(this,sn,void 0);f(this,sn,t),this.recording=new xi(t,e),this.room=r,this.setupEvents()}get telemetry(){return a(this,sn).getValue("telemetry")}get logger(){return a(this,sn).getValue("logger")}getRecordingTypeFromProtoType(t){let e;switch(t){case Ni.BROWSER:e="BROWSER";break;case Ni.COMPOSITE:e="COMPOSITE";break;case Ni.TRACK:e="TRACK";break;default:e="BROWSER"}return e}setupEvents(){a(this,sn).getValue("peerSessionStore").on(P.ROOM_STATE,t=>{t.activeRecordings.length!==0?this.recording.updateRecordings(t.activeRecordings.map(e=>{const r=this.getRecordingTypeFromProtoType(e.recordingType);return{id:e.recordingId,state:e.recordingStatus,type:r}})):this.recording.recordings.length&&this.recording.updateRecordings([])}),this.room.on(x.recordingStarted,t=>{let e=!1;const r=[...this.recording.recordings];if(r.forEach(i=>{i.id===t.recordingId&&(e=!0,i.state="RECORDING")}),e===!1){const i=this.getRecordingTypeFromProtoType(t.recordingType);r.push({id:t.recordingId,state:"RECORDING",type:i})}this.recording.updateRecordings(r)}),this.room.on(x.recordingPaused,t=>{const e=[...this.recording.recordings];e.forEach(r=>{r.id===t.recordingId&&(r.state="PAUSED")}),this.recording.updateRecordings(e)}),this.room.on(x.recordingStopped,t=>{const e=[...this.recording.recordings.filter(r=>r.id!==t.recordingId)];this.recording.updateRecordings(e)})}}sn=new WeakMap,$D([E.trace("RecordingController.setupEvents")],xv.prototype,"setupEvents",1);class UD{constructor(t){m(this,rn,void 0);f(this,rn,t)}hasFeature(t){return a(this,rn).getValue("logger").warn("Unimplemented method: meeting.__internals__.hasFeature called"),!1}getFeatureValue(t){return a(this,rn).getValue("logger").warn("Unimplemented method: meeting.__internals__.getFeatureValue called"),null}getAllFeatures(){return a(this,rn).getValue("logger").warn("Unimplemented method: meeting.__internals__.getAllFeatures called"),{}}}rn=new WeakMap;class hp{constructor(t,e,r,i){p(this,"authToken");p(this,"logger");p(this,"features");p(this,"browserSpecs");p(this,"callStats");this.authToken=t,this.logger=e,this.features=r,this.browserSpecs=Pe,this.callStats=i}static init(t){return new hp(t.getValue("authToken"),t.getValue("logger"),new UD(t),t.getValue("callstats"))}}class pp{constructor(t){p(this,"internals");this.internals=t}static async init(t){const e=hp.init(t);return new pp(e)}}var BD=Object.defineProperty,FD=Object.getOwnPropertyDescriptor,jt=(s,t,e,r)=>{for(var i=r>1?void 0:r?FD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&BD(t,e,i),i};class Dt extends Bn{constructor(e,r,i=Tl,n=!0){const o=e.getValue("logger");super(o);m(this,Ge,void 0);m(this,Ce,void 0);m(this,be,void 0);m(this,br,void 0);m(this,ls,void 0);m(this,rc,void 0);m(this,Ve,void 0);p(this,"audioUpdateInProgress");p(this,"videoUpdateInProgress");f(this,Ve,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,f(this,Ge,new jv(e,r)),f(this,Ce,new f1(e,a(this,Ge),void 0,i)),f(this,be,new w1(e,a(this,Ge),void 0,i)),f(this,ls,new y1(a(this,Ve),a(this,Ge))),f(this,br,new S1(e,a(this,Ge))),f(this,rc,n),a(this,Ce).on("trackMuted",this.onAudioTrackMuted.bind(this)),a(this,Ce).on("trackChanged",this.onAudioTrackChanged.bind(this)),a(this,be).on("trackChanged",this.onVideoTrackChanged.bind(this)),a(this,be).on("trackEnded",this.onVideoTrackEnded.bind(this)),a(this,ls).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}get telemetry(){return a(this,Ve).getValue("telemetry")}set context(e){f(this,Ve,e)}async onVisibilityChange(){a(this,Ve).getValue("callstats").tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?a(this,Ve).getValue("callstats").browserBackgrounded():(a(this,Ve).getValue("callstats").browserForegrounded(),await this.setupSpeaker())}async repopulateAvailableDevices(){return!0}async setupStreams({audio:e,video:r}){var o;e?a(this,Ve).getValue("callstats").audioOn():a(this,Ve).getValue("callstats").audioOff(),r?a(this,Ve).getValue("callstats").videoOn():a(this,Ve).getValue("callstats").videoOff();let i,n;if(e&&r)try{const c=await a(this,Ge).getAudioAndVideoTrack(a(this,Ce).userSelectedDevice,a(this,be).userSelectedDevice);i=c.audioTrack,n=c.videoTrack}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:c})}if(!i&&e)try{i=await a(this,Ge).getAudioTrack(!1,a(this,Ce).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!n&&r)try{n=await a(this,Ge).getVideoTrack(a(this,be).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get video track",{error:c})}e&&!i&&a(this,Ve).getValue("callstats").audioOff(),r&&!n&&a(this,Ve).getValue("callstats").videoOff(),await a(this,Ce).setMediaTrack(i),await a(this,be).setMediaTrack(n);try{await this.setupSpeaker()}catch(c){}if(n){const c=await this.getDeviceById(n.getSettings().deviceId);a(this,Ve).getValue("callstats").selectedDevice("VIDEO",c)}if(i){const c=await this.getDeviceById(i.getSettings().deviceId);a(this,Ve).getValue("callstats").selectedDevice("AUDIO",c)}(o=a(this,br).currentDevice)!=null&&o.deviceId&&a(this,Ve).getValue("callstats").selectedDevice("SPEAKER",a(this,br).currentDevice),a(this,Ge).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})}getCurrentDevices(){return{audio:a(this,Ce).currentDevice,video:a(this,be).currentDevice,speaker:a(this,br).currentDevice}}get permissions(){return a(this,Ge).permissions}getAllDevices(){return a(this,Ge).getAvailableDevices()}getDeviceById(e,r){return a(this,Ge).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return a(this,Ce).mediaTrack}get audioTrack(){return a(this,Ce).transformedMediaTrack}get audioEnabled(){return a(this,Ce).trackEnabled}async enableAudio(e){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{e?await a(this,Ce).enableTrack(!1,e):await a(this,Ce).unmuteTrack()}catch(r){}finally{this.audioUpdateInProgress=!1}}}disableAudio(){a(this,Ce).mediaTrack&&!a(this,Ce).isCustomTrack?a(this,Ce).muteTrack():a(this,Ce).disableTrack()}getAudioDevices(e){return a(this,Ge).getAudioInputDevices(e)}async setAudioDevice(e,{saveDevicePreference:r}){await a(this,Ce).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Ve).getValue("callstats").selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async setupSpeaker(){const{speaker:e}=this.getCurrentDevices();await a(this,br).setPreferredSpeaker();const{speaker:r}=this.getCurrentDevices();(e==null?void 0:e.deviceId)!==(r==null?void 0:r.deviceId)&&r&&this.emit("DEVICE_CHANGE",{device:r})}async setSpeakerDevice(e,{saveDevicePreference:r}){await a(this,br).setupSpeaker(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Ve).getValue("callstats").selectedDevice("SPEAKER",e),this.emit("DEVICE_CHANGE",{device:e})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return a(this,be).mediaTrack}get videoTrack(){return a(this,be).transformedMediaTrack}get videoEnabled(){return a(this,be).trackEnabled}async enableVideo(e){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{e?await a(this,be).enableTrack(!1,e):await a(this,be).unmuteTrack()}catch(r){}finally{this.videoUpdateInProgress=!1}}}disableVideo(){a(this,be).disableTrack()}getVideoDevices(e){return a(this,Ge).getVideoInputDevices(e)}async setVideoDevice(e,{saveDevicePreference:r}){await a(this,be).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Ve).getValue("callstats").selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async updateVideoConstraints(e){await a(this,be).updateConstraints(e)}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:a(this,ls).audioMediaTrack,video:a(this,ls).videoMediaTrack}}get screenShareEnabled(){return a(this,ls).trackEnabled}async enableScreenShare(){await a(this,ls).enableScreenShare()}async disableScreenShare(){a(this,ls).disableScreenShare()}async updateScreenshareConstraints(e){await a(this,ls).updateConstraints(e)}getSpeakerDevices(e){return a(this,Ge).getAudioOutputDevices(e)}addAudioMiddleware(e){return a(this,Ce).addMiddleware(e)}removeAudioMiddleware(e){return a(this,Ce).removeMiddleware(e)}removeAllAudioMiddlewares(){return a(this,Ce).removeAllMiddlewares()}addVideoMiddleware(e){return a(this,be).addMiddleware(e)}removeVideoMiddleware(e){return a(this,be).removeMiddleware(e)}removeAllVideoMiddlewares(){return a(this,be).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return a(this,be).setVideoMiddlewareGlobalConfig(e)}destruct(){a(this,Ce).disableTrack(),a(this,be).disableTrack(),a(this,be).terminateMiddlewareWebWorker(),a(this,ls).disableScreenShare(),a(this,Ge).destruct()}async onDeviceChange(e,r){var n,o;if(this.emit("DEVICE_LIST_UPDATED",e),r||!a(this,rc))return;let i=!1;(n=e==null?void 0:e.added)==null||n.reverse().forEach(async c=>{var d;c&&!Tl(c)&&(c.kind==="audioinput"&&((d=this.audioTrack)==null?void 0:d.enabled)===!0?await this.setAudioDevice(c,{saveDevicePreference:!1}):c.kind==="audiooutput"&&(i=!0,await this.setSpeakerDevice(c,{saveDevicePreference:!1})))}),i||(o=e==null?void 0:e.removed)==null||o.forEach(async c=>{var d;if(c.kind==="audiooutput"&&((d=this.getCurrentDevices().speaker)==null?void 0:d.deviceId)===c.deviceId){const l=await this.getSpeakerDevices();(l==null?void 0:l.length)>0&&await this.setSpeakerDevice(l[0],{saveDevicePreference:!1})}})}removeAllTracks(){this.destruct()}removeAudioTrack(){a(this,Ce).disableTrack()}removeVideoTrack(){a(this,be).disableTrack(),a(this,be).terminateMiddlewareWebWorker()}async removeDocumentEventListeners(){document.removeEventListener("visibilitychange",this.onVisibilityChange)}}Ge=new WeakMap,Ce=new WeakMap,be=new WeakMap,br=new WeakMap,ls=new WeakMap,rc=new WeakMap,Ve=new WeakMap,jt([E.trace("MediaHandler.setupStreams")],Dt.prototype,"setupStreams",1),jt([E.trace("MediaHandler.enableAudio")],Dt.prototype,"enableAudio",1),jt([E.trace("MediaHandler.disableAudio")],Dt.prototype,"disableAudio",1),jt([E.trace("MediaHandler.setAudioDevice")],Dt.prototype,"setAudioDevice",1),jt([E.trace("MediaHandler.enableVideo")],Dt.prototype,"enableVideo",1),jt([E.trace("MediaHandler.disableVideo")],Dt.prototype,"disableVideo",1),jt([E.trace("MediaHandler.setVideoDevice")],Dt.prototype,"setVideoDevice",1),jt([E.trace("MediaHandler.updateVideoConstraints")],Dt.prototype,"updateVideoConstraints",1),jt([E.trace("MediaHandler.enableScreenShare")],Dt.prototype,"enableScreenShare",1),jt([E.trace("MediaHandler.disableScreenShare")],Dt.prototype,"disableScreenShare",1),jt([E.trace("MediaHandler.updateScreenshareConstraints")],Dt.prototype,"updateScreenshareConstraints",1),jt([E.trace("MediaHandler.destruct")],Dt.prototype,"destruct",1),jt([E.trace("MediaHandler.onDeviceChange")],Dt.prototype,"onDeviceChange",1);function Sl(s,t,e){switch(!0){case Pe.isChromiumBased():switch(t){case"NotAllowedError":return e.includes("by system")?"SYSTEM_DENIED":s==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case Pe.isSafari():switch(t){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case Pe.isFirefox():switch(t){case"NotFoundError":case"NotReadableError":return"SYSTEM_DENIED";case"NotAllowedError":return"DENIED";case"AbortError":default:return"COULD_NOT_START"}default:return"COULD_NOT_START"}}const HD=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function Tl(s){var e,r;const t=(e=s.label)==null?void 0:e.toLowerCase();return((r=Pe._bowser)==null?void 0:r.getOSName())==="macOS"&&t.includes("iphone")?!0:HD.some(i=>t==null?void 0:t.includes(i))}async function qD(s,t,e){if(!(t!=null&&t.length))return e;const r=s.getValue("logger"),i=new AudioContext,n=await Promise.all(t==null?void 0:t.map(d=>d(i))),o=i.createMediaStreamSource(new MediaStream([e])),c=i.createMediaStreamDestination();try{let d=o;for(let l=0;l<n.length;l+=1)d.connect(n[l]),d=n[l];d.connect(c)}catch(d){return r.error("getTransformedAudioTrack::middleware_execution_failed",{error:d}),e}return c.stream.getAudioTracks()[0]}const jD=s=>(t,e)=>(s.set(t,e),e),$v=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,Uv=536870912,Bv=Uv*2,GD=(s,t)=>e=>{const r=t.get(e);let i=r===void 0?e.size:r<Bv?r+1:0;if(!e.has(i))return s(e,i);if(e.size<Uv){for(;e.has(i);)i=Math.floor(Math.random()*Bv);return s(e,i)}if(e.size>$v)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;e.has(i);)i=Math.floor(Math.random()*$v);return s(e,i)},Fv=new WeakMap,WD=jD(Fv),yl=GD(WD,Fv),JD=s=>s.method!==void 0&&s.method==="call",KD=s=>s.error===null&&typeof s.id=="number",El=((s,t)=>{let e=null;return()=>{if(e!==null)return e;const r=new Blob([t],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(r);return e=s(i),setTimeout(()=>URL.revokeObjectURL(i)),e}})(s=>{const t=new Map([[0,()=>{}]]),e=new Map([[0,()=>{}]]),r=new Map,i=new Worker(s);return i.addEventListener("message",({data:l})=>{if(JD(l)){const{params:{timerId:u,timerType:h}}=l;if(h==="interval"){const g=t.get(u);if(typeof g=="number"){const v=r.get(g);if(v===void 0||v.timerId!==u||v.timerType!==h)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(h==="timeout"){const g=e.get(u);if(typeof g=="number"){const v=r.get(g);if(v===void 0||v.timerId!==u||v.timerType!==h)throw new Error("The timer is in an undefined state.")}else if(typeof g!="undefined")g(),e.delete(u);else throw new Error("The timer is in an undefined state.")}}else if(KD(l)){const{id:u}=l,h=r.get(u);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:g,timerType:v}=h;r.delete(u),v==="interval"?t.delete(g):e.delete(g)}else{const{error:{message:u}}=l;throw new Error(u)}}),{clearInterval:l=>{const u=yl(r);r.set(u,{timerId:l,timerType:"interval"}),t.set(l,u),i.postMessage({id:u,method:"clear",params:{timerId:l,timerType:"interval"}})},clearTimeout:l=>{const u=yl(r);r.set(u,{timerId:l,timerType:"timeout"}),e.set(l,u),i.postMessage({id:u,method:"clear",params:{timerId:l,timerType:"timeout"}})},setInterval:(l,u=0)=>{const h=yl(t);return t.set(h,()=>{l(),typeof t.get(h)=="function"&&i.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:h,timerType:"interval"}})}),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:h,timerType:"interval"}}),h},setTimeout:(l,u=0)=>{const h=yl(e);return e.set(h,l),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:h,timerType:"timeout"}}),h}}},`(()=>{"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})}}))})();`),Hv=s=>El().clearInterval(s),zD=s=>El().clearTimeout(s),qv=(s,t)=>El().setInterval(s,t),mp=Object.freeze(Object.defineProperty({__proto__:null,clearInterval:Hv,clearTimeout:zD,setInterval:qv,setTimeout:(s,t)=>El().setTimeout(s,t)},Symbol.toStringTag,{value:"Module"}));class YD{constructor(t){m(this,nn,void 0);m(this,ic,void 0);f(this,ic,t)}get logger(){return a(this,ic).getValue("logger")}terminateMiddlewareWebWorker(){if(a(this,nn))try{Hv(a(this,nn)),f(this,nn,void 0)}catch(t){this.logger.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}async getTransformedVideoTrack(t,e,r){if(!(t!=null&&t.length))return e;const i=document.createElement("canvas"),n=await Promise.all(t==null?void 0:t.map(g=>g({canvas:i,WorkerTimers:mp})));if(r.disablePerFrameCanvasRendering){const v=i.captureStream().getVideoTracks()[0];return Object.defineProperty(v,"originalSettings",{value:e.getSettings()}),v}const o=document.createElement("video"),c=new MediaStream;c.addTrack(e);const d=i.getContext("2d");o.srcObject=c,o.autoplay=!0,this.terminateMiddlewareWebWorker();const l=async()=>{if(e.enabled===!1||e.readyState==="ended"){this.terminateMiddlewareWebWorker(),o.remove(),i.remove();return}try{d.drawImage(o,0,0);for(let g=0;g<n.length;g+=1)typeof n[g]=="function"&&await n[g](i,d)}catch(g){this.logger.error("getTransformedVideoTrack::middleware_execution_failed",{error:g})}};try{o.play()}catch(g){}o.addEventListener("play",()=>{i.width=o.width||e.getSettings().width,i.height=o.width||e.getSettings().height,f(this,nn,qv(l,50))},!1);const h=i.captureStream().getVideoTracks()[0];return Object.defineProperty(h,"originalSettings",{value:e.getSettings()}),h}}nn=new WeakMap,ic=new WeakMap;const QD={qvga:{width:{ideal:320},height:{ideal:240},frameRate:{ideal:30}},vga:{width:{ideal:640},height:{ideal:480},frameRate:{ideal:30}},hd:{width:{ideal:1280},height:{ideal:720},frameRate:{ideal:30}},fhd:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},uhd:{width:{ideal:3840},height:{ideal:2160},frameRate:{ideal:30}}},XD=[[320,[{rid:"f",scaleResolutionDownBy:1,scalabilityMode:"L1T3"},{rid:"h",scaleResolutionDownBy:2,scalabilityMode:"L1T3"}]],[640,[{rid:"f",scaleResolutionDownBy:1,scalabilityMode:"L1T3"},{rid:"h",scaleResolutionDownBy:2,scalabilityMode:"L1T3"}]],[1280,[{rid:"f",scaleResolutionDownBy:1,scalabilityMode:"L1T3"},{rid:"h",scaleResolutionDownBy:2,scalabilityMode:"L1T3"},{rid:"q",scaleResolutionDownBy:4,scalabilityMode:"L1T3"}]],[1920,[{rid:"f",scaleResolutionDownBy:1,scalabilityMode:"L1T3"},{rid:"h",scaleResolutionDownBy:2,scalabilityMode:"L1T3"},{rid:"q",scaleResolutionDownBy:4,scalabilityMode:"L1T3"}]],[3840,[{rid:"f",scaleResolutionDownBy:1,scalabilityMode:"L1T3"},{rid:"h",scaleResolutionDownBy:2,scalabilityMode:"L1T3"},{rid:"q",scaleResolutionDownBy:4,scalabilityMode:"L1T3"}]]],ZD=(s,t)=>{var d,l,u;const e=(d=s==null?void 0:s.getValue("overrides"))==null?void 0:d.simulcastConfig;if((l=e==null?void 0:e.encodings)!=null&&l.length)return e.encodings;const r="getSettings"in t&&t.getSettings().width||"getConstraints"in t&&t.getConstraints().width||"originalSettings"in t&&((u=t.originalSettings)==null?void 0:u.width),i=XD,n=i.map(([h])=>h).sort((h,g)=>h-g);let o=Number.MAX_VALUE,c=0;return n.forEach((h,g)=>{Math.abs(h-r)<o&&(o=Math.abs(h-r),c=g)}),i[c][1]};var _e=(s=>(s.WEBCAM="webcam",s.WEBCAM_BACKUP="webcam_backup",s.MIC="mic",s.SCREENSHARE_VIDEO="screenshare_video",s.SCREENSHARE_AUDIO="screenshare_audio",s))(_e||{});const e1=nC(),Kn=Ls(e1.config.media);function t1(s){var e,r;const t={};return s.audio&&(t.audio={enableStereo:(e=s.audio.enableStereo)!=null?e:!1,enableHighBitrate:(r=s.audio.enableHighBitrate)!=null?r:!1}),t.video=s.video.quality,t}class s1{constructor(t,e){m(this,an,void 0);m(this,tu,void 0);p(this,"getScreenShareConstraints",()=>{var l,u,h,g,v,y,k,I,D;const t=(l=a(this,an))==null?void 0:l.screenshare,e=(h=(u=t==null?void 0:t.width)==null?void 0:u.max)!=null?h:1920,r=(v=(g=t==null?void 0:t.height)==null?void 0:g.max)!=null?v:1080,i=(k=(y=t==null?void 0:t.frameRate)==null?void 0:y.max)!=null?k:5,n=(D=(I=t==null?void 0:t.frameRate)==null?void 0:I.ideal)!=null?D:5,o=t==null?void 0:t.displaySurface,c=t==null?void 0:t.selfBrowserSurface;let d={width:{max:e},height:{max:r},frameRate:{ideal:n,max:i}};return o!==void 0&&["monitor","browser","window"].includes(o)&&(d={...d,displaySurface:o}),c!==void 0&&(d={...d,selfBrowserSurface:c}),{audio:!0,video:d}});p(this,"getAudioConstraints",t=>{var n,o,c,d,l,u,h;const e={},r=(n=a(this,an))==null?void 0:n.audio,i=r!=null&&r.enableStereo?2:1;return Pe.isFirefox()||Pe.isWebKitBased()?(e.audio={deviceId:t,autoGainControl:(o=r==null?void 0:r.autoGainControl)!=null?o:!0,echoCancellation:(c=r==null?void 0:r.echoCancellation)!=null?c:!0,noiseSuppression:(d=r==null?void 0:r.noiseSupression)!=null?d:!0,channelCount:i},e):(e.audio={autoGainControl:(l=r==null?void 0:r.autoGainControl)!=null?l:!0,echoCancellation:(u=r==null?void 0:r.echoCancellation)!=null?u:!0,noiseSuppression:(h=r==null?void 0:r.noiseSupression)!=null?h:!0,channelCount:i},t&&(e.audio.deviceId={exact:t}),e)});p(this,"getVideoConstraints",t=>{var o,c,d;const e={},r=(o=a(this,an))==null?void 0:o.video,i=Ek(QD);let n=i.vga;if(typeof r=="string"){const l=i[r];l&&(n=l)}else r!==void 0&&(n.height.ideal=r.height.ideal,n.width.ideal=r.width.ideal,n.frameRate.ideal=(d=(c=r.frameRate)==null?void 0:c.ideal)!=null?d:30);return e.video=n,typeof e.video=="boolean"||(t?e.video.deviceId={exact:t}:e.video.facingMode="user"),e});f(this,tu,t),f(this,an,e)}getUpdatedVideoConstraints(t){return t}}an=new WeakMap,tu=new WeakMap;class gp extends Error{constructor(e,r,i){super(r);p(this,"constraints");p(this,"name");this.name=e,this.constraints=i}}class r1{constructor(){p(this,"permissions");this.permissions={audio:"NOT_REQUESTED",video:"NOT_REQUESTED",screenshare:"NOT_REQUESTED"}}async getAudioInputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="audioinput")}async getVideoInputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="videoinput")}async getAudioOutputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="audiooutput")}}var i1=Object.defineProperty,n1=Object.getOwnPropertyDescriptor,bs=(s,t,e,r)=>{for(var i=r>1?void 0:r?n1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&i1(t,e,i),i};let Gt=(KS=class extends r1{constructor(t,e){super();m(this,Ta,void 0);m(this,us,void 0);m(this,Xe,void 0);f(this,Xe,t),f(this,us,new s1(t,e)),f(this,Ta,new AbortController)}get telemetry(){return a(this,Xe).getValue("telemetry")}get logger(){return a(this,Xe).getValue("logger")}get constraintsBuilder(){return a(this,us)}async destruct(){var t;(t=a(this,Ta))==null||t.abort()}handlePermissionErrors(t,e){const r=Sl(t,e.name,e.message);return this.permissions[t]=r,a(this,Xe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_ERROR,{message:r,constraints:e.constraints,kind:t}),r}async getAudioAndVideoTrack(t,e){var r,i,n,o;try{const c=await this.getAudioInputDevices(),d=await this.getVideoInputDevices(),l=!!(c!=null&&c.find(D=>D.deviceId===t));let u;t&&l?u=t:c&&((r=c[0])!=null&&r.deviceId)&&(u=(i=c[0])==null?void 0:i.deviceId);const h=!!(d!=null&&d.find(D=>D.deviceId===e));let g;e&&h?g=e:d&&((n=d[0])!=null&&n.deviceId)&&(g=(o=d[0])==null?void 0:o.deviceId);const v={audio:a(this,us).getAudioConstraints(u).audio,video:a(this,us).getVideoConstraints(g).video};this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(v)});const y=await navigator.mediaDevices.getUserMedia(v);this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(v)});const k=y.getAudioTracks()[0];let I=y.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",I.label.includes("OBS Virtual")){const N=(await this.getVideoInputDevices()).find(B=>B.label.includes("OBS Virtual"));I=await this.getVideoTrack(N.deviceId)}return a(this,Xe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),a(this,Xe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:k,videoTrack:I}}catch(c){throw this.logger.error("WebMediaInterface.getAudioAndVideoTrack",{error:c}),new C("Couldnt fetch audio and video track","1605")}}async getAudioTrack(t,e){var c,d;let r=await this.getAudioInputDevices();if(!(r!=null&&r.length))throw this.permissions.audio="NO_DEVICES_AVAILABLE",a(this,Xe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new C("No audio devices available","1606");const i=!!(r!=null&&r.find(l=>l.deviceId===e));let n;e&&i?n=e:(c=r[0])!=null&&c.deviceId&&(n=(d=r[0])==null?void 0:d.deviceId);const o=async l=>{let u;try{r=r.filter(g=>g.deviceId!==l),u=a(this,us).getAudioConstraints(l),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(u)});const[h]=(await navigator.mediaDevices.getUserMedia(u)).getAudioTracks();return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(u)}),h}catch(h){const g=Sl("audio",h.name,h.message),v=new gp(h.name,h.message,u);if(g==="COULD_NOT_START"){const y=r.shift();if(!y)throw v;this.logger.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(u),error:h});const k=a(this,us).getAudioConstraints(y.deviceId);return this.logger.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(k)}),o(y.deviceId)}throw v}};try{const l=await o(n);return l.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",a(this,Xe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),l}catch(l){throw l.constraints&&this.handlePermissionErrors("audio",l),new C(l.message,"1601")}}async getVideoTrack(t){var c,d,l;const e=(c=await this.getCurrentDeviceLabel(t))==null?void 0:c.includes("OBS Virtual"),r=await this.getVideoInputDevices();if(!(r!=null&&r.length))throw this.permissions.video="NO_DEVICES_AVAILABLE",a(this,Xe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new C("No video devices available","1607");const i=!!(r!=null&&r.find(u=>u.deviceId===t));let n;t&&i?n=t:(d=r[0])!=null&&d.deviceId&&(n=(l=r[0])==null?void 0:l.deviceId);const o=async u=>{try{let h=u;const{video:g}=h;e&&typeof g!="boolean"&&(h={video:{deviceId:g.deviceId}}),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(h)});const[v]=(await navigator.mediaDevices.getUserMedia(h)).getVideoTracks();if(e&&typeof g!="boolean"&&typeof g.width=="object"){const{width:y,height:k}=v.getSettings(),{ideal:I}=g.width;v.applyConstraints({width:{ideal:I},height:{ideal:Math.floor(k*I/y)},frameRate:g.frameRate})}return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(h)}),v}catch(h){const g=Sl("video",h.name,h.message),v=new gp(h.name,h.message,u);if(g==="COULD_NOT_START"){const y=r.shift();if(!y)throw v;this.logger.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(u),error:h});const k=a(this,us).getVideoConstraints(y.deviceId);return this.logger.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(k)}),o({video:k.video})}throw v}};try{const u=a(this,us).getVideoConstraints(n),h=await o(u);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",a(this,Xe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),h}catch(u){throw u.constraints&&this.handlePermissionErrors("video",u),new C(u.message,"1602")}}async getScreenShareTracks(){const t=async e=>{try{this.logger.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),a(this,Xe).getValue("callstats").screenShareRequested();const r=await navigator.mediaDevices.getDisplayMedia(e);return this.logger.info("getDisplayMediaWithoutTimeout::received_display_media",{constraints:JSON.stringify(e)}),r}catch(r){const i=Sl("video",r.name,r.message),n=new gp(r.name,r.message,e),o={video:!0};if(I_(e,o))throw n;if(i==="COULD_NOT_START")return t(o);throw n}};try{const e=a(this,us).getScreenShareConstraints(),r=await t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",a(this,Xe).getValue("peerSessionStore").emit(P.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 C(e.message,"1612")}}async getCurrentDeviceLabel(t){const e=await this.getDevice(t||"default");return e==null?void 0:e.label}async enumerateDevicesWithExternalFirst(){const t=await navigator.mediaDevices.enumerateDevices(),e=i=>{var o;const n=((o=i.label)==null?void 0:o.toLowerCase())||"";return Tl(i)?4:n.includes("airpods")||n.includes("airdopes")||n.includes("bluetooth")||n.includes("wireless")||n.includes("headphones")||n.includes("headset")&&!n.includes("earpiece")||n.includes("earbuds")||n.includes("usb")||n.includes("external")?0:i.deviceId==="default"||n.includes("default")?1:n.includes("built-in")||n.includes("internal")?2:3},r=i=>{var o;if(i.kind!=="videoinput")return!1;const n=((o=i.label)==null?void 0:o.toLowerCase())||"";return n.includes("front")||n.includes("user")||n.includes("selfie")?!0:!(n.includes("back")||n.includes("rear")||n.includes("environment"))};return t.sort((i,n)=>{var u,h;const o=e(i),c=e(n);if(o!==c)return o-c;const d=i.deviceId==="default"||((u=i.label)==null?void 0:u.toLowerCase().includes("default")),l=n.deviceId==="default"||((h=n.label)==null?void 0:h.toLowerCase().includes("default"));if(d&&!l)return-1;if(!d&&l)return 1;if(i.kind==="videoinput"&&n.kind==="videoinput"){const g=r(i),v=r(n);if(g&&!v)return-1;if(!g&&v)return 1}return 0})}async getAvailableDevices(){try{return await this.enumerateDevicesWithExternalFirst()||[]}catch(t){return this.logger.error("enumerate_devices_failed",{error:t}),[]}}async getAvailableDevicesByKind(t){try{return(await this.enumerateDevicesWithExternalFirst()).filter(({kind:e})=>t===e)}catch(e){throw this.logger.error("enumerate_devices_failed",{error:e}),new C("Failed to get available devices by kind","1609")}}async getDevice(t){try{return(await this.enumerateDevicesWithExternalFirst()).filter(r=>r.deviceId===t)[0]}catch(e){throw this.logger.error("enumerate_devices_failed",{error:e}),new C("Failed to get device","1609")}}async onDeviceChange(t){if(Pe.supportsDeviceChangeEvent()){let e=await this.getAvailableDevices();navigator.mediaDevices.addEventListener("devicechange",async r=>{var l,u;const i=h=>`${h.kind}-${h.label}-${h.deviceId}-${h.groupId}`,n=new Set(e.map(h=>i(h))),o=await this.getAvailableDevices(),c=new Set(o.map(h=>i(h))),d={added:o.filter(h=>!n.has(i(h))),removed:e.filter(h=>!c.has(i(h))),devices:o};if(e=o,(l=d.added)!=null&&l.length||(u=d.removed)!=null&&u.length){this.logger.info("repopulated_full_device_list",{devices:JSON.stringify(o)});const h=[...d.added,...d.removed];h.some(g=>g.kind==="audioinput")&&a(this,Xe).getValue("callstats").devices("AUDIO",o==null?void 0:o.filter(g=>g.kind==="audioinput")),h.some(g=>g.kind==="videoinput")&&a(this,Xe).getValue("callstats").devices("VIDEO",o==null?void 0:o.filter(g=>g.kind==="videoinput")),h.some(g=>g.kind==="audiooutput")&&a(this,Xe).getValue("callstats").devices("SPEAKER",o==null?void 0:o.filter(g=>g.kind==="audiooutput")),t(r,d,!1)}},{signal:a(this,Ta).signal})}}},Ta=new WeakMap,us=new WeakMap,Xe=new WeakMap,KS);bs([E.trace("WebMediaInterface.destruct")],Gt.prototype,"destruct",1),bs([E.trace("WebMediaInterface.handlePermissionErrors")],Gt.prototype,"handlePermissionErrors",1),bs([E.trace("WebMediaInterface.getAudioAndVideoTrack")],Gt.prototype,"getAudioAndVideoTrack",1),bs([E.trace("WebMediaInterface.getAudioTrack")],Gt.prototype,"getAudioTrack",1),bs([E.trace("WebMediaInterface.getVideoTrack")],Gt.prototype,"getVideoTrack",1),bs([E.trace("WebMediaInterface.getScreenShareTracks")],Gt.prototype,"getScreenShareTracks",1),bs([E.trace("WebMediaInterface.getAvailableDevices")],Gt.prototype,"getAvailableDevices",1),bs([E.trace("WebMediaInterface.getAvailableDevicesByKind")],Gt.prototype,"getAvailableDevicesByKind",1),bs([E.trace("WebMediaInterface.getDevice")],Gt.prototype,"getDevice",1),bs([E.trace("WebMediaInterface.onDeviceChange")],Gt.prototype,"onDeviceChange",1),Gt=bs([pt("1600")],Gt);const jv=Gt,$i={setItem:(s,t,e)=>{try{localStorage.setItem(s,t)}catch(r){e==null||e.error("LocalStorage::setItem::crashed",{error:r,localStorage:{key:s,value:t}})}},getItem:(s,t)=>{try{return localStorage.getItem(s)}catch(e){t==null||t.error("LocalStorage::getItem::crashed",{error:e,localStorage:{key:s}})}return null}},a1=(s=0)=>new Promise(t=>setTimeout(t,s)),o1=(s,t,e)=>{const r=typeof e=="number"?e:250,i=s.createMediaStreamSource(t),n=s.createAnalyser();n.fftSize=2048,i.connect(n);const o=new Uint8Array(n.fftSize);let c=!1;setTimeout(()=>{c=!0},r);function d(){return c?Promise.resolve(!0):(n.getByteTimeDomainData(o),o.some(l=>l!==128&&l!==0)?Promise.resolve(!1):a1().then(d))}return d().then(l=>(i.disconnect(),l),l=>{throw i.disconnect(),l})},c1=typeof AudioContext!="undefined"?AudioContext:null;class fp{constructor(t){p(this,"_AudioContext");p(this,"audioContext");p(this,"_audioContextRefContainers");const e={AudioContext:c1,...t};Object.defineProperties(this,{_AudioContext:{value:e.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:fp}})}getOrCreate(t){if(!this._audioContextRefContainers.has(t)&&(this._audioContextRefContainers.add(t),this._AudioContext&&!this.audioContext))try{this.audioContext=new this._AudioContext}catch(e){}return this.audioContext}release(t){this._audioContextRefContainers.has(t)&&(this._audioContextRefContainers.delete(t),!this._audioContextRefContainers.size&&this.audioContext&&(this.audioContext.close(),this.audioContext=null))}}const Gv=new fp,d1=3,l1=250;function u1(s){const t={},e=Gv.getOrCreate(t);let r=d1;function i(){return r-=1,o1(e,s.srcObject,l1).then(n=>n?r>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{Gv.release(t)})}async function Wv(s,t){const e=new Audio,r=new MediaStream;r.addTrack(t),e.srcObject=r;let i=!1;try{const n=e.play();n&&await n,i=await u1(e),i&&s.info("checkIfAudioTrackIsSilent::silence_detected")}catch(n){s.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:n})}finally{e.pause(),e.remove()}return i}var h1=Object.defineProperty,p1=Object.getOwnPropertyDescriptor,Jv=(s,t,e,r)=>{for(var i=r>1?void 0:r?p1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&h1(t,e,i),i};let bl=class extends Bn{constructor(t,e,r,i){var o;const n=t.getValue("logger");super(n);p(this,"constructorName",this.constructor.name);p(this,"userSelectedDevice");p(this,"mediaInterface");p(this,"isNonPreferredDevice");p(this,"_mediaTrack");p(this,"transformedMediaTrack");p(this,"middlewares",[]);p(this,"currentDevice");p(this,"userPreferredDeviceKey",`Realtimekit::${this.constructorName}::UserDeviceID`);p(this,"setUserPreferredDevice",t=>$i.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>$i.getItem(this.userPreferredDeviceKey,this.logger));p(this,"isCustomTrack",!1);p(this,"context");this.context=t,this.mediaInterface=e,r&&this.setMediaTrack(r),this.userSelectedDevice=(o=this.getUserPreferredDevice())!=null?o:void 0,this.isNonPreferredDevice=i,this.onTrackEnded=this.onTrackEnded.bind(this),this.onTrackMuted=this.onTrackMuted.bind(this)}get telemetry(){return this.context.getValue("telemetry")}disableTrack(){var t,e;this.removeMediaTrackListeners(),this.isCustomTrack||(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}async setMediaTrack(t,e=!1){const r=i=>{this.logger.error(`${this.constructorName}.setMediaTrack.error`,{error:i})};try{this.disableTrack()}catch(i){r(i)}this._mediaTrack=await this.conditionallyChangeTrack(t,e),await this.setTransformedTrack();try{this.addMediaTrackListeners(),await this.setCurrentDevice()}catch(i){r(i)}}get trackEnabled(){return!!this.mediaTrack&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}muteTrack(){if(!this.mediaTrack){this.logger.warn("BaseMediaHandler.muteTrack Tried muting with no track present");return}this.transformedMediaTrack&&(this.transformedMediaTrack.enabled=!1),this.mediaTrack.enabled=!1}async unmuteTrack(){try{this.mediaTrack?this.mediaTrack.enabled=!0:await this.enableTrack(!1)}catch(t){throw this.logger.error(`${this.constructorName}.unmuteTrack.error`,{error:t}),this.disableTrack(),new C("Failed to unmute track","1611")}}getCurrentDeviceId(){var e;const{kind:t}=this.mediaTrack;switch(t){case"audio":{const{deviceId:r}=this.mediaTrack.getSettings();if(r)return r;const i=this.mediaTrack.getConstraints();return this.userSelectedDevice?(i&&typeof i.deviceId=="object"&&"exact"in i.deviceId?i.deviceId.exact:i.deviceId)||((e=i==null?void 0:i.advanced)==null?void 0:e[0].deviceId)||"default":this.mediaTrack.getSettings().deviceId}default:return this.mediaTrack.getSettings().deviceId}}async setCurrentDevice(){var e;if(!this.mediaTrack){this.currentDevice=void 0;return}const t=this.getCurrentDeviceId();((e=this.currentDevice)==null?void 0:e.deviceId)!==t&&(this.currentDevice=await this.mediaInterface.getDevice(t))}async setDevice(t,{saveDevicePreference:e}){if(!t)throw this.logger.warn(`${this.constructorName}.setDevice No device received`),new C("No device received!","1603");this.userSelectedDevice=t.deviceId,e&&this.setUserPreferredDevice(t.deviceId),await this.onSetDevice(t)}async addMiddleware(t){if(Pe.isWebKitBased()&&!(Pe.isSafari()&&q_.test(Pe.getVersion())))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&&await this.setTransformedTrack(),{success:!0,message:"Successfully added the middleware."}}catch(e){return this.logger.error("While adding middleware",{error:e}),this.removeMiddleware(t),{success:!1,message:e==null?void 0:e.message}}}async removeMiddleware(t){const e=this.middlewares.indexOf(t,0);if(e>-1)try{return this.middlewares.splice(e,1),await this.setTransformedTrack(!0),{success:!0,message:"Successfully removed the middleware."}}catch(r){return this.logger.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."}}async removeAllMiddlewares(){var t;if((t=this.middlewares)!=null&&t.length)try{return this.middlewares=[],await this.setTransformedTrack(!0),{success:!0,message:"Successfully removed all the middlewares."}}catch(e){return this.logger.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&&(this.logger.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&&(this.logger.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}`),this.logger.info(`${this.constructorName}.removeMediaTrackListeners`),this.mediaTrack.removeEventListener("ended",this.onTrackEnded),this.mediaTrack.removeEventListener("mute",this.onTrackMuted))}};Jv([E.trace("BaseMediaHandler.unmuteTrack")],bl.prototype,"unmuteTrack",1),bl=Jv([pt("1600")],bl);const Kv=bl;var m1=Object.defineProperty,g1=Object.getOwnPropertyDescriptor,vp=(s,t,e,r)=>{for(var i=r>1?void 0:r?g1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&m1(t,e,i),i};const Sp="[Realtimekit]nonSilentDeviceLabels";class wl extends Kv{async onSetDevice(t){if(!t)throw this.logger.warn("AudioMediaHandler.setDevice No device received"),new C("No device received!","1603");if(t.kind!=="audioinput")throw this.logger.warn("AudioMediaHandler.setDevice Received non audio device"),new C("Non audio device received while setting device!","1603");try{const e=this.trackEnabled;this.disableTrack(),await this.setMediaTrack(await this.mediaInterface.getAudioTrack(!e,this.userSelectedDevice))}catch(e){throw this.logger.error("AudioMediaHandler.setDevice.error",{error:e}),this.disableTrack(),new C(e.message,"1604")}}async enableTrack(t,e){if(this.trackEnabled){this.logger.warn("AudioMediaHandler.enableTrack Track already enabled!");return}if(e){this.isCustomTrack=!0,await this.setMediaTrack(e,!0);return}this.isCustomTrack=!1;const r=await this.mediaInterface.getAudioTrack(t,this.userSelectedDevice);await this.setMediaTrack(r)}async setTransformedTrack(t){var e;if(!t&&!((e=this.middlewares)!=null&&e.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=await qD(this.context,this.middlewares,this.mediaTrack),this.emit("trackChanged")}catch(r){this.logger.error("AudioMediaHandler.setTransformedTrack",{error:r}),this.transformedMediaTrack=this.mediaTrack}}async onTrackEnded(){this.logger.info("AudioMediaHandler.TrackEnded"),this.emit("trackEnded");const t=this.mediaTrack.enabled;this.disableTrack(),await this.enableTrack(!t),await this.setTransformedTrack(),this.emit("trackChanged")}onTrackMuted(){this.logger.info("AudioMediaHandler.TrackMuted"),this.emit("trackMuted")}async conditionallyChangeTrack(t,e=!1){var d;if(!t||this.userSelectedDevice||e)return t;let r=t;const i=await this.mediaInterface.getAudioInputDevices(),n=this.isNonPreferredDevice?i.filter(l=>l&&!this.isNonPreferredDevice(l)):i;if(!(n!=null&&n.length))return r;n.find(l=>l.deviceId===t.getSettings().deviceId)||(r.stop(),this.logger.info("localmediahandler::setupstreams::found_audio_non_preferred"),r=await this.mediaInterface.getAudioTrack(!1,n[0].deviceId));const o=JSON.parse($i.getItem(Sp,this.logger));if(o!=null&&o.devices.some(l=>l.label===r.label))return r;if(!await Wv(this.logger,r)){const l=(d=o==null?void 0:o.devices.concat({label:r.label}))!=null?d:[{label:r.label}];return $i.setItem(Sp,JSON.stringify({devices:l}),this.logger),r}this.logger.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const c=r.getSettings().deviceId;return n.filter(l=>l.deviceId!==c).some(async l=>{var u;if(r=await this.mediaInterface.getAudioTrack(!1,l.deviceId),!await Wv(this.logger,r)){const h=(u=o==null?void 0:o.devices.concat({label:r.label}))!=null?u:[{label:r.label}];return $i.setItem(Sp,JSON.stringify({devices:h}),this.logger),this.logger.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return this.logger.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1}),r}}vp([E.trace("AudioMediaHandler.setTransformedTrack")],wl.prototype,"setTransformedTrack",1),vp([E.trace("AudioMediaHandler.onTrackEnded")],wl.prototype,"onTrackEnded",1),vp([E.trace("AudioMediaHandler.conditionallyChangeTrack")],wl.prototype,"conditionallyChangeTrack",1);const f1=wl;class v1{constructor(t,e){m(this,on,void 0);p(this,"currentDevice");p(this,"userPreferredDeviceKey","Realtimekit::speaker::UserDeviceID");p(this,"logger");p(this,"setUserPreferredDevice",t=>$i.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>$i.getItem(this.userPreferredDeviceKey,this.logger));f(this,on,e),this.logger=t.getValue("logger")}async setPreferredSpeaker(){const t=this.getUserPreferredDevice(),e=await a(this,on).getAudioOutputDevices(),r=e==null?void 0:e.find(i=>i.deviceId===t);await this.setupSpeaker(r,{saveDevicePreference:!1})}async setupSpeaker(t,{saveDevicePreference:e}){var n,o;if(!(a(this,on)instanceof jv))return;let r=t;if(t||([r]=(await a(this,on).getAvailableDevicesByKind("audiooutput")).filter(d=>!Tl(d))),!r)throw new C("No speaker found","1608");if(((n=this.currentDevice)==null?void 0:n.deviceId)===r.deviceId)return;e&&this.setUserPreferredDevice(r.deviceId),this.currentDevice=r;const i=document.querySelectorAll("audio");(o=i[0])!=null&&o.setSinkId&&i.forEach(async c=>{if(typeof c.sinkId!="undefined"&&this.currentDevice.deviceId&&c.sinkId!==this.currentDevice.deviceId)try{await c.setSinkId(this.currentDevice.deviceId)}catch(d){}})}}on=new WeakMap;const S1=v1;class T1 extends Bn{constructor(e,r){const i=e.getValue("logger");super(i);p(this,"mediaInterface");p(this,"audioMediaTrack");p(this,"videoMediaTrack");p(this,"previousAudioMediaTrack");p(this,"previousVideoMediaTrack");m(this,nc,void 0);f(this,nc,e),this.mediaInterface=r,this.onTrackEnded=this.onTrackEnded.bind(this)}get trackEnabled(){return!!this.videoMediaTrack}async enableScreenShare(){var e,r,i,n,o,c;try{const{audioTrack:d,videoTrack:l}=await this.mediaInterface.getScreenShareTracks();this.audioMediaTrack=d,this.videoMediaTrack=l,this.addMediaTrackListeners(),this.mediaInterface.permissions&&this.mediaInterface.permissions.screenshare!=="ACCEPTED"&&(this.mediaInterface.permissions.screenshare="ACCEPTED",a(this,nc).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"})),(this.previousAudioMediaTrack||this.previousVideoMediaTrack)&&((e=this.previousAudioMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded),(r=this.previousVideoMediaTrack)==null||r.removeEventListener("ended",this.onTrackEnded),(i=this.previousAudioMediaTrack)==null||i.removeEventListener("mute",this.onTrackEnded),(n=this.previousVideoMediaTrack)==null||n.removeEventListener("mute",this.onTrackEnded),(o=this.previousAudioMediaTrack)==null||o.stop(),(c=this.previousVideoMediaTrack)==null||c.stop()),this.previousAudioMediaTrack=this.audioMediaTrack,this.previousVideoMediaTrack=this.videoMediaTrack}catch(d){}}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,this.previousAudioMediaTrack=void 0,this.previousVideoMediaTrack=void 0}async updateConstraints(e){if(!this.videoMediaTrack)throw new C("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new C("update constraints not supported for non web clients","1100",this.logger);try{this.videoMediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),this.addMediaTrackListeners()}catch(i){this.logger.error("ScreenShareHandler.updateConstraints.error",{error:i})}}addMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.addEventListener("ended",this.onTrackEnded),Pe.isWebKitBased()&&((r=this.videoMediaTrack)==null||r.addEventListener("mute",this.onTrackEnded))}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")}}nc=new WeakMap;const y1=T1;var E1=Object.defineProperty,b1=Object.getOwnPropertyDescriptor,Pl=(s,t,e,r)=>{for(var i=r>1?void 0:r?b1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&E1(t,e,i),i};class Co extends Kv{constructor(e,r,i,n){super(e,r,i,n);m(this,ya,void 0);m(this,ac,{disablePerFrameCanvasRendering:!1});f(this,ya,new YD(e))}async onSetDevice(e){if(!e)throw this.logger.warn("VideoMediaHandler.setDevice No device received"),new C("No device received!","1603");if(e.kind!=="videoinput")throw this.logger.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new C("Non video device received while setting video device!","1603");if(!(this.mediaTrack&&this.mediaTrack.enabled)){this.logger.warn("VideoMediaHandler.setDevice Tried switching device with video disabled",{devices:[e]}),this.currentDevice=e;return}try{this.disableTrack(),await this.setMediaTrack(await this.mediaInterface.getVideoTrack(this.userSelectedDevice))}catch(r){throw this.logger.error("VideoMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new C("Failed to change device","1600",this.logger)}}async enableTrack(e,r){if(this.trackEnabled){this.logger.warn("VideoMediaHandler.enableTrack Track already enabled!");return}if(r){this.isCustomTrack=!0,await this.setMediaTrack(r,!0);return}this.isCustomTrack=!1;const i=await this.mediaInterface.getVideoTrack(this.userSelectedDevice);await this.setMediaTrack(i)}async setTransformedTrack(e){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=await a(this,ya).getTransformedVideoTrack(this.middlewares,this.mediaTrack,a(this,ac)),this.emit("trackChanged")}catch(i){this.logger.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}}async setVideoMiddlewareGlobalConfig(e){f(this,ac,e)}async updateConstraints(e){if(!this._mediaTrack)throw new C("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new C("update constraints not supported for non web clients","1100",this.logger);try{this._mediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),await this.setTransformedTrack(),this.addMediaTrackListeners(),await this.setCurrentDevice()}catch(i){this.logger.error("VideoMediaHandler.updateConstraints.error",{error:i})}}terminateMiddlewareWebWorker(){a(this,ya).terminateMiddlewareWebWorker()}async onTrackEnded(){this.logger.info("VideoMediaHandler.TrackEnded"),this.disableTrack(),this.emit("trackEnded")}onTrackMuted(){this.logger.info("VideoMediaHandler.TrackMuted"),this.emit("trackMuted")}async conditionallyChangeTrack(e,r=!1){if(!e||this.userSelectedDevice||r)return e;let i=e;const n=await this.mediaInterface.getVideoInputDevices(),o=this.isNonPreferredDevice?n.filter(c=>!this.isNonPreferredDevice(c)):n;return!(o!=null&&o.length)||window.FAST_RTK||o.find(c=>c.deviceId===e.getSettings().deviceId)||(i.stop(),this.logger.info("localmediahandler::setupstreams::found_video_non_preferred"),i=await this.mediaInterface.getVideoTrack(o[0].deviceId)),i}}ya=new WeakMap,ac=new WeakMap,Pl([E.trace("VideoMediaHandler.setTransformedTrack")],Co.prototype,"setTransformedTrack",1),Pl([E.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],Co.prototype,"setVideoMiddlewareGlobalConfig",1),Pl([E.trace("VideoMediaHandler.onTrackEnded")],Co.prototype,"onTrackEnded",1),Pl([E.trace("VideoMediaHandler.conditionallyChangeTrack")],Co.prototype,"conditionallyChangeTrack",1);const w1=Co,zv=Ls(Nh()),ba=class{constructor(t){m(this,bt,void 0);m(this,cn,void 0);m(this,oc,void 0);m(this,Ea,void 0);if(!t)throw new C("Could not load preset.","0904");f(this,bt,t.config),f(this,oc,t.name),f(this,cn,t.ui||Ls(Nh().ui)),f(this,Ea,t.permissions.plugins.config)}static fromResponse(t){return new ba(t)}static default(){return new ba(zv)}static init(t,e=!0){return!t||e?new ba(zv):new ba(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:a(this,cn).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return a(this,bt).viewType}get livestreamViewerQualities(){return a(this,bt).livestreamViewerQualities||[]}get maxVideoStreams(){return a(this,bt).maxVideoStreams}get maxScreenShareCount(){return a(this,bt).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(a(this,Ea)).filter(t=>a(this,Ea)[t].disabled)}get designTokens(){return a(this,cn).designTokens}get configDiff(){return a(this,cn).configDiff}get isSimulcastEnabled(){var t,e,r,i;return(i=(r=(e=(t=a(this,bt))==null?void 0:t.media)==null?void 0:e.video)==null?void 0:r.simulcast)!=null?i:!1}get mediaConstraints(){var t,e,r,i,n,o,c,d,l,u,h,g,v,y,k,I,D,N,B,U,j,Z,re,F;return{audio:{enableStereo:(i=(r=(e=(t=a(this,bt))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?i:Kn.audio.enableStereo,enableHighBitrate:(d=(c=(o=(n=a(this,bt))==null?void 0:n.media)==null?void 0:o.audio)==null?void 0:c.enableHighBitrate)!=null?d:Kn.audio.enableHighBitrate},video:{quality:(g=(h=(u=(l=a(this,bt))==null?void 0:l.media)==null?void 0:u.video)==null?void 0:h.quality)!=null?g:Kn.video.quality,frameRate:(I=(k=(y=(v=a(this,bt))==null?void 0:v.media)==null?void 0:y.video)==null?void 0:k.frameRate)!=null?I:Kn.video.frameRate},screenshare:{quality:(U=(B=(N=(D=a(this,bt))==null?void 0:D.media)==null?void 0:N.screenshare)==null?void 0:B.quality)!=null?U:Kn.screenshare.quality,frameRate:(F=(re=(Z=(j=a(this,bt))==null?void 0:j.media)==null?void 0:Z.screenshare)==null?void 0:re.frameRate)!=null?F:Kn.screenshare.frameRate}}}get name(){return a(this,oc)}};let Tp=ba;bt=new WeakMap,cn=new WeakMap,oc=new WeakMap,Ea=new WeakMap;var P1=Object.defineProperty,k1=Object.getOwnPropertyDescriptor,Yv=(s,t,e,r)=>{for(var i=r>1?void 0:r?k1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&P1(t,e,i),i};class yp extends Bt{constructor(e,r){const i=e.getValue("logger");super(i);m(this,wa,void 0);p(this,"state","IDLE");p(this,"playbackUrl");p(this,"ingestionCredentials");p(this,"viewerCount");m(this,cc,void 0);f(this,wa,r),f(this,cc,e),this.viewerCount=0}get telemetry(){return a(this,cc).getValue("telemetry")}setLivestreamState(e){const r=this.state;this.state=e,r!==e&&this.emitCurrentLivestreamState()}emitCurrentLivestreamState(){this.emit("livestreamUpdate",this.state)}async start(e={manualIngestion:!1}){if(!a(this,wa).permissions.canLivestream)throw this.logger.error("Livestream::start::permission_denied"),new C("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const r=Ht(),{playbackUrl:i,ingestionCredentials:n}=await r.startLivestreaming(e);this.playbackUrl=i,this.ingestionCredentials=n,e!=null&&e.manualIngestion&&this.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}catch(r){throw this.logger.error("Recording::stop::livestream_failed_to_start",{error:r}),this.setLivestreamState("IDLE"),new C("Error while starting livestream","1900",this.logger)}}async stop(){if(!a(this,wa).permissions.canLivestream)throw this.logger.error("Livestream::stop::permission_denied"),new C("User does not have permission to stop livestreaming","1901");if(this.state!=="LIVESTREAMING"&&this.state!=="WAITING_ON_MANUAL_INGESTION")throw this.logger.error("Livestream::stop::inconsistent_state"),new C("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),await Ht().stopLivestreaming()}catch(e){throw this.logger.error("Livestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new C("Error while stopping livestream","1900",this.logger)}}}wa=new WeakMap,cc=new WeakMap,Yv([E.trace("livestream.start")],yp.prototype,"start",1),Yv([E.trace("livestream.stop")],yp.prototype,"stop",1);var _1=Object.defineProperty,C1=Object.getOwnPropertyDescriptor,R1=(s,t,e,r)=>{for(var i=r>1?void 0:r?C1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&_1(t,e,i),i};class Qv{constructor(t,e,r){p(this,"livestream");m(this,Pa,void 0);m(this,ka,void 0);m(this,wr,void 0);m(this,Bs,void 0);f(this,Bs,t),f(this,ka,e),this.livestream=new yp(t,e),f(this,wr,r),this.setupEvents()}get logger(){return a(this,Bs).getValue("logger")}get telemetry(){return a(this,Bs).getValue("telemetry")}async fetchInitialLivestreamingState(){const t=Ht(),{status:e,playbackUrl:r,manualIngest:i,ingestionCredentials:n}=await t.getActiveLivestream();this.livestream.playbackUrl=r,this.livestream.ingestionCredentials=n,e==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),e==="INVOKED"&&i&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}setupEvents(){a(this,wr).on(x.startedLivestream,async t=>{this.livestream.playbackUrl=t.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{a(this,ka).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}}),a(this,wr).on(x.livestreamingInvoked,async t=>{if(t.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{a(this,ka).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}}),a(this,wr).on(x.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),a(this,wr).on(x.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),a(this,wr).on(x.roomPeerCount,t=>{this.livestream.viewerCount=t.count,this.livestream.emit("viewerCountUpdate",t.count)}),a(this,Bs).getValue("peerSessionStore").on(P.PEER_JOINED_INTERNAL,async t=>{var e;((e=t.flags)==null?void 0:e.hiddenParticipant)===!0&&t.recorderType==="LIVESTREAMER"&&(f(this,Pa,t.id),this.livestream.setLivestreamState("LIVESTREAMING"))}),a(this,Bs).getValue("peerSessionStore").on(P.PEER_CLOSED,t=>{t.id===a(this,Pa)&&(f(this,Pa,void 0),this.livestream.setLivestreamState("IDLE"))}),a(this,Bs).getValue("peerSessionStore").onAsync(P.LEAVE_MEDIA_ROOM,async()=>{if(!this.livestream.playbackUrl){this.logger.info("Fetching livestreaming state on leave stage");try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Failed to fetch livestreaming state on leave stage",{error:t})}}}),a(this,Bs).getValue("peerSessionStore").on(P.SOCKET_SERVICE_ROOM_JOINED,async()=>{try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Error: LivestreamController.fetchLivestream")}})}}Pa=new WeakMap,ka=new WeakMap,wr=new WeakMap,Bs=new WeakMap,R1([E.trace("LivestreamController.setupEvents")],Qv.prototype,"setupEvents",1);var I1=Object.defineProperty,A1=Object.getOwnPropertyDescriptor,Ro=(s,t,e,r)=>{for(var i=r>1?void 0:r?A1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&I1(t,e,i),i};class zn{constructor({name:t,socketHandler:e,meetingId:r}){m(this,su);p(this,"name","");m(this,ct,{});m(this,ai,"");m(this,oi,void 0);p(this,"rateLimitConfig",{maxInvocations:5,period:1});p(this,"bulkRateLimitConfig",{maxInvocations:5,period:1});p(this,"listeners",{});this.name=t,f(this,oi,e),f(this,ai,r)}async set(t,e,r=!0,i=!1){a(this,ct)[t]=e,r&&this.remoteSet(t,e),i&&(this.listeners[t]&&this.listeners[t].forEach(n=>n({[t]:a(this,ct)[t]})),this.listeners["*"]&&this.listeners["*"].forEach(n=>n({[t]:a(this,ct)[t]})))}remoteSet(t,e){a(this,oi).storeInsertKeys(a(this,ai),this.name,[{key:t,payload:e}])}async bulkSet(t){t.forEach(({key:e,payload:r})=>{a(this,ct)[e]=r}),a(this,oi).storeInsertKeys(a(this,ai),this.name,t)}async update(t,e,r=!0){R(this,su,aT).call(this,t,e,r)}async delete(t,e=!0,r=!1){if(a(this,ct)[t]&&delete a(this,ct)[t],e)return a(this,oi).storeDeleteKeys(a(this,ai),this.name,[{key:t}]);r&&(this.listeners[t]&&(this.listeners[t].forEach(i=>i({[t]:void 0})),delete this.listeners[t]),this.listeners["*"]&&this.listeners["*"].forEach(i=>i({[t]:void 0})))}async bulkDelete(t){return t.forEach(({key:e})=>{a(this,ct)[e]&&delete a(this,ct)[e]}),a(this,oi).storeDeleteKeys(a(this,ai),this.name,t)}get(t){if(a(this,ct)[t])return a(this,ct)[t]}getAll(){return a(this,ct)}clear(){f(this,ct,{})}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get bulkRateLimits(){return this.bulkRateLimitConfig}updateBulkRateLimits(t,e){this.bulkRateLimitConfig.maxInvocations=t,this.bulkRateLimitConfig.period=e}subscribe(t,e){if(this.listeners[t]){this.listeners[t].push(e);return}this.listeners[t]=[e]}unsubscribe(t,e){var r;if(e){this.listeners[t]=((r=this.listeners[t])==null?void 0:r.filter(i=>i!==e))||[];return}this.listeners[t]&&delete this.listeners[t]}populate(t){f(this,ct,t)}}ct=new WeakMap,ai=new WeakMap,oi=new WeakMap,su=new WeakSet,aT=function(t,e,r=!0){let i;const n=a(this,ct)[t],o=Object.prototype.toString.call(e),c=Object.prototype.toString.call(n);if(o!==c){this.set(t,e);return}switch(c){case"[object Array]":i=[...n,...e];break;case"[object Object]":i={...n,...e};break;case"[object Map]":i=new Map([...n,...e]);break;case"[object Set]":i=new Set([...n,...e]);break;default:i=e;break}this.set(t,i,r)},Ro([qt(Wn,"rateLimitConfig")],zn.prototype,"remoteSet",1),Ro([qt(Wn,"bulkRateLimitConfig")],zn.prototype,"bulkSet",1),Ro([qt(Wn,"rateLimitConfig")],zn.prototype,"update",1),Ro([qt(Wn,"rateLimitConfig")],zn.prototype,"delete",1),Ro([qt(Wn,"bulkRateLimitConfig")],zn.prototype,"bulkDelete",1);class M1{constructor(t,e){m(this,dc);m(this,ru);p(this,"stores",new Map);m(this,ci,void 0);m(this,di,"");m(this,lc,void 0);m(this,_s,new Map);f(this,ci,e),f(this,di,t.getValue("meetingId")),f(this,lc,t),R(this,ru,oT).call(this)}create(t,e=!1){if(j_.includes(t)&&!e)throw new C(`'${t}' is a reserved store name.`,"0601");const r=new zn({name:t,socketHandler:a(this,ci),meetingId:a(this,di)});return a(this,ci).storeGetKeys(a(this,di),t,[]),new Promise((n,o)=>{const c=setTimeout(()=>{a(this,_s).delete(t),o(Error("Failed"))},3e3);a(this,_s).set(t,{rejectTimeout:c,resolve:n,store:r})})}refresh(t){const e=this.stores.get(t);return e?(e.clear(),a(this,ci).storeGetKeys(a(this,di),t,[]),new Promise((i,n)=>{const o=setTimeout(()=>{a(this,_s).delete(t),n(Error("Store refresh timed out"))},3e3);a(this,_s).set(t,{rejectTimeout:o,resolve:i,store:e})})):Promise.reject(Error(`Store '${t}' does not exist`))}}ci=new WeakMap,di=new WeakMap,dc=new WeakSet,Xp=function(){return a(this,lc).getValue("peerId")},lc=new WeakMap,_s=new WeakMap,ru=new WeakSet,oT=function(){[or.storeInsertKeys,or.storeGetKeys,or.storeDeleteKeys].forEach(t=>{a(this,ci).on(t,async e=>{var n,o;if(e.pluginId!==a(this,di))return;const r=(n=e.storeItems)==null?void 0:n.map(c=>{var d;return{timestamp:c.timestamp,peerId:c.peerId,payload:JSON.parse((d=c.payload)!=null&&d.length?new TextDecoder().decode(c.payload):"{}"),key:c.storeKey}});if(t===or.storeGetKeys){const c=a(this,_s).get(e.storeName),d=this.stores.get(e.storeName)||(c==null?void 0:c.store);if(a(this,_s).get(e.storeName)&&(this.stores.set(e.storeName,c.store),c.resolve(d),clearTimeout(c.rejectTimeout),a(this,_s).delete(e.storeName)),!d)return;r.forEach(l=>{d.set(l.key,l.payload,!1,!1)});return}const i=this.stores.get(e.storeName)||((o=a(this,_s).get(e.storeName))==null?void 0:o.store);i!==void 0&&(t===or.storeInsertKeys&&r.forEach(({key:c,peerId:d,payload:l})=>{d!==a(this,dc,Xp)&&i.set(c,l,!1,!0)}),t===or.storeDeleteKeys&&r.forEach(({key:c,peerId:d})=>{d!==a(this,dc,Xp)&&i.delete(c,!1,!0)}))})})};function Ui(s){var t,e,r,i,n,o,c,d,l,u,h,g,v;return s?{media:{audio:{enabled:s.audioEnabled,trackId:(t=s.audioTrack)==null?void 0:t.id,permission:"mediaPermissions"in s?(e=s.mediaPermissions)==null?void 0:e.audio:null},video:{enabled:s.videoEnabled,trackId:(r=s.videoTrack)==null?void 0:r.id,permission:"mediaPermissions"in s?(i=s.mediaPermissions)==null?void 0:i.video:null},screenshare:{enabled:s.screenShareEnabled,permission:"mediaPermissions"in s?(n=s.mediaPermissions)==null?void 0:n.screenshare:null,audio:{enabled:(c=(o=s.screenShareTracks)==null?void 0:o.audio)==null?void 0:c.enabled,trackId:(l=(d=s.screenShareTracks)==null?void 0:d.audio)==null?void 0:l.id},video:{enabled:(h=(u=s.screenShareTracks)==null?void 0:u.video)==null?void 0:h.enabled,trackId:(v=(g=s.screenShareTracks)==null?void 0:g.video)==null?void 0:v.id}}}}:{}}var O1=Object.defineProperty,D1=Object.getOwnPropertyDescriptor,Yn=(s,t,e,r)=>{for(var i=r>1?void 0:r?D1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&O1(t,e,i),i};const N1=.8,L1=1.2;let hr=(zS=class extends Bt{constructor(t,e,r,i){const n=t.getValue("logger");super(n);m(this,dn);m(this,li);m(this,ln);m(this,iu);m(this,un);m(this,hc);m(this,au);m(this,ou);p(this,"id");p(this,"userId");p(this,"name");p(this,"picture");p(this,"isHost");p(this,"customParticipantId");p(this,"flags");p(this,"device");p(this,"videoTrack");p(this,"audioTrack");p(this,"screenShareTracks");p(this,"videoEnabled");p(this,"audioEnabled");p(this,"screenShareEnabled");p(this,"producers");p(this,"manualProducerConfig");m(this,_a,void 0);p(this,"supportsRemoteControl",!1);m(this,Ca,void 0);p(this,"presetName");m(this,Kt,void 0);m(this,wt,void 0);m(this,uc,void 0);m(this,ui,new Map);m(this,Pr,1);m(this,nu,Ih(t=>{if(!this.videoTrack)return;const{clientWidth:e,clientHeight:r}=t,{width:i,height:n}=this.videoTrack.getSettings();if(!i||!n)return;const o=n/r,c=i/e,d=Math.max(o,c);d>L1&&a(this,Pr)===1?(f(this,Pr,0),a(this,Kt).getValue("peerSessionStore").emit(P.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,Pr)})):d<N1&&a(this,Pr)===0&&(f(this,Pr,1),a(this,Kt).getValue("peerSessionStore").emit(P.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,Pr)}))},2e3));f(this,Kt,t);const{id:o,userId:c,displayName:d,device:l,picture:u,isHost:h,flags:g,stageStatus:v,customParticipantId:y,audioMuted:k,audioTrack:I,videoEnabled:D=!1,videoTrack:N,producers:B,metadata:U}=e;this.id=o,this.userId=c,this.name=d,this.device=l,this.picture=u,this.isHost=h,this.flags=g,this.manualProducerConfig=x_,f(this,Ca,v!=null?v:"ON_STAGE"),this.customParticipantId=y,this.audioEnabled=!k,this.audioTrack=I,this.videoEnabled=D,this.videoTrack=N,this.screenShareTracks={audio:void 0,video:void 0},this.producers=B!=null?B:[],this.presetName=U==null?void 0:U.preset_name,f(this,_a,!1),f(this,wt,r),f(this,uc,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),R(this,hc,Zp).call(this)}get stageStatus(){return a(this,Ca)}get telemetry(){return a(this,Kt).getValue("telemetry")}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(this.logger.info("Participant::setVideoEnabled::videoUpdate",{...Ui(this)}),this.logger.info(`Emitting videoUpdate to the UI Kit for remote peerId: ${this.id}. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(this.logger.info("Participant::setAudioEnabled::audioUpdate",{...Ui(this)}),this.logger.info(`Emitting audioUpdate to the UI Kit for remote peerId: ${this.id}. Audio enabled: ${this.audioEnabled}. Audio track available: ${!!this.audioTrack}.`),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}))}setScreenShareEnabled(t,e=!0){var r;this.screenShareEnabled=t,e&&(this.logger.info(`Emitting screenShareUpdate to the UI Kit for remote peerId: ${this.id}. Screen sharing enabled: ${this.screenShareEnabled}. Video track available: ${!!((r=this.screenShareTracks)!=null&&r.video)}.`),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}setupEvents(){this.on("videoUpdate",R(this,hc,Zp)),a(this,li,so)&&(this.on("audioUpdate",R(this,au,dT)),this.on("screenShareUpdate",R(this,ou,lT)))}async pin(){if(!a(this,ln,bd))throw new C("Can`t pin participant without joining room","1205");if(!a(this,wt).permissions.pinParticipant)throw new C("You do not have permission to pin participants.","1201");return a(this,dn,Ed).pinPeer(this.id)}async unpin(){if(!a(this,ln,bd))throw new C("Can`t unpin participant without joining room","1205");if(!a(this,wt).permissions.pinParticipant)throw new C("You do not have permission to unpin participants.","1201");return a(this,dn,Ed).pinPeer(null)}setIsPinned(t,e=!0){var i;f(this,_a,t);const r=t?"pinned":"unpinned";(i=a(this,un,wd))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}async disableAudio(){const t=this.id;if(this.logger.info(`Local peer ${a(this,wt).id} is disabling mic of a remote peer ${t}`),!a(this,ln,bd))throw new C("Can`t disable participant audio without joining room","1205");if(a(this,wt).permissions.canDisableParticipantAudio)return a(this,dn,Ed).disableAudio(t);throw this.logger.error(`Local peer ${a(this,wt).id} is not authorized to disable mic of a remote peer ${t}`),new C("Unauthorized: User does not have permission to disable participant audio.","1201")}async kick(){const t=this.id;if(this.logger.info(`Local peer ${a(this,wt).id} is kicking a remote peer ${t} out of the meeting.`),!a(this,iu,cT))throw new C("Can`t kick participant without joining room","1205");if(a(this,wt).permissions.kickParticipant){await a(this,Kt).getValue("peerSessionStore").emitAsync(P.KICK_PEER,{peerId:t});return}throw this.logger.error(`Local peer ${a(this,wt).id} is not authorized to kick a remote peer ${t} out of the meeting.`),new C("Unauthorized: User does not have permission to kick participants.","1201")}async disableVideo(){const t=this.id;if(this.logger.info(`Local peer ${a(this,wt).id} is disabling webcam of a remote peer ${t}.`),!a(this,ln,bd))throw new C("Can`t disable participant video without joining room","1205");if(a(this,wt).permissions.canDisableParticipantVideo)return a(this,dn,Ed).disableVideo(t);throw this.logger.error(`Local peer ${a(this,wt).id} is not authorized to disable webcam of a remote peer ${t}.`),new C("Unauthorized: User does not have permission to disable participant video.","1201")}async getPermissions(){return a(this,uc).getUserPermissions(this.userId)}setStageStatus(t){f(this,Ca,t),this.emit("stageStatusUpdate",this)}get isPinned(){return a(this,_a)}registerVideoElement(t){var r,i,n,o;if(!t)return;let e;(i=(r=a(this,ui).get(t))==null?void 0:r.observer)==null||i.disconnect(),"ResizeObserver"in window&&(e=new ResizeObserver(()=>a(this,nu).call(this,t)),e.observe(t)),a(this,ui).set(t,{observer:e}),this.updateVideo(t),(o=a(this,un,wd))==null||o.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(n=this.raised)!=null?n:!1)}deregisterVideoElement(t){var e,r,i,n;if(!t){(e=a(this,un,wd))==null||e.removeSource(this.id);return}t.srcObject=void 0,(i=(r=a(this,ui).get(t))==null?void 0:r.observer)==null||i.disconnect(),a(this,ui).delete(t),(n=a(this,un,wd))==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 i=new MediaStream;i.addTrack(this.videoTrack),t.srcObject=i}else t.srcObject=void 0;t.style.display=this.videoEnabled?"block":"none"}},_a=new WeakMap,Ca=new WeakMap,Kt=new WeakMap,dn=new WeakSet,Ed=function(){return a(this,Kt).getValue("roomNodeClient")},li=new WeakSet,so=function(){return a(this,Kt).getValue("audioPlayback")},ln=new WeakSet,bd=function(){return a(this,Kt).getValue("connectionHandler").mediaJoined},iu=new WeakSet,cT=function(){return a(this,Kt).getValue("connectionHandler").socketJoined},wt=new WeakMap,uc=new WeakMap,ui=new WeakMap,un=new WeakSet,wd=function(){return a(this,Kt).getValue("pip")},Pr=new WeakMap,nu=new WeakMap,hc=new WeakSet,Zp=function(){Array.from(a(this,ui).keys()).forEach(this.updateVideo)},au=new WeakSet,dT=function(){var t,e;this.audioEnabled&&this.audioTrack?(t=a(this,li,so))==null||t.addParticipantTrack(this.id,this.audioTrack):(e=a(this,li,so))==null||e.removeParticipantTrack(this.id)},ou=new WeakSet,lT=function(){var t,e;this.screenShareEnabled&&this.screenShareTracks.audio?(t=a(this,li,so))==null||t.addParticipantTrack(`screenshare-${this.id}`,this.screenShareTracks.audio):(e=a(this,li,so))==null||e.removeParticipantTrack(`screenshare-${this.id}`)},zS);Yn([E.trace("Participant.disableAudio")],hr.prototype,"disableAudio",1),Yn([E.trace("Participant.kick")],hr.prototype,"kick",1),Yn([E.trace("Participant.disableVideo")],hr.prototype,"disableVideo",1),Yn([E.trace("Participant.getPermissions")],hr.prototype,"getPermissions",1),Yn([E.trace("Participant.setStageStatus")],hr.prototype,"setStageStatus",1),hr=Yn([pt("1200")],hr);class Io extends Ov{constructor(t,e){const{onAddEvent:r="participantJoined",onDeleteEvent:i="participantLeft",onClearEvent:n="participantsCleared"}=e!=null?e:{};super({onAddEvent:r,onDeleteEvent:i,onClearEvent:n},t)}add(t,e=!0){return this.has(t.id)&&Object.is(this.get(t.id),t)===!1&&this.delete(t.id),super.add(t,e)}clear(t=!0,e=!1){return super.clear(t,e)}delete(t,e=!0,r=!1){return super.delete(t,e,r)}}class V1 extends Bn{constructor(e){super(e);m(this,hi,void 0);f(this,hi,new Map)}__set(e,r){return a(this,hi).set(e,r)}__clear(){return a(this,hi).clear()}get(e){return a(this,hi).get(e)}toArray(){return Array.from(a(this,hi).values())}}hi=new WeakMap;class x1{constructor(){p(this,"_orderedArray");p(this,"_map");this._map=new Map,this._orderedArray=[]}add(t,e){if(!this._map.has(t))return this._map.set(t,{peerId:t,priority:e}),this._orderedArray.splice(Math.max(e-1,0),0,t),this.index(t);const r=this.index(t);this.delete(t);const i=this.add(t,e);return r!==i?i:-1}delete(t){if(this._map.has(t)){const e=this.index(t);this._map.delete(t),this._orderedArray.splice(e,1)}}index(t){return this._map.has(t)?this._orderedArray.indexOf(t):-1}[Symbol.iterator](){return this._orderedArray[Symbol.iterator]()}}class $1{constructor(){p(this,"_activeSpeakerPeers");p(this,"_compulsoryPeers");this._activeSpeakerPeers=new x1,this._compulsoryPeers=new Set}add(t,e,r){if(!t)return-1;if(e<0)return this._compulsoryPeers.add(t),0;const i=r.getValue("logger");if(this.compulsoryPeers.includes(t)&&(e>0||e===246267631)){if(i.info("SelectedPeer::removing_compulsory_peer",{selectedPeer:{peerId:t}}),this._removeFromCompulsoryPeer(t),e===246267631)return-1}else if(e===229490415)return this.delete(t,r),-1;return this._activeSpeakerPeers.add(t,e)}delete(t,e){const r=e==null?void 0:e.getValue("logger");r==null||r.info("SelectedPeer::deleting_peer_from_selectedPeer",{selectedPeer:{peerId:t}}),this._removeFromCompulsoryPeer(t),this._activeSpeakerPeers.delete(t)}reassignPeer(t,e,r){const i=this._activeSpeakerPeers.index(t),n=this._compulsoryPeers.has(t);this.delete(t,r),n&&this.add(e,-1,r),i>=0&&this.add(e,i+1,r)}index(t){return this._activeSpeakerPeers.index(t)}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(t){this._compulsoryPeers.delete(t)}}const Xv=new $1;var U1=Object.defineProperty,B1=Object.getOwnPropertyDescriptor,$s=(s,t,e,r)=>{for(var i=r>1?void 0:r?B1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&U1(t,e,i),i};const Zv=["ACTIVE_GRID","PAGINATED","MANUAL"];let ns=(YS=class extends Bt{constructor(t,e,r){var o,c;const i=t.getValue("logger");super(i);m(this,pc);m(this,hn);m(this,Ra);p(this,"waitlisted");p(this,"joined");p(this,"active");p(this,"videoSubscribed");p(this,"audioSubscribed");p(this,"pinned");p(this,"all");m(this,xe,void 0);m(this,pn,void 0);m(this,Vt,void 0);p(this,"rateLimitConfig",{maxInvocations:5,period:1});p(this,"viewMode");p(this,"currentPage");p(this,"lastActiveSpeaker");p(this,"selectedPeers",Xv);const n=(c=(o=t.getValue("defaults"))==null?void 0:o.viewMode)!=null?c:"ACTIVE_GRID";if(!Zv.includes(n))throw new C(`Invalid view mode: ${n}. Try ACTIVE_GRID, PAGINATED or MANUAL.`,"1207");f(this,xe,t),f(this,pn,e),f(this,Vt,r),this.waitlisted=new Io(i),this.joined=new Io(i),this.videoSubscribed=new Io(i),this.audioSubscribed=new Io(i),this.active=this.videoSubscribed,this.pinned=new Io(i),this.all=new V1(i),this.viewMode=n,this.currentPage=this.viewMode==="PAGINATED"?1:0,this.setupEvents()}get pip(){return a(this,xe).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get telemetry(){return a(this,xe).getValue("telemetry")}setupEvents(){a(this,xe).getValue("peerSessionStore").on(P.E2EE_ACTIVE_CONSUMER,({peerId:e})=>{var r;((r=a(this,xe).getValue("modules").e2ee)==null?void 0:r.enabled)!==!0&&this.emit("media_decode_error",{reason:`Got encrypted media for participantId ${e}, but encryption wasn't enabled in init.defaults`,code:"1702"})});const t=a(this,xe).getValue("audioPlayback");t&&this.audioSubscribed.on("participantLeft",e=>{t.removeParticipantTrack(e.id)})}get count(){return this.joined.size}get maxActiveParticipantsCount(){var t;return(t=a(this,xe))==null?void 0:t.getValue("maxPreferredStreams")}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new C("0 <= Max active participants count limit <= 24","1203");a(this,xe).setValue("maxPreferredStreams",t),a(this,Ra,sh)&&a(this,xe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}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)/Math.max(this.maxActiveParticipantsCount-t,1))}return 0}acceptWaitingRoomRequest(t){var r,i;if(!a(this,hn,Pd))throw new C("Can`t accept waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;return a(this,Vt).acceptWaitingRoomRequest([e])}async acceptAllWaitingRoomRequest(t){const e=t.map(r=>{var i,n;return(n=(i=this.waitlisted.get(r))==null?void 0:i.userId)!=null?n:r});return a(this,Vt).acceptWaitingRoomRequest(e)}async rejectWaitingRoomRequest(t){var r,i;if(!a(this,hn,Pd))throw new C("Can`t reject waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;a(this,Vt).rejectWaitingRoomRequest([e])}async setViewMode(t){if(this.logger.info("Participants::set_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),!(r=>Zv.includes(r))(t))throw this.logger.error("Participants::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.`,"1207");if(this.viewMode===t){this.logger.info("Participants::setViewMode::view_mode_same_as_previous");return}this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,a(this,xe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="ACTIVE_GRID"?(this.currentPage=0,a(this,xe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="MANUAL"&&(this.currentPage=0,a(this,xe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})}async subscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new C("MANUAL subscription mode was not activated.","1206");t.forEach(r=>{const i=this.joined.get(r);i&&(e.includes("audio")&&(i.manualProducerConfig={...i.manualProducerConfig,audio:!0},this.audioSubscribed.has(i.id)||this.audioSubscribed.add(i)),e.includes("video")&&(i.manualProducerConfig={...i.manualProducerConfig,video:!0},this.videoSubscribed.has(i.id)||this.videoSubscribed.add(i)),e.includes("screenshareAudio")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!0},this.audioSubscribed.has(i.id)||this.audioSubscribed.add(i)),e.includes("screenshareVideo")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!0},this.videoSubscribed.has(i.id)||this.videoSubscribed.add(i)))}),a(this,xe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}async unsubscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new C("MANUAL subscription mode was not activated.","1206");t.forEach(r=>{const i=this.joined.get(r);i&&(e.includes("audio")&&(i.manualProducerConfig={...i.manualProducerConfig,audio:!1},i.manualProducerConfig.screenshareAudio||this.audioSubscribed.delete(i.id)),e.includes("video")&&(i.manualProducerConfig={...i.manualProducerConfig,video:!1},i.manualProducerConfig.screenshareVideo||this.videoSubscribed.delete(i.id)),e.includes("screenshareAudio")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!1},i.manualProducerConfig.audio||this.audioSubscribed.delete(i.id)),e.includes("screenshareVideo")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!1},i.manualProducerConfig.video||this.videoSubscribed.delete(i.id)))}),a(this,xe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}getPeerIdsForCurrentPage(){this.logger.info("Participants::getPeerIdsForCurrentPage()",{pageNavigation:{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}});const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(c=>this.joined.has(c)),r=Array.from(this.pinned.keys()).filter(c=>!e.includes(c)),i=Array.from(this.joined.toArray().filter(c=>c.stageStatus==="ON_STAGE").map(c=>c.id)),n=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-r.length)),o=this.currentPage*(this.maxActiveParticipantsCount-e.length-r.length);return e.concat(r,i.slice(n,o))}async setPage(t){if(this.logger.info("Participants::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 this.logger.error("Participants::invalid_page_number"),new C(`Invalid page: ${t}. Page must be an integer and greater than 0 and less than or equal to .pageCount`,"1202");this.currentPage=t,a(this,xe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.viewMode,page:t}),this.emit("pageChanged",{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount})}}async disableAllAudio(t){if(this.logger.info("Participants::disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),!a(this,Ra,sh))throw new C("Can`t disable all audio without joining room","1205");if(a(this,pn).permissions.canAllowParticipantAudio)return a(this,pc,em).muteAll(t);throw this.logger.error("Participants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new C("Unauthorized: User does not have permission to disable peer audio.","1201")}async disableAllVideo(){if(this.logger.info("Participants::disable_all_video"),!a(this,Ra,sh))throw new C("Can`t disable all video without joining room","1205");if(a(this,pn).permissions.canAllowParticipantVideo)return a(this,pc,em).muteAllVideo();throw this.logger.error("Participants::unauthorized_disable_all_video"),new C("Unauthorized: User does not have permission to disable peer video.","1201")}async kickAll(){if(this.logger.info("Participants::kick_all"),a(this,xe).getValue("viewType")!=="LIVESTREAM"&&!a(this,hn,Pd))throw new C("Can`t kick all without joining room","1205");if(!a(this,pn).permissions.kickParticipant)throw this.logger.error("Participants::unauthorized_kick_all"),new C("Unauthorized: User does not have permission to kick peers.","1201");const e=!0;a(this,Vt).kickAll(e)}async broadcastMessage(t,e,r){if(this.logger.info("Participants::broadcastMessage"),!a(this,hn,Pd))throw new C("Can`t broadcast message without joining room","1205");if(!(t!=null&&t.trim()))throw new C("`type` must be a non-empty string.","1209");if(r)if("meetingIds"in r)await a(this,Vt).broadcastToMeetings(t,r.meetingIds,e);else{let i=[];"participantIds"in r?i=r.participantIds:i=this.joined.toArray().filter(n=>{var o;return(o=r.presetNames)==null?void 0:o.includes(n.presetName)}).map(n=>n.id),await a(this,Vt).broadcastToPeers(t,i,e)}else await a(this,Vt).broadcastMessage(t,e)}async getAllJoinedPeers(t,e,r){return(await a(this,Vt).getRoomPeers(t,e,r)).peers.map(pr.formatSocketPeerMessage)}async updatePermissions(t,e){const r=this.joined.toArray().filter(n=>t.includes(n.id)).map(n=>n.userId),i=[...new Set(r)];if(!i.length)throw new C("Cannot update permissions, no valid userIDs found","1204");a(this,Vt).updatePermissions(i,e)}async getParticipantsInMeetingPreJoin(){return a(this,Vt).getRoomPeersNonPaginated()}},xe=new WeakMap,pc=new WeakSet,em=function(){return a(this,xe).getValue("roomNodeClient")},hn=new WeakSet,Pd=function(){var t;return((t=a(this,xe).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},Ra=new WeakSet,sh=function(){var t;return((t=a(this,xe).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},pn=new WeakMap,Vt=new WeakMap,YS);$s([E.trace("Participants.setViewMode")],ns.prototype,"setViewMode",1),$s([E.trace("Participants.setPage")],ns.prototype,"setPage",1),$s([E.trace("Participants.disableAllAudio")],ns.prototype,"disableAllAudio",1),$s([E.trace("Participants.disableAllVideo")],ns.prototype,"disableAllVideo",1),$s([E.trace("Participants.kickAll")],ns.prototype,"kickAll",1),$s([E.trace("Participants.broadcastMessage"),qt(Wn,"rateLimitConfig")],ns.prototype,"broadcastMessage",1),$s([E.trace("Participants.getAllJoinedPeers"),qt({maxInvocations:10,period:60})],ns.prototype,"getAllJoinedPeers",1),$s([E.trace("Participant.updatePermissions"),qt({maxInvocations:1e3,period:60})],ns.prototype,"updatePermissions",1),$s([E.trace("Participants.getParticipantsInMeetingPreJoin")],ns.prototype,"getParticipantsInMeetingPreJoin",1),ns=$s([pt("1200")],ns);var F1=Object.defineProperty,H1=Object.getOwnPropertyDescriptor,Bi=(s,t,e,r)=>{for(var i=r>1?void 0:r?H1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&F1(t,e,i),i};const q1=5e3,j1=1e4,Qn=(QS=class{constructor(s,t,e){m(this,gn);m(this,cu);m(this,du);m(this,mc);m(this,lu);m(this,uu);p(this,"participants");p(this,"self");p(this,"selectedPeers",Xv);p(this,"maxSpatialLayerUpdates",new Map);p(this,"consumerPeerMap");p(this,"events");p(this,"roomSocketHandler");p(this,"context");p(this,"videoPeerConsumerMap",new Map);m(this,hs,{mode:"ACTIVE_GRID",page:0});m(this,Fs,!1);m(this,pi,!1);p(this,"isRebuildingReconnectSnapshot",!1);m(this,Ze,new Map);m(this,kr,void 0);m(this,mn,void 0);m(this,hu,({state:s})=>{s==="disconnected"||s==="stageLeft"||(this.isRebuildingReconnectSnapshot=!1,R(this,uu,mT).call(this),a(this,Ze).clear(),f(this,kr,void 0))});p(this,"updateConsumerSpatialLayers",Ih(()=>{const s={},t=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(t.entries()).forEach(([e,r])=>{s[r]===void 0&&(s[r]={layer:r,consumerIds:[]}),s[r].consumerIds.push(e)}),Object.keys(s).forEach(e=>{const r=s[e];this.logger.log(`Switching max spatial layer to ${r.layer}`,{consumerIds:r.consumerIds}),this.roomNodeClient.switchConsumersToLayer(r.consumerIds,r.layer)})},2e3));p(this,"updateConsumers",async(s,t)=>{this.logger.info(`updateConsumers: Starting serialized consumer updates: createProducerIds=[${s.map(({producerId:e})=>e).join(",")}], deleteConsumerIds=[${t.join(",")}], consumersSyncing=${a(this,Fs)}.`);try{s.length!==0&&(this.logger.info(`updateConsumers: Creating consumers for producerIds=[${s.map(({producerId:e})=>e).join(",")}].`),await this.roomNodeClient.createConsumers(s),this.logger.info("updateConsumers: Successfully created consumers."))}catch(e){this.logger.error("updateConsumers: Error creating consumers",{error:e})}try{t.length!==0&&(this.logger.info(`updateConsumers: Closing consumers after grace period: consumerIds=[${t.join(",")}].`),await this.roomNodeClient.closeConsumersById(t),this.logger.info("updateConsumers: Successfully closed consumers."))}catch(e){this.logger.error("updateConsumers: Error closing consumers",{error:e})}this.logger.info("updateConsumers: Completed consumer updates.")});this.context=s,this.roomSocketHandler=e,this.participants=new ns(s,t,this.roomSocketHandler),this.self=t,this.consumerPeerMap=new Map,this.events=Es,t.config.viewType!=="CHAT"&&(this.setupEventsGlobal(),R(this,lu,pT).call(this)),this.setupEvents(),this.self.on("roomLeft",a(this,hu))}get roomNodeClient(){return this.context.getValue("roomNodeClient")}get mediaJoined(){var s;return((s=this.roomNodeClient)==null?void 0:s.mediaJoined)===!0}get pip(){return this.context.getValue("pip")}static async init(s,t,e){return new Qn(s,t,e)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}handleSocketPeers(s){var d;const t=new Set(this.roomSocketHandler.socket.supersededLocalPeerIds),e=(d=s==null?void 0:s.filter(l=>!l.waitlisted&&!t.has(l.peerId)))!=null?d:[],r=new Set(e.map(({peerId:l})=>l)),i=t.size>0||this.participants.joined.size>0,n=this.context.getValue("viewType"),o=this.context.getValue("stageStatus"),c=this.mediaJoined&&(n!==Ss.Livestream||o==="ON_STAGE");this.isRebuildingReconnectSnapshot=i&&c,this.isRebuildingReconnectSnapshot||(this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear(),this.participants.pinned.clear()),this.participants.joined.forEach(({id:l})=>{var u;r.has(l)||(u=this.pip)==null||u.removeSource(l)}),this.participants.joined.clear(),e.forEach(l=>{var h;const u=this.createParticipantObjFromSocketPeer(l);if(this.isRebuildingReconnectSnapshot){const g=(h=this.participants.videoSubscribed.get(l.peerId))!=null?h:this.participants.audioSubscribed.get(l.peerId);g&&(u.manualProducerConfig={...g.manualProducerConfig})}this.logger.debug(`Processing socket join for ${this.self.id===u.id?"local peer":"remote peer"} ${u.id} listed in socket peers.`),this.onParticipantSocketJoined(u),this.logger.debug(`Processed socket join for ${this.self.id===u.id?"local peer":"remote peer"} ${u.id} listed in socket peers.`)})}handlePeerMediaJoinedBroadcast({participant:s,producerHandoverFromPeerId:t}){var i;if(!s)return;const e=s.peerId===this.self.id,r=(i=s.producerStates)!=null?i:[];this.logger.info(`${e?"Local peer":"Remote peer"} ${s.peerId} has joined media room with producerStates: ${JSON.stringify(r)}`),t&&t!==s.peerId&&r.length>0&&(this.logger.info(`Producer handover detected from ${t} to ${s.peerId} for producer ids ${r.map(({producerId:n})=>n).join(",")}`),this.context.getValue("peerSessionStore").emit(P.PRODUCER_HANDOVER,{oldPeerId:t,newPeerId:s.peerId,producerIds:r.map(({producerId:n})=>n)})),this.logger.debug(`Processing media join for newly joined ${e?"local peer":"remote peer"} ${s.peerId}.`),this.onParticipantMediaJoined(s.peerId,r),this.logger.debug(`Processed media join for newly joined ${e?"local peer":"remote peer"} ${s.peerId}.`)}clearParticipantMediaState(s,t,e){const r=s;e?t==="audio"?(r.screenShareTracks.audio=void 0,r.setScreenShareEnabled(r.screenShareEnabled&&r.screenShareTracks.video!==void 0)):(r.setScreenShareEnabled(!1),r.screenShareTracks={audio:void 0,video:void 0}):t==="audio"?(r.setAudioEnabled(!1),r.audioTrack=void 0):(r.setVideoEnabled(!1),this.updatePipSource(r.id,!1),r.videoTrack=void 0)}setupEvents(){this.roomSocketHandler.on(x.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),this.context.getValue("peerSessionStore").on(P.SOCKET_PEERS,this.handleSocketPeers.bind(this)),this.roomSocketHandler.on(this.events.peerJoinedBroadcast,this.handlePeerMediaJoinedBroadcast.bind(this)),this.roomSocketHandler.on(this.events.selfJoinComplete,async({participants:s,selectedPeers:t,roomState:e})=>{this.logger.info(`Local peer has joined media room. Processing media joins for existing ${s==null?void 0:s.length} peers.`),s.forEach(({peerId:n,producerStates:o})=>{this.logger.debug(`Processing media join for ${this.self.peerId===n?"local peer":"existing remote peer"} ${n}.`),this.onParticipantMediaJoined(n,o),this.logger.debug(`Processed media join for ${this.self.peerId===n?"local peer":"existing remote peer"} ${n}.`)}),this.isRebuildingReconnectSnapshot&&this.rewireConsumersOnLocalUserReconnect();const{audioPeers:r,compulsoryPeers:i}=t!=null?t:{};if(this.applyPinnedSnapshot(e.pinnedPeerIds),this.computeActivateParticipants(r!=null?r:[],i),this.participants.viewMode==="PAGINATED"){const n=Math.max(1,Math.min(this.participants.currentPage,this.participants.pageCount));n!==this.participants.currentPage&&await this.participants.setPage(n)}this.isRebuildingReconnectSnapshot=!1,this.logger.info("Participants reconciliation on local peer's media join is complete. Reconciling consumers."),this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}),this.context.getValue("peerSessionStore").on(P.MAX_SPATIAL_LAYER_CHANGE,({peerId:s,maxSpatialLayer:t})=>{const e=this.videoPeerConsumerMap.get(s);e&&(this.maxSpatialLayerUpdates.set(e,t),this.updateConsumerSpatialLayers())}),this.context.getValue("peerSessionStore").on(P.PRODUCER_HANDOVER,s=>this.handleProducerHandover(s)),this.context.getValue("peerSessionStore").on(P.NEW_PRODUCER,({peerId:s,producer:t})=>{if(!t){this.logger.error(`Received new remote producer for peer ${s}. producer is invalid/empty.`);return}const e=this.participants.joined.get(s);if(!e){this.logger.warn(`Received new ${t.screenShare?"screenshare":"participant"} ${t.kind} remote producer ${t.producerId} for a non-existent peer ${s}`);return}const r=e.producers.find(({producerId:n})=>n===t.producerId);let i="REPLACED";r?(Object.assign(r,t),i="REPLACED"):(e.producers.push(t),i="INSERTED"),this.logger.info(`Scheduling syncConsumer post upserting (${i}) new producer ${t.producerId} to peer ${s} for ${t.screenShare?"screenshare":"participant"} ${t.kind}`),this.scheduleSyncConsumers({source:"NEW_REMOTE_PRODUCER"})}),this.context.getValue("peerSessionStore").on(P.PRODUCER_CLOSED,({peerId:s,producerId:t})=>{const e=this.participants.joined.get(s);if(!e){this.logger.warn(`Received producer closed event for producer ${t} of a peer ${s} that might have already left the meeting.`);return}const r=e.producers.find(i=>i.producerId===t);r?(this.logger.info(`${r.screenShare?"Screenshare":"Participant"} ${r.kind} producer ${t} of peer ${s} has closed. Updating media state and scheduling syncConsumers for reconciliation.`),this.clearParticipantMediaState(e,r.kind,r.screenShare),r.kind==="video"&&!r.screenShare&&this.videoPeerConsumerMap.get(s)===t&&this.videoPeerConsumerMap.delete(s),e.producers=e.producers.filter(i=>i.producerId!==t),this.scheduleSyncConsumers({source:"PRODUCER_CLOSED"})):this.logger.warn(`Received producer closed event for producer ${t} of a peer ${s}. Peer doesn't have the producer associated with it. Ignoring the event.`)}),this.context.getValue("peerSessionStore").on(P.PRODUCER_TOGGLE,({peerId:s,producerId:t,paused:e,kind:r})=>{const i=this.participants.joined.get(s);if(i){const n=i.producers.find(o=>o.producerId===t);if(!n){this.logger.warn(`Processing participant ${r} producer ${e?"paused":"resumed"} broadcast for remote producer ${t} of peer ${s} however producer is not associated with the peer. Ignoring the event.`);return}if(this.logger.info(`Processing participant ${r} producer ${e?"paused":"resumed"} broadcast for remote producer ${t} of peer ${s}. Reconciling media states and consumers.`),n.pause=e,r==="audio"&&i.setAudioEnabled(!e),r==="video"){const o=this.roomNodeClient.getConsumers().get(t);e?(i.setVideoEnabled(!1),this.updatePipSource(i.id,!1)):o&&!o.closed&&(i.videoTrack=o.track,i.setVideoEnabled(!0),this.updatePipSource(i.id,!0)),this.context.getValue("callstats").consumerSharedMediaState(t,{video:!e}),this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}}else this.logger.warn(`Processing participant ${r} producer ${e?"paused":"resumed"} broadcast for remote producer ${t} of a missing peer ${s}. Ignoring the event.`)}),this.roomSocketHandler.on(this.events.globalPeerPinBroadcast,s=>{let t;if(s&&(t=s.participantId),!this.mediaJoined)return;const e=t;this.onParticipantPinned(e);const r=this.participants.joined.get(e);r&&(this.logger.info(`globalPeerPinBroadcast: Scheduling audio/video consumer sync for pinned participant ${e} - ProducerCount: ${r.producers.length}, ConsumersSyncing: ${a(this,Fs)}, ProducerIds: [${r.producers.map(i=>i.producerId).join(", ")}]`),this.scheduleSyncConsumers({source:"GLOBAL_PEER_PIN"}))}),this.roomSocketHandler.on(this.events.selectedPeer,({audioPeers:s,compulsoryPeers:t})=>{this.mediaJoined&&this.onSelectedPeers(t.concat(s))}),this.roomSocketHandler.on(this.events.selectedPeerDiff,({entries:s})=>{if(!this.mediaJoined)return;const t=s.map(e=>({peerId:e.peerId,priority:e.priority}));this.updateActiveParticipantsWithPriorities(t,!0)})}waitingRoomRequestHandler(s){var r,i;this.logger.info(`Received waitlisted peers: ${((i=(r=s==null?void 0:s.requests)==null?void 0:r.map(n=>n.peerId))==null?void 0:i.join(", "))||"none"}`);const t=s.requests.filter(n=>!this.participants.waitlisted.get(n.peerId)),e=this.participants.waitlisted.toArray().filter(n=>!s.requests.find(o=>o.peerId===n.id));t.forEach(n=>this.participants.waitlisted.add(new hr(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))),e.forEach(n=>this.participants.waitlisted.delete(n.id))}get maxPreferredStreams(){return this.participants.maxActiveParticipantsCount}selectPagePeers(s){const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(d=>this.participants.joined.has(d)),r=Array.from(this.participants.pinned.keys()).filter(d=>!e.includes(d)),i=Array.from(this.participants.joined.toArray().filter(d=>d.stageStatus==="ON_STAGE").map(d=>d.id)),n=Math.max((s-1)*(this.maxPreferredStreams-e.length-r.length)),o=s*(this.maxPreferredStreams-e.length-r.length);return e.concat(r,i.slice(n,o))}selectActivePeers(s){const t=new Map,e=Array.from(this.participants.joined.toArray().filter(u=>u.stageStatus==="ON_STAGE").map(u=>(t.set(u.id,!0),u.id))),r=this.selectedPeers.peers,i=this.participants.pinned.toArray().reduce((u,h)=>(h.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(h.id):u.push(h.id),u),[]),n=this.self.stageStatus==="ON_STAGE"?1:0,o=s-n,c=new Set(r.concat(i).filter(u=>u!==this.self.id&&t.has(u)));let d=Array.from(c);const l=o-c.size;if(l>=0){const u=e.filter(h=>!c.has(h)&&h!==this.self.id).slice(0,l);d=Array.from(c).concat(u)}else d=d.slice(0,o);return d}updateMediaSubscribedMaps(s,t){const{page:e}=t!=null?t:{};s&&a(this,hs).mode!==s&&(a(this,hs).mode=s),e&&a(this,hs).page!==e&&(a(this,hs).page=e);const{mode:r,page:i}=a(this,hs);switch(r){case"PAGINATED":{if(!i)return;const n=this.selectPagePeers(i),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMap(this.participants.videoSubscribed,n),this.updateParticipantsMap(this.participants.audioSubscribed,o),this.logger.debug("ParticipantController::updateActive::updating_current_page_peers",{peerIds:n});break}case"ACTIVE_GRID":{const n=this.selectActivePeers(this.participants.maxActiveParticipantsCount),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMapMinReplacement(this.participants.videoSubscribed,n),this.updateParticipantsMap(this.participants.audioSubscribed,o);break}case"MANUAL":{this.reconcileManualSubscriptionMaps();break}default:throw new Error(`View mode ${s} not supported`)}}async scheduleSyncConsumers({source:s}){var e,r,i;const t=((e=a(this,hs))==null?void 0:e.mode)==="PAGINATED"&&!a(this,Fs)?200:0;this.logger.info(`scheduleSyncConsumers():: Source: ${s}, ViewMode: ${(r=a(this,hs))==null?void 0:r.mode}, ConsumersSyncing: ${a(this,Fs)}, Delay: ${t}, Page: ${(i=a(this,hs))==null?void 0:i.page}`),setTimeout(()=>this.syncConsumers(),t)}async syncConsumers(){var I,D,N,B,U,j,Z,re;const s=this.context.getValue("connectionHandler");if((I=s==null?void 0:s.socketState)!=null&&I.state&&s.socketState.state!=="connected"){R(this,gn,kd).call(this,"socket not connected"),this.logger.info("syncConsumers: Socket not connected, deferring sync.");return}if(((N=(D=s==null?void 0:s.mediaState)==null?void 0:D.recv)==null?void 0:N.state)!=="connected"){R(this,gn,kd).call(this,"Recv transport not connected"),this.logger.info("syncConsumers: Connection not ready, exiting.");return}if(R(this,cu,uT).call(this),a(this,Fs)){f(this,pi,!0),this.logger.info("syncConsumers: Sync in progress, marking resyncRequired=true and exiting.");return}this.logger.info("syncConsumers: Starting sync operation."),f(this,Fs,!0),f(this,pi,!1);let t=[];this.participants.videoSubscribed.forEach(F=>{var vt,A;const ee=this.participants.joined.get(F.id),we=(A=(vt=F.producers)==null?void 0:vt.filter(S=>S.kind==="video"))!=null?A:[];ee&&(we!=null&&we.length)&&we.forEach(S=>{var ce,fe,V,_;const w=((fe=(ce=ee.manualProducerConfig)==null?void 0:ce.video)!=null?fe:!0)&&S.kind==="video"&&!S.screenShare,$=((_=(V=ee.manualProducerConfig)==null?void 0:V.screenshareVideo)!=null?_:!0)&&S.kind==="video"&&S.screenShare;(w||$)&&(S.pause||t.push(S))})}),this.participants.audioSubscribed.forEach(F=>{var vt,A;const ee=this.participants.joined.get(F.id),we=(A=(vt=F.producers)==null?void 0:vt.filter(S=>S.kind==="audio"))!=null?A:[];ee&&(we!=null&&we.length)&&we.forEach(S=>{var ce,fe,V,_;const w=((fe=(ce=ee.manualProducerConfig)==null?void 0:ce.audio)!=null?fe:!0)&&S.kind==="audio"&&!S.screenShare,$=((_=(V=ee.manualProducerConfig)==null?void 0:V.screenshareAudio)!=null?_:!0)&&S.kind==="audio"&&S.screenShare;(w||$)&&t.push(S)})}),t=V_(t,F=>F.producerId);const e=new Map;t.forEach(F=>{e.set(F.producerId,F)});const r=(U=(B=this.roomNodeClient)==null?void 0:B.getConsumers())!=null?U:new Map,i=[];r.forEach(F=>{F.closed&&i.push(F.id)});const n=(Z=(j=this.roomNodeClient)==null?void 0:j.removeClosedConsumers(i))!=null?Z:[];n.forEach(F=>{a(this,Ze).delete(F),this.consumerPeerMap.has(F)&&this.processConsumerClosed(F)}),n.length>0&&this.logger.info(`syncConsumers: Removed closed consumers: consumerIds=[${n.join(",")}].`);let o=[];const c=new Set,d=[],l=[];e.forEach(F=>{const ee=r.get(F.producerId);if(!ee){o.push(F);return}c.add(ee.id);const{needsRemap:we,wasMarkedForDeletion:vt}=R(this,mc,tm).call(this,ee,F);we&&l.push(ee.id),vt&&d.push(ee.id)});const u=[];r.forEach(F=>{F.closed||c.has(F.id)||R(this,du,hT).call(this,F)&&u.push(F.id)});const h=Date.now(),g=[];let v=[];a(this,Ze).forEach((F,ee)=>{const we=r.get(ee);if(!we||we.closed){a(this,Ze).delete(ee);return}if(c.has(ee)){a(this,Ze).delete(ee);return}h-F>=j1?v.push(ee):g.push(ee)}),e.size>0&&this.logger.debug(`syncConsumers: Desired producer IDs: [${Array.from(e.keys()).join(",")}].`),r.size>0&&this.logger.debug(`syncConsumers: Current consumer IDs: [${Array.from(r.keys()).join(",")}].`),o.length>0&&this.logger.info(`syncConsumers: Producer IDs requiring consumers: [${o.map(({producerId:F})=>F).join(",")}].`),c.size>0&&this.logger.debug(`syncConsumers: Consumer IDs to keep: [${Array.from(c).join(",")}].`),l.length>0&&this.logger.info(`syncConsumers: Consumer IDs with consumer rewiring: [${l.join(",")}].`),d.length>0&&this.logger.info(`syncConsumers: Consumer IDs revived before deletion: [${d.join(",")}].`),u.length>0&&this.logger.info(`syncConsumers: Newly marked consumer IDs: [${u.join(",")}].`),g.length>0&&this.logger.info(`syncConsumers: Consumer IDs in deletion grace period: [${g.join(",")}].`),v.length>0&&this.logger.info(`syncConsumers: Consumer IDs ready for deletion: [${v.join(",")}].`);const y=35,k=35;o.length>y&&(this.logger.warn(`syncConsumers: Too many remote producers to create consumers: ${o.length}. Only adding ${y} in this run.`),o=o.slice(0,y),this.scheduleSyncConsumers({source:"SOFT_CAPPED_CREATE_CONSUMERS"})),v.length>k&&(this.logger.warn(`syncConsumers: Too many remote consumers ready to close: ${v.length}. Only removing ${k} in this run.`),v=v.slice(0,k),this.scheduleSyncConsumers({source:"SOFT_CAPPED_REMOVE_CONSUMERS"}));try{o.length>0||v.length>0?(this.logger.info(`syncConsumers: Calling updateConsumers: createProducerIds=[${o.map(({producerId:F})=>F).join(",")}], deleteConsumerIds=[${v.join(",")}].`),await this.updateConsumers(o,v),this.logger.info("syncConsumers: updateConsumers completed successfully.")):this.logger.info("syncConsumers: No changes needed, skipping updateConsumers.")}catch(F){this.logger.error("syncConsumers: updateConsumers failed with error.",{error:F})}finally{this.logger.info("syncConsumers: Setting consumersSyncing=false and completing sync."),f(this,Fs,!1),(re=s==null?void 0:s.socketState)!=null&&re.state&&s.socketState.state!=="connected"&&f(this,pi,!0)}a(this,pi)&&(this.logger.info("syncConsumers: Resync required, calling syncConsumers again."),this.syncConsumers())}computeActivateParticipants(s,t){const e=s.map((i,n)=>({peerId:i,priority:n+1})),r=t==null?void 0:t.map((i,n)=>({peerId:i,priority:-(n+1)}));e.push(...r!=null?r:[]),e.length>0&&this.updateActiveParticipantsWithPriorities(e)}createParticipantObjFromSocketPeer(s){const t=Qn.formatSocketPeerMessage(s);return new hr(this.context,{...t,isHost:!1,videoEnabled:!1,audioMuted:!0,videoTrack:void 0,audioTrack:void 0},this.self,this.roomSocketHandler)}updatePipSource(s,t){var e,r;t?(e=this.pip)==null||e.enableSource(s):(r=this.pip)==null||r.disableSource(s)}onParticipantMediaJoined(s,t){if(!this.mediaJoined||s===this.self.id)return;const e=this.participants.joined.get(s);if(!e){this.logger.warn(`Received media.peerJoinedBroadcast for non-existent peer ${s}`);return}this.logger.info(`processing media state of remote producers of peer ${s} with producerStates: ${JSON.stringify(t)}`),t.forEach(r=>{r.kind===Ns.AUDIO&&!r.screenShare?e.setAudioEnabled(!r.pause):r.kind===Ns.VIDEO&&!r.screenShare&&(e.setVideoEnabled(!r.pause),this.updatePipSource(e.id,!r.pause));const i={...r,producingTransportId:r.producingTransportId,kind:r.kind===Ns.AUDIO?"audio":"video",producingPeerId:s,mimeType:r.mimeType},n=e.producers.find(({producerId:o})=>o===i.producerId);n?Object.assign(n,i):e.producers.push(i)}),this.logger.info(`Reconciling consumers due to media join of peer ${s}. Media join is complete.`),this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}updateParticipantsMapMinReplacement(s,t){const e=Array.from(s.keys()),r=new Map(s),i=new Set(t),n=[];e.forEach((o,c)=>{(!i.has(o)||!this.participants.joined.get(o))&&n.push(c)}),t.forEach(o=>{if(s.get(o))return;if(e.length<t.length){e.push(o);return}const c=n.shift();e[c]=o}),n.forEach(o=>{e.splice(o,1)}),Array.from(s.keys()).forEach(o=>{s.delete(o,!i.has(o))}),e.forEach(o=>{const c=this.participants.joined.get(o);if(!c)return;const d=r.get(o),l=!d||d!==c;s.add(c,l)}),s.emit("participantsUpdate")}reconcileManualSubscriptionMaps(){const s=Array.from(this.participants.videoSubscribed.keys()),t=Array.from(this.participants.audioSubscribed.keys());this.updateParticipantsMap(this.participants.videoSubscribed,s.filter(e=>this.participants.joined.has(e))),this.updateParticipantsMap(this.participants.audioSubscribed,t.filter(e=>this.participants.joined.has(e)))}updateParticipantsMap(s,t){Array.from(s.keys()).forEach(r=>{t.includes(r)||s.delete(r,!0)}),t.forEach(r=>{const i=s.get(r),n=this.participants.joined.get(r);n&&i!==n&&(i&&s.delete(r,!1),s.add(n,!0))}),s.emit("participantsUpdate")}updatePinnedParticipants(){this.participants.pinned.forEach(s=>{s.setIsPinned(!1),this.participants.pinned.delete(s.id)})}applyPinnedSnapshot(s){const t=s[0];if(this.participants.pinned.forEach(i=>{i.id!==t&&(i.setIsPinned(!1),this.participants.pinned.delete(i.id))}),t===this.self.id){this.self.setIsPinned(!0),this.participants.pinned.emit("participantsUpdate");return}if(this.self.isPinned&&this.self.setIsPinned(!1),!t){this.participants.pinned.emit("participantsUpdate");return}const e=this.participants.joined.get(t),r=this.participants.pinned.get(t);if(!e){r&&this.participants.pinned.delete(t),this.participants.pinned.emit("participantsUpdate");return}r!==e&&(r&&(r.setIsPinned(!1),this.participants.pinned.delete(t,!1)),e.setIsPinned(!0),this.participants.pinned.add(e,!0)),this.participants.pinned.emit("participantsUpdate")}rewireConsumersOnLocalUserReconnect(){this.participants.joined.forEach(s=>{s.producers.forEach(t=>{const e=this.roomNodeClient.getConsumers().get(t.producerId);!e||e.closed||(R(this,mc,tm).call(this,e,t),t.pause&&!t.screenShare&&(t.kind==="audio"?s.setAudioEnabled(!1):(s.setVideoEnabled(!1),this.updatePipSource(s.id,!1))))})})}static replaceParticipantInMap(s,t,e,r){const i=s,n=i.get(t);if(!n)return;const o=new Set,c=Array.from(i.values()).reduce((d,l)=>{const u=l.id===t?e:l;return o.has(u.id)||(o.add(u.id),d.push(u)),d},[]);if(Array.from(i.keys()).forEach(d=>{i.delete(d,!1)}),c.forEach(d=>i.add(d,!1)),r){const d=i.emit.bind(i);d("participantLeft",n),d("participantJoined",e)}i.emit("participantsUpdate")}handleProducerHandover(s){const{oldPeerId:t,newPeerId:e,producerIds:r}=s;if(typeof t!="string"||typeof e!="string"||t===e||!Array.isArray(r)||r.length===0||r.some(u=>typeof u!="string")||e===this.self.id)return;const i=this.participants.joined.get(t),n=this.participants.joined.get(e);if(!i||!n||!i.userId||i.userId!==n.userId){this.logger.warn(`ParticipantController::producerHandover::participant validation failed from ${t} to ${e}`);return}this.selectedPeers.reassignPeer(t,e,this.context);const o=this.context.getValue("audioPlayback");o==null||o.reassignParticipantTrack(t,e),o==null||o.reassignParticipantTrack(`screenshare-${t}`,`screenshare-${e}`);const c=new Set(r),d=i.producers.filter(({producerId:u})=>c.has(u));if(d.length===0)return;d.some(u=>u.kind==="audio"&&!u.screenShare)&&(i.setAudioEnabled(!1),i.audioTrack=void 0),d.some(u=>u.screenShare)&&(i.setScreenShareEnabled(!1),i.screenShareTracks={audio:void 0,video:void 0}),n.manualProducerConfig={...i.manualProducerConfig},i.producers=i.producers.filter(({producerId:u})=>!c.has(u)),d.forEach(u=>{if(n.producers.some(({producerId:g})=>g===u.producerId))return;const h={...u};delete h.consumer,this.context.getValue("peerSessionStore").emit(P.NEW_PRODUCER,{peerId:e,producer:{...h,producingPeerId:e}})}),this.roomNodeClient.handoverPeerProducers(e,r).forEach(u=>{u.kind==="video"&&u.appData.screenShare!==!0&&this.videoPeerConsumerMap.get(t)===u.id&&(this.videoPeerConsumerMap.delete(t),this.updatePipSource(t,!1)),this.context.getValue("peerSessionStore").emit(P.NEW_CONSUMER_CREATED,{id:u.id,appData:u.appData,peerId:e})}),Qn.replaceParticipantInMap(this.participants.videoSubscribed,t,n,!0),Qn.replaceParticipantInMap(this.participants.audioSubscribed,t,n,!1),this.participants.pinned.has(t)&&(i.setIsPinned(!1),n.setIsPinned(!0),Qn.replaceParticipantInMap(this.participants.pinned,t,n,!0)),this.logger.info(`Removing old peer ${t} locally after handover.`),this.onParticipantLeave(t).catch(u=>{this.logger.error("Failed to remove old peer locally after handover",{error:u})})}setupEventsGlobal(){this.roomSocketHandler.on(x.joinRoom,({peer:s})=>{s.waitlisted||(this.logger.info(`Processing socket join for ${this.self.id===s.peerId?"local peer":"remote peer"} ${s.peerId}.`),this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(s)),this.logger.info(`Processed socket join for ${this.self.id===s.peerId?"local peer":"remote peer"} ${s.peerId}.`))}),this.roomSocketHandler.on(x.leaveRoom,async s=>{const{peerId:t}=s.peer;this.logger.info(`peer ${t} left the meeting. Removing it from selected peers`),this.selectedPeers.delete(t,this.context),this.onParticipantLeave(t)}),this.context.getValue("peerSessionStore").on(P.SOCKET_SERVICE_ROOM_JOINED,()=>{this.self.permissions.acceptWaitingRequests&&this.roomSocketHandler.getWaitingRoomRequests()}),this.self.permissions.on("permissionsUpdate",s=>{const{acceptWaitingRequests:t}=s;t!==void 0&&(t?this.roomSocketHandler.getWaitingRoomRequests():this.participants.waitlisted.clear())}),this.context.getValue("peerSessionStore").on(P.PEER_CLOSED,({id:s})=>{this.logger.info(`Remote peer ${s} has left media room. Scheduling delayed consumer cleanup.`),this.scheduleSyncConsumers({source:"REMOTE_PEER_CLOSED"})}),this.context.getValue("peerSessionStore").on(P.MEDIA_ROOM_JOIN_FAILED,()=>{this.isRebuildingReconnectSnapshot&&(this.isRebuildingReconnectSnapshot=!1)}),this.context.getValue("peerSessionStore").on(P.SOCKET_SERVICE_DISCONNECTED,()=>{this.isRebuildingReconnectSnapshot=!1,f(this,pi,!0),R(this,gn,kd).call(this,"socket disconnected"),this.logger.info("Socket disconnected — keeping participants visible for seamless reconnection")}),this.context.getValue("peerSessionStore").on(P.TRANSPORT_STATE_UPDATE,({transport:s,state:t})=>{if(s==="recv"){if(t!=="connected"){R(this,gn,kd).call(this,`Recv transport not yet connected. state: ${t}`);return}this.logger.info("Receive transport connected; scheduling consumer reconciliation"),this.scheduleSyncConsumers({source:"RECV_TRANSPORT_CONNECTED"})}}),this.context.getValue("peerSessionStore").on(P.CONSUMER_PAUSED,({id:s})=>{this.processConsumerPaused(s)}),this.context.getValue("peerSessionStore").on(P.CONSUMER_RESUMED,({id:s})=>{this.processConsumerResumed(s)}),this.context.getValue("peerSessionStore").on(P.NEW_CONSUMER_CREATED,({id:s})=>{this.processNewConsumer(s)}),this.context.getValue("peerSessionStore").on(P.CONSUMER_CLOSED,({id:s})=>{const t=a(this,Ze).delete(s);this.logger.info(`Consumer closed: consumerId=${s}, wasMarkedForDeletion=${t}.`),this.processConsumerClosed(s)}),this.context.getValue("peerSessionStore").on(P.ROOM_MESSAGE,async({payload:s,type:t,timestamp:e})=>{this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(P.MESSAGE,async({payload:s,type:t,timestamp:e})=>{t!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(P.LOW_CONSUMER_SCORE,({peerId:s,score:t,kind:e})=>{const r=this.participants.joined.get(s);r&&(r.emit("poorConnection",{score:t,kind:e}),this.participants.emit("poorConnection",{participantId:s,score:t,kind:e}))}),this.context.getValue("peerSessionStore").on(P.CONSUMER_SCORE_UPDATE,({score:s,kind:t,appData:e,peerId:r,scoreStats:i})=>{var c;const n=t==="video"&&((c=e==null?void 0:e.screenShare)!=null?c:!1),o=this.participants.joined.get(r);o&&(o.emit("mediaScoreUpdate",{kind:t,isScreenshare:n,score:s,participantId:r,scoreStats:i}),this.participants.emit("mediaScoreUpdate",{kind:t,isScreenshare:n,score:s,participantId:r,scoreStats:i}))}),this.context.getValue("peerSessionStore").onAsync(P.KICK_PEER,async({peerId:s})=>{const t=this.participants.joined.get(s);this.roomNodeClient.kick(s),await this.roomSocketHandler.kick(s),t?t.emit("kicked"):this.participants.joined.emit("kicked",{id:s})}),this.context.getValue("peerSessionStore").on(P.UPDATE_ACTIVE,({viewMode:s,page:t}={})=>{this.isRebuildingReconnectSnapshot||(this.logger.info(`UPDATE_ACTIVE event received - viewMode: ${a(this,hs).mode}, page: ${t}`),this.updateMediaSubscribedMaps(s,{page:t}),this.scheduleSyncConsumers({source:"UPDATE_ACTIVE"}))})}async onParticipantPinned(s){if(!s){this.self.isPinned&&this.self.setIsPinned(!1),this.participants.pinned.size!==0&&this.updatePinnedParticipants();return}if(s===this.self.id){this.participants.pinned.size!==0&&this.updatePinnedParticipants(),this.self.setIsPinned(!0);return}const t=this.participants.joined.get(s);this.self.isPinned&&this.self.setIsPinned(!1),this.updatePinnedParticipants(),t.setIsPinned(!0),this.participants.pinned.add(t)}async onParticipantSocketJoined(s){var t,e,r;this.self.id!==s.id&&!((t=s.flags)!=null&&t.recorder)&&!((e=s.flags)!=null&&e.hidden_participant)&&!((r=s.flags)!=null&&r.hiddenParticipant)&&(this.isRebuildingReconnectSnapshot||(this.participants.videoSubscribed.delete(s.id),this.participants.audioSubscribed.delete(s.id)),this.participants.joined.add(s),this.participants.waitlisted.delete(s.id),s.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&this.context.getValue("peerSessionStore").emit(P.UPDATE_STAGE_REQUESTS,{request:{displayName:s.name,userId:s.userId,peerId:s.id},add:!0})),this.context.getValue("peerSessionStore").emit(P.PEER_JOINED_INTERNAL,s)}async onParticipantLeave(s){var e;this.logger.info(`peer ${s} has left. Deleting peer from participant maps`);const t=this.participants.joined.get(s);if(this.participants.joined.delete(s,!0,!0),this.participants.pinned.delete(s,!0,!0),this.participants.waitlisted.delete(s,!0,!0),(e=this.pip)==null||e.removeSource(s),t&&t.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&this.context.getValue("peerSessionStore").emit(P.UPDATE_STAGE_REQUESTS,{request:{displayName:t.name,userId:t.userId,peerId:t.id},add:!1}),!this.isRebuildingReconnectSnapshot){if(this.participants.viewMode==="PAGINATED"){const r=Math.max(1,Math.min(this.participants.currentPage,this.participants.pageCount));if(r!==this.participants.currentPage){await this.participants.setPage(r);return}}this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}}processMedia(s){var h;const t=this.roomNodeClient.getConsumers(),{peerId:e,kind:r,appData:i,track:n,producerId:o,rtpReceiver:c,paused:d,localId:l}=(h=t.get(s))!=null?h:{};if(!e)return this.logger.warn("processMedia::Peer ID is undefined",{consumer:{id:s,kind:r,peerId:e,appData:{supportsRemoteControl:!!(i!=null&&i.supportsRemoteControl),screenShare:!!(i!=null&&i.screenShare)},remotelyPaused:d,producerId:o}}),{};const u=i;return r==="video"&&u.screenShare!==!0&&this.videoPeerConsumerMap.set(e,s),this.logger.info("ParticipantController::processMedia",{consumer:{id:s,peerId:e,kind:r,appData:u,remotelyPaused:d,producerId:o}}),this.consumerPeerMap.set(s,{type:r,peerId:e,appData:u,remotelyPaused:d,producerId:o,trackId:n==null?void 0:n.id}),{peerId:e,kind:r,appData:u,remotelyPaused:d,track:n,producerId:o,rtpReceiver:c,localId:l}}processConsumerClosed(s){var l;const{peerId:t,type:e,appData:r,remotelyPaused:i,producerId:n,trackId:o}=this.consumerPeerMap.get(s)||{},c=this.participants.joined.get(t);if(this.logger.info("ParticipantController::processConsumerClosed",{consumer:{id:s,peerId:t,appData:r,kind:e,remotelyPaused:i,producerId:n}}),this.consumerPeerMap.delete(s),e==="video"&&(r==null?void 0:r.screenShare)!==!0&&this.videoPeerConsumerMap.get(t)===s&&this.videoPeerConsumerMap.delete(t),r!=null&&r.e2ee&&o&&this.context.getValue("peerSessionStore").emit(P.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:o}),!c)return;r!=null&&r.screenShare?this.context.getValue("callstats").consumerSharedMediaState(s,{screen:!1}):e==="audio"?this.context.getValue("callstats").consumerSharedMediaState(s,{audio:!1}):e==="video"&&this.context.getValue("callstats").consumerSharedMediaState(s,{video:!1});const d=c.producers.find(u=>u.producerId===n);if(((l=d==null?void 0:d.consumer)==null?void 0:l.id)!==s){this.logger.info(`Ignoring stale consumer media cleanup: consumerId=${s}, producerId=${n}, peerId=${t}.`);return}d.consumer={id:s,peerId:t,kind:void 0,appData:r,paused:i,producerId:n,rtpReceiver:void 0,localId:void 0},!(e!=="audio"&&e!=="video")&&this.clearParticipantMediaState(c,e,(r==null?void 0:r.screenShare)===!0)}processConsumerResumed(s){var g;const t=this.processMedia(s),{peerId:e,kind:r,appData:i,track:n,remotelyPaused:o,producerId:c,rtpReceiver:d,localId:l}=t;if(!e)return;this.logger.info("ParticipantController::processConsumerResumed",{consumer:{id:s,peerId:e,kind:r,appData:i,remotelyPaused:o,producerId:c}});const u=this.participants.joined.get(e);if(!u)return;const h=u.producers.find(v=>v.producerId===c);if(h&&(h.consumer={id:s,peerId:e,kind:r,appData:i,paused:o,producerId:c,rtpReceiver:d,localId:l}),i.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:d,track:n}),i.screenShare){r==="video"?u.screenShareTracks.video=n:r==="audio"&&(u.screenShareTracks.audio=n),u.setScreenShareEnabled(!0),(g=this.context)==null||g.getValue("callstats").consumerSharedMediaState(s,{screen:!0});return}r==="video"?(u.videoTrack=n,u.setVideoEnabled(!0),this.updatePipSource(u.id,!0),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!0})):r==="audio"&&(u.audioTrack=n,u.setAudioEnabled(u.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:u.audioEnabled}))}processConsumerPaused(s){this.logger.info(`ParticipantController::processConsumerPaused called for consumerId: ${s}`);const{peerId:t,kind:e,track:r,appData:i,remotelyPaused:n,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(s);if(!t)return;this.logger.info("ParticipantController::processConsumerPaused",{consumer:{id:s,peerId:t,kind:e,appData:i,remotelyPaused:n,producerId:o}});const l=this.participants.joined.get(t);if(!l)return;const u=l.producers.find(h=>h.producerId===o);u&&(u.consumer={id:s,peerId:t,kind:e,appData:i,paused:n,producerId:o,rtpReceiver:c,localId:d}),r&&i.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:r.id}),e==="video"?(l.videoTrack=r,l.setVideoEnabled(!1),this.updatePipSource(l.id,!1),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!1})):e==="audio"&&(l.audioTrack=r,l.setAudioEnabled(l.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:l.audioEnabled}))}processNewConsumer(s){const{peerId:t,kind:e,remotelyPaused:r,track:i,appData:n,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(s);if(!t)return;this.logger.info("ParticipantController::processNewConsumer",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:n,producerId:o}});const l=this.participants.joined.get(t);if(!l)return;const u=l.producers.find(h=>h.producerId===o);if(u&&(u.consumer={id:s,peerId:t,kind:e,appData:n,paused:r,producerId:o,rtpReceiver:c,localId:d}),n.screenShare){e==="video"?l.screenShareTracks.video=i:e==="audio"&&(l.screenShareTracks.audio=i),(!r||this.self.permissions.isRecorder)&&l.setScreenShareEnabled(!0),n.supportsRemoteControl&&(l.supportsRemoteControl=!0),this.participants.broadcastMessage("screenshareConsumerCreated",{producerId:o,peerId:t,screenShare:!0,consumerId:s,consumerPeerId:this.self.id}),this.logger.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:n,producerId:o}});return}e==="video"?(l.videoTrack=i,r||(l.setVideoEnabled(!0),this.updatePipSource(l.id,!0)),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!r})):e==="audio"&&(l.audioTrack=i,r||l.setAudioEnabled(!0),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:!r})),!r&&n.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_CONSUMER,{peerId:t,rtpReceiver:c,track:i}),this.context.getValue("peerSessionStore").emit(P.ENABLE_E2EE_CRYPTOR_ON_NEW_CONSUMER,{appData:n,peerId:l.id})}static formatSocketPeerMessage(s){var e,r,i,n,o,c;if(!s)return;const t=dp(s.stageType);return{id:s.peerId,userId:s.userId,name:s.displayName,displayName:s.displayName,stageType:t,customParticipantId:s.customParticipantId,presetId:s.presetId,picture:s.displayPictureUrl,waitlisted:s.waitlisted,stageStatus:t,metadata:{preset_name:(e=s.flags)==null?void 0:e.presetName},recorderType:(r=s.flags)==null?void 0:r.recorderType,flags:{hiddenParticipant:(i=s.flags)==null?void 0:i.hiddenParticipant,hidden_participant:(n=s.flags)==null?void 0:n.hiddenParticipant,recorder:((o=s.flags)==null?void 0:o.recorderType)!==void 0&&((c=s.flags)==null?void 0:c.recorderType)!=="NONE"}}}async onSelectedPeers(s,t){this.participants.viewMode==="ACTIVE_GRID"&&this.computeActivateParticipants(s,t)}updateActiveParticipantsWithPriorities(s,t=!1){if(this.participants.viewMode==="MANUAL")return;if(!this.mediaJoined){this.logger.warn("Skipped::ParticipantController::updateActiveParticipantsWithPriorities",{roomJoined:this.mediaJoined});return}s.forEach(r=>{this.selectedPeers.add(r.peerId,r.priority,this.context)});const e=this.selectedPeers.activeSpeakerPeers.at(0);e!==void 0&&e!==this.participants.lastActiveSpeaker&&(this.participants.lastActiveSpeaker=e,this.participants.emit("activeSpeaker",{peerId:e,volume:1})),t&&this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}},hs=new WeakMap,Fs=new WeakMap,pi=new WeakMap,Ze=new WeakMap,kr=new WeakMap,mn=new WeakMap,gn=new WeakSet,kd=function(s){a(this,kr)===void 0&&(f(this,kr,Date.now()),this.logger.info(`Consumer deletion aging paused: reason="${s}", consumerIds=[${Array.from(a(this,Ze).keys()).join(",")}].`))},cu=new WeakSet,uT=function(){if(a(this,kr)===void 0)return;const s=Date.now()-a(this,kr);a(this,Ze).forEach((t,e)=>{a(this,Ze).set(e,t+s)}),f(this,kr,void 0),this.logger.info(`Consumer deletion aging resumed: pausedDurationMs=${s}, consumerIds=[${Array.from(a(this,Ze).keys()).join(",")}].`)},du=new WeakSet,hT=function(s){return a(this,Ze).has(s.id)?!1:(a(this,Ze).set(s.id,Date.now()),!0)},mc=new WeakSet,tm=function(s,t){const e=s.peerId,r=!t.consumer||t.consumer.peerId!==t.producingPeerId||e!==t.producingPeerId;s.reassignPeer(t.producingPeerId);const i=a(this,Ze).delete(s.id);return r&&this.processNewConsumer(s.id),{needsRemap:r,wasMarkedForDeletion:i}},lu=new WeakSet,pT=function(){f(this,mn,setInterval(()=>{a(this,Ze).size!==0&&(this.logger.info(`Consumer deletion sweep scheduling reconciliation: consumerIds=[${Array.from(a(this,Ze).keys()).join(",")}].`),this.scheduleSyncConsumers({source:"CONSUMER_DELETION_SWEEP"}))},q1))},uu=new WeakSet,mT=function(){a(this,mn)!==void 0&&(clearInterval(a(this,mn)),f(this,mn,void 0))},hu=new WeakMap,QS);let pr=Qn;Bi([E.trace("ParticipantController.setupEvents")],pr.prototype,"setupEvents",1),Bi([E.trace("ParticipantController.setupEvents")],pr.prototype,"setupEventsGlobal",1),Bi([E.trace("ParticipantController.processMedia")],pr.prototype,"processMedia",1),Bi([E.trace("ParticipantController.processConsumerClosed")],pr.prototype,"processConsumerClosed",1),Bi([E.trace("ParticipantController.processConsumerResumed")],pr.prototype,"processConsumerResumed",1),Bi([E.trace("ParticipantController.processConsumerPaused")],pr.prototype,"processConsumerPaused",1),Bi([E.trace("ParticipantController.processNewConsumer")],pr.prototype,"processNewConsumer",1);const De=Ls(Nh().permissions),mu=class extends Bt{constructor(e,r,i,n=!1){const o=e.getValue("logger");super(o);m(this,Pt);m(this,z,void 0);m(this,Ia,void 0);m(this,Aa,void 0);m(this,pu,e=>{var l,u,h;const{chat:r,connectedMeetings:i,plugins:n,polls:o,media:c,...d}=e;if(r&&(r.private&&Ur(a(this,z).chat.private,r.private),r.public&&Ur(a(this,z).chat.public,r.public),this.emit("chatUpdate")),i&&Ur(a(this,z).connectedMeetings,i),c){const g=y=>{switch(y){case Fr.NONE:return G.Allowed;case Fr.ALLOWED:return G.Allowed;case Fr.NOT_ALLOWED:return G.NotAllowed;case Fr.CAN_REQUEST:return G.CanRequest;default:return}},v={audio:void 0,video:void 0,screenshare:void 0};(l=c.audio)!=null&&l.canProduce&&(v.audio={canProduce:g(c.audio.canProduce)}),(u=c.video)!=null&&u.canProduce&&(v.video={canProduce:g(c.video.canProduce)}),(h=c.screenshare)!=null&&h.canProduce&&(v.screenshare={canProduce:g(c.screenshare.canProduce)}),Ur(a(this,z).media,v)}n&&(Ur(a(this,z).plugins,n),this.emit("pluginsUpdate")),o&&(Ur(a(this,z).polls,o),this.emit("pollsUpdate")),Object.keys(d).length!==0&&Ur(a(this,z),d),this.emit("permissionsUpdate",e)});if(!r)throw this.logger.error("PermissionPreset::load_preset_permissions_failed"),new C("Could not load preset permissions.","0904");f(this,Aa,e),f(this,Ia,i),f(this,z,r),n&&this.setupEvents()}setupEvents(){a(this,Aa).getValue("peerSessionStore").on(P.UPDATE_PERMISSIONS,a(this,pu))}static init(e,r,i){let n;return i?n=new mu(e,i,r,!0):n=new mu(e,De,r),n}get mediaRoomType(){return"CF"}get stageEnabled(){var e;return((e=a(this,z))==null?void 0:e.stageEnabled)||a(this,Ia)===Ss.Webinar||a(this,Ia)===Ss.Livestream}get acceptStageRequests(){var e,r;return this.stageEnabled?((e=a(this,z))==null?void 0:e.acceptStageRequests)||((r=a(this,z))==null?void 0:r.canAcceptProductionRequests):!1}get stageAccess(){var e,r,i;return((e=a(this,z))==null?void 0:e.stageAccess)===G.NotAllowed?G.NotAllowed:((r=a(this,z))==null?void 0:r.stageAccess)===G.CanRequest?G.CanRequest:((i=a(this,z))==null?void 0:i.stageAccess)===G.Allowed||a(this,z).media.audio.canProduce===G.Allowed||a(this,z).media.video.canProduce===G.Allowed||a(this,z).media.screenshare.canProduce===G.Allowed?G.Allowed:a(this,z).media.audio.canProduce===G.CanRequest||a(this,z).media.video.canProduce===G.CanRequest||a(this,z).media.screenshare.canProduce===G.CanRequest?G.CanRequest:G.NotAllowed}get acceptWaitingRequests(){var e,r;return(r=(e=a(this,z))==null?void 0:e.acceptWaitingRequests)!=null?r:De.acceptWaitingRequests}get requestProduceVideo(){var e,r,i;return((i=(r=(e=a(this,z))==null?void 0:e.media)==null?void 0:r.video)==null?void 0:i.canProduce)===G.CanRequest}get requestProduceAudio(){var e,r,i;return((i=(r=(e=a(this,z))==null?void 0:e.media)==null?void 0:r.audio)==null?void 0:i.canProduce)===G.CanRequest}get requestProduceScreenshare(){var e,r,i;return((i=(r=(e=a(this,z))==null?void 0:e.media)==null?void 0:r.screenshare)==null?void 0:i.canProduce)===G.CanRequest}get canAllowParticipantAudio(){var e,r;return(r=(e=a(this,z))==null?void 0:e.disableParticipantAudio)!=null?r:De.disableParticipantAudio}get canAllowParticipantScreensharing(){var e,r;return(r=(e=a(this,z))==null?void 0:e.canAcceptProductionRequests)!=null?r:De.canAcceptProductionRequests}get canAllowParticipantVideo(){var e,r;return(r=(e=a(this,z))==null?void 0:e.disableParticipantVideo)!=null?r:De.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var e,r;return(r=(e=a(this,z))==null?void 0:e.kickParticipant)!=null?r:De.kickParticipant}get pinParticipant(){var e,r;return(r=(e=a(this,z))==null?void 0:e.pinParticipant)!=null?r:De.pinParticipant}get canRecord(){var e,r;return(r=(e=a(this,z))==null?void 0:e.canRecord)!=null?r:De.canRecord}get waitingRoomBehaviour(){var e,r;return(r=(e=a(this,z))==null?void 0:e.waitingRoomType)!=null?r:De.waitingRoomType}get plugins(){var e,r;return(r=(e=a(this,z))==null?void 0:e.plugins)!=null?r:De.plugins}get polls(){var e,r;return(r=(e=a(this,z))==null?void 0:e.polls)!=null?r:De.polls}get canProduceVideo(){var r;const e=(r=a(this,z).media.video.canProduce)!=null?r:De.media.video.canProduce;return this.stageEnabled&&(a(this,Pt,es)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Pt,es)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,Pt,es)==="OFF_STAGE"||a(this,Pt,es)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get canProduceScreenshare(){var r;const e=(r=a(this,z).media.screenshare.canProduce)!=null?r:De.media.screenshare.canProduce;return this.stageEnabled&&(a(this,Pt,es)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Pt,es)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,Pt,es)==="OFF_STAGE"||a(this,Pt,es)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get canProduceAudio(){var r;const e=(r=a(this,z).media.audio.canProduce)!=null?r:De.media.audio.canProduce;return this.stageEnabled&&(a(this,Pt,es)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Pt,es)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,Pt,es)==="OFF_STAGE"||a(this,Pt,es)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get chatPublic(){var e,r,i;return(i=(r=(e=a(this,z))==null?void 0:e.chat)==null?void 0:r.public)!=null?i:De.chat.public}get chatPrivate(){var e,r,i;return(i=(r=(e=a(this,z))==null?void 0:e.chat)==null?void 0:r.private)!=null?i:De.chat.private}get connectedMeetings(){var e,r;return(r=(e=a(this,z))==null?void 0:e.connectedMeetings)!=null?r:De==null?void 0:De.connectedMeetings}get hiddenParticipant(){var e,r;return(r=(e=a(this,z))==null?void 0:e.hiddenParticipant)!=null?r:De.hiddenParticipant}get showParticipantList(){var e;return(e=a(this,z).showParticipantList)!=null?e:De.showParticipantList}get canChangeParticipantPermissions(){var e,r;return(r=(e=a(this,z))==null?void 0:e.canChangeParticipantPermissions)!=null?r:De.canChangeParticipantPermissions}get canEditDisplayName(){var e;return(e=a(this,z).canEditDisplayName)!=null?e:!1}get canEditMeetingTitle(){var e,r;return(r=(e=a(this,z))==null?void 0:e.canEditMeetingTitle)!=null?r:!1}get isRecorder(){return a(this,z).isRecorder}get canSpotlight(){return a(this,z).canSpotlight}get canLivestream(){return a(this,z).canLivestream}get transcriptionEnabled(){return a(this,z).transcriptionEnabled}};let Ep=mu;z=new WeakMap,Ia=new WeakMap,Aa=new WeakMap,pu=new WeakMap,Pt=new WeakSet,es=function(){return a(this,Aa).getValue("stageStatus")};class eS extends Bt{constructor(e,r){super(r);p(this,"localMediaHandler");m(this,zt,void 0);f(this,zt,e)}async updatePermission(){var d,l;const e=(u,h)=>{this.mediaPermissions[u]=h;const g={message:this.mediaPermissions[u],kind:u};h==="DENIED"?a(this,zt).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_ERROR,g):a(this,zt).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,g)};if(Pe.getName()==="firefox")return;const r="microphone",i="camera",n=await((d=navigator==null?void 0:navigator.permissions)==null?void 0:d.query({name:r})),o=await((l=navigator==null?void 0:navigator.permissions)==null?void 0:l.query({name:i})),c=(u,h)=>{switch(h){case"granted":e(u,"ACCEPTED");break;case"denied":e(u,"DENIED");break;case"prompt":e(u,"NOT_REQUESTED");break}this.localMediaHandler.repopulateAvailableDevices()};n&&(n.onchange=()=>c("audio",n.state)),o&&(o.onchange=()=>c("video",o.state))}async populateMediaPermissionsInCallstats({message:e,kind:r}){var i,n,o,c;switch(r){case"audio":{(i=a(this,zt))==null||i.getValue("callstats").mediaPermission("AUDIO",e),(n=a(this,zt))==null||n.getValue("callstats").mediaPermission("SPEAKER",e);break}case"video":{(o=a(this,zt))==null||o.getValue("callstats").mediaPermission("VIDEO",e);break}case"screenshare":{(c=a(this,zt))==null||c.getValue("callstats").mediaPermission("SCREENSHARE",e);break}}}get peerId(){var e;return(e=a(this,zt))==null?void 0:e.getValue("peerId")}async init(e={},r=!1,i=null){var n,o,c,d,l,u,h;if(Pe.init(),i&&f(this,zt,i),!this.localMediaHandler)try{let g=!0;if((n=i==null?void 0:i.getValue("defaults"))!=null&&n.mediaHandler)g=!1,this.localMediaHandler=i.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:v}=navigator;this.localMediaHandler=await v.init(e)}else this.localMediaHandler=new Dt(i,e.constraints,(o=i==null?void 0:i.getValue("defaults"))==null?void 0:o.isNonPreferredDevice,(c=i==null?void 0:i.getValue("defaults"))==null?void 0:c.autoSwitchAudioDevice);if(i==null||i.getValue("peerSessionStore").on(P.MEDIA_PERMISSION_UPDATE,async v=>{if(this.populateMediaPermissionsInCallstats({message:v.message,kind:v.kind}),v.message==="NOT_REQUESTED")switch(v==null?void 0:v.kind){case"audio":this.rawAudioTrack&&(this.logger.info("Disabling audio due to media permission update"),this.disableAudio());break;case"video":this.rawVideoTrack&&(this.logger.info("Disabling video due to media permission update"),this.disableVideo());break;default:break}this.emit("mediaPermissionUpdate",v)}),i==null||i.getValue("peerSessionStore").on(P.MEDIA_PERMISSION_ERROR,async v=>{const{kind:y,message:k,constraints:I}=v;this.populateMediaPermissionsInCallstats({message:k,kind:y}),y==="audio"?(this.logger.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):y==="video"&&(this.logger.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),this.logger.error("SelfController::mediaPermissionError",{error:{message:k},constraints:I,mediaPermissionsErrors:{kind:y,message:k}}),this.emit("mediaPermissionError",v),this.emit("mediaPermissionUpdate",{message:k,kind:y})}),g){this.logger.info(`Setting up SelfMedia streams using media handler. audio:${(d=e==null?void 0:e.audio)!=null?d:!0} video:${(l=e==null?void 0:e.video)!=null?l:!0}`);const v=this.localMediaHandler.setupStreams({video:(u=e==null?void 0:e.video)!=null?u:!0,audio:(h=e==null?void 0:e.audio)!=null?h:!0});r||await v}}catch(g){this.logger.error("Self::init::Failed To Setup Streams",{error:{name:g.name,message:g.message}})}}set context(e){f(this,zt,e),this.localMediaHandler.context=e}get audioTrack(){return this.localMediaHandler.audioTrack}get rawAudioTrack(){return this.localMediaHandler.rawAudioTrack}get mediaPermissions(){return this.localMediaHandler.permissions}async addAudioMiddleware(e){return this.localMediaHandler.addAudioMiddleware(e)}async removeAudioMiddleware(e){return this.localMediaHandler.removeAudioMiddleware(e)}async removeAllAudioMiddlewares(){return this.localMediaHandler.removeAllAudioMiddlewares()}get videoTrack(){return this.localMediaHandler.videoTrack}get rawVideoTrack(){return this.localMediaHandler.rawVideoTrack}async addVideoMiddleware(e){return this.localMediaHandler.addVideoMiddleware(e)}async setVideoMiddlewareGlobalConfig(e={disablePerFrameCanvasRendering:!1}){return this.localMediaHandler.setVideoMiddlewareGlobalConfig(e)}async removeVideoMiddleware(e){return this.localMediaHandler.removeVideoMiddleware(e)}async removeAllVideoMiddlewares(){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}async enableAudio(){await this.localMediaHandler.enableAudio(),this.logger.info(`Emitting audioUpdate to the UI Kit for self. Audio enabled: ${this.audioEnabled}. Audio track available: ${!!this.audioTrack}.`),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableVideo(){await this.localMediaHandler.enableVideo(),this.logger.info(`Emitting videoUpdate to the UI Kit for self. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}async disableAudio(){this.localMediaHandler.disableAudio(),this.logger.info(`Emitting audioUpdate to the UI Kit for self. Audio enabled: ${this.audioEnabled}. Audio track available: ${!!this.audioTrack}.`),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableScreenShare(){var e;await this.localMediaHandler.enableScreenShare(),this.logger.info(`Emitting screenShareUpdate to the UI Kit for self. Screen sharing enabled: ${this.screenShareEnabled}. Video track available: ${!!((e=this.screenShareTracks)!=null&&e.video)}.`),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableScreenShare(){var e;await this.localMediaHandler.disableScreenShare(),this.logger.info(`Emitting screenShareUpdate to the UI Kit for self. Screen sharing enabled: ${this.screenShareEnabled}. Video track available: ${!!((e=this.screenShareTracks)!=null&&e.video)}.`),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableVideo(){await this.localMediaHandler.disableVideo(),this.logger.info(`Emitting videoUpdate to the UI Kit for self. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}getCurrentDevices(){return this.localMediaHandler.getCurrentDevices()}async getAudioDevices(){return await this.localMediaHandler.getAudioDevices()}async getVideoDevices(){return await this.localMediaHandler.getVideoDevices()}async getSpeakerDevices(){return await this.localMediaHandler.getSpeakerDevices()}getDeviceById(e,r){let i;return r==="audio"?i="audioinput":r==="video"?i="videoinput":r==="speaker"&&(i="audiooutput"),this.localMediaHandler.getDeviceById(e,i)}async setDevice(e){switch(e.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(e,{saveDevicePreference:!0})}catch(r){}finally{this.logger.info(`Emitting audioUpdate to the UI Kit for self. Audio enabled: ${this.audioEnabled}. Audio track available: ${!!this.audioTrack}.`),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":await this.localMediaHandler.setSpeakerDevice(e,{saveDevicePreference:!0});break;case"videoinput":try{await this.localMediaHandler.setVideoDevice(e,{saveDevicePreference:!0})}catch(r){}finally{this.logger.info(`Emitting videoUpdate to the UI Kit for self. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})}}zt=new WeakMap;var G1=Object.defineProperty,W1=Object.getOwnPropertyDescriptor,yt=(s,t,e,r)=>{for(var i=r>1?void 0:r?W1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&G1(t,e,i),i};let ze=(XS=class extends eS{constructor(t,e,r,i,n){const o=t.getValue("logger");super(t,o);m(this,_r);m(this,tt);m(this,Da);m(this,Fe);m(this,gc);p(this,"name");p(this,"picture");p(this,"customParticipantId");p(this,"waitlistStatus");m(this,Ma,void 0);m(this,kt,void 0);m(this,Oa,void 0);p(this,"role");p(this,"userId");p(this,"organizationId");p(this,"supportsRemoteControl",!1);p(this,"device");m(this,et,void 0);p(this,"hidden",!1);p(this,"presetName");p(this,"roomState","init");m(this,Na,new Set);m(this,La,new Set);f(this,et,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=e.customParticipantId,this.waitlistStatus="none",f(this,kt,r),f(this,Ma,i),this.hidden=!1,f(this,Oa,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=Pe.isElectron(),this.device=Pe.getDeviceInfo(),this.presetName=n,this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),R(this,gc,sm).call(this)}get telemetry(){return a(this,et).getValue("telemetry")}get stageStatus(){return a(this,et).getValue("stageStatus")}get producers(){var t,e;return Array.from((e=(t=a(this,tt,St).getProducers())==null?void 0:t.values())!=null?e:[])}get id(){return this.peerId}get peerId(){return a(this,et).getValue("peerId")}static async __init__(t,e,r,i,n,o=!1){var g,v,y,k,I,D;let c=(v=(g=t.getValue("defaults"))==null?void 0:g.audio)!=null?v:!0,d=(k=(y=t.getValue("defaults"))==null?void 0:y.video)!=null?k:!0;r.canProduceAudio!=="ALLOWED"&&(c=!1),r.canProduceVideo!=="ALLOWED"&&(d=!1);const l=new ze(t,e,r,i,n),u=t1(i.mediaConstraints);Ur(u,(I=t.getValue("defaults"))==null?void 0:I.mediaConfiguration);const h=(D=t.getValue("defaults"))==null?void 0:D.mediaHandler;return h&&(h.context=t),await l.init({audio:c,video:d,constraints:u},o,t),l.setupEvents(),l}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"),a(this,kt).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",R(this,gc,sm));const t=a(this,Da,rh);t&&t.onError(e=>{this.emit("autoplayError",e)}),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::AUDIO_TRACK_CHANGE",{...Ui(this)}),a(this,Fe,Je)&&this.audioEnabled)try{await a(this,tt,St).shareMic(this.audioTrack)}catch(e){this.logger.error("Self::setupEvents::Error while sharing mic",{error:e}),this.localMediaHandler.disableAudio()}this.logger.info(`Emitting audioUpdate to the UI Kit for self. Audio enabled: ${this.audioEnabled}. Audio track available: ${!!this.audioTrack}.`),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}),this.localMediaHandler.on("VIDEO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::VIDEO_TRACK_CHANGE",{...Ui(this)}),a(this,Fe,Je)&&this.rawVideoTrack===void 0)this.logger.info("Self::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&a(this,Fe,Je))try{await a(this,tt,St).shareWebcam(this.videoTrack)}catch(e){this.logger.error("Self::setupEvents::failed shareWebcam",{error:e}),this.videoEnabled&&await this.localMediaHandler.disableVideo()}this.logger.info(`Emitting videoUpdate to the UI Kit for self. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}),this.localMediaHandler.on("DEVICE_CHANGE",async({device:e})=>{var r;this.emit("deviceUpdate",{device:e}),e.kind==="audiooutput"&&typeof HTMLAudioElement.prototype.setSinkId=="function"&&((r=a(this,Da,rh))==null||r.setSpeakerDevice(e.deviceId))}),this.localMediaHandler.on("DEVICE_LIST_UPDATED",e=>{this.emit("deviceListUpdate",e)}),this.localMediaHandler.on("SCREENSHARE_TRACK_CHANGE",async()=>{var e;if(!a(this,Fe,Je)){this.logger.error("Self.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{await a(this,tt,St).shareScreen(this.screenShareTracks)}catch(r){this.logger.error("Self::setupEvents::Error while sharing screen",{error:r}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.logger.info("Self::setupEvents::SCREENSHARE_TRACK_CHANGE",{...Ui(this)}),this.logger.info(`Emitting screenShareUpdate to the UI Kit for self. Screen sharing enabled: ${this.screenShareEnabled}. Video track available: ${!!((e=this.screenShareTracks)!=null&&e.video)}.`),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}),this.localMediaHandler.on("SCREENSHARE_ENDED",async()=>{this.logger.log("Disabling screenshare due to SCREENSHARE_ENDED"),await this.disableScreenShare(),this.logger.info("Self::setupEvents::SCREENSHARE_ENDED",{...Ui(this)})}),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{var e;(e=a(this,et))==null||e.getValue("callstats").mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",async()=>{var e;a(this,Fe,Je)&&await a(this,tt,St).pauseWebcam(),this.logger.info(`Emitting videoUpdate to the UI Kit for self. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(e=a(this,et))==null||e.getValue("callstats").videoOff()}),a(this,kt).on("permissionsUpdate",e=>{var r,i,n;(r=e==null?void 0:e.media)!=null&&r.audio&&a(this,kt).canProduceAudio!==G.Allowed&&(this.disableAudio(),this.logger.info(`Disabled audio due to dynamic preset change: canProduceAudio: ${this.permissions.canProduceAudio}`)),(i=e==null?void 0:e.media)!=null&&i.video&&a(this,kt).canProduceVideo!==G.Allowed&&(this.disableVideo(),this.logger.info(`Disabled video due to dynamic preset change: canProduceVideo: ${this.permissions.canProduceVideo}`)),(n=e==null?void 0:e.media)!=null&&n.screenshare&&a(this,kt).canProduceScreenshare!==G.Allowed&&(this.disableScreenShare(),this.logger.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return a(this,kt)}get config(){return a(this,Ma)}get roomJoined(){var t;return a(this,Ma).viewType===Ss.Livestream&&this.stageStatus!=="ON_STAGE"?((t=a(this,et).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:a(this,Fe,Je)}setName(t){if(!t)throw new C("Name cannot be empty.","1103");this.name=t}async setupTracks(t={}){t.forceReset,await this.disableAudio(),await this.disableVideo(),this.localMediaHandler.removeAudioTrack(),this.localMediaHandler.removeVideoTrack(),t.audio&&await this.enableAudio(),t.video&&await this.enableVideo()}async destructMediaHandler(){return this.localMediaHandler.destruct()}async removeDocumentEventListeners(){return this.localMediaHandler.removeDocumentEventListeners()}async enableAudio(t){var e;if(this.permissions.canProduceAudio!==G.NotAllowed&&!(a(this,kt).canProduceAudio===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if((e=a(this,et))==null||e.getValue("callstats").audioOn(),await this.localMediaHandler.enableAudio(t),a(this,Fe,Je)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{await a(this,tt,St).shareMic(this.audioTrack)}catch(r){this.logger.error("Self::enableAudio::Error while sharing mic",{error:r}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return}this.logger.info(`Emitting audioUpdate to the UI Kit for self. Audio enabled: ${this.audioEnabled}. Audio track available: ${!!this.audioTrack}.`),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}}async enableVideo(t){var e;if(a(this,kt).canProduceVideo!==G.NotAllowed&&!(a(this,kt).canProduceVideo===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if((e=a(this,et))==null||e.getValue("callstats").videoOn(),await this.localMediaHandler.enableVideo(t),a(this,Fe,Je)&&this.stageStatus==="ON_STAGE")try{await a(this,tt,St).shareWebcam(this.videoTrack)}catch(r){this.logger.error("Self::enableVideo::Error while sharing video",{error:r}),this.videoEnabled&&this.localMediaHandler.disableVideo()}this.logger.info(`Emitting videoUpdate to the UI Kit for self. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),this.logger.info("Self.enableVideo",{...Ui(this)})}}async updateVideoConstraints(t){if(!this.localMediaHandler.updateVideoConstraints)throw new C("Unsupported","1102");await this.localMediaHandler.updateVideoConstraints(t)}async enableScreenShare(){var t;if(!a(this,Fe,Je))throw new C("Can`t enable screenshare without joining room","1105");if(a(this,kt).canProduceScreenshare!==G.NotAllowed&&!(a(this,kt).canProduceScreenshare===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&(this.screenShareEnabled&&this.logger.info("An screen share is already active, showing picker to select a new screen share"),await this.localMediaHandler.enableScreenShare(),this.screenShareTracks.audio||this.screenShareTracks.video)){try{await a(this,tt,St).shareScreen(this.screenShareTracks)}catch(e){this.logger.error("Self::enableScreenShare::Error while sharing screen",{error:e}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.logger.info(`Emitting screenShareUpdate to the UI Kit for self. Screen sharing enabled: ${this.screenShareEnabled}. Video track available: ${!!((t=this.screenShareTracks)!=null&&t.video)}.`),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}}async updateScreenshareConstraints(t){if(!this.localMediaHandler.updateScreenshareConstraints)throw new C("Unsupported","1102");await this.localMediaHandler.updateScreenshareConstraints(t)}async disableAudio(){var t;this.audioEnabled&&(this.localMediaHandler.disableAudio(),a(this,Fe,Je)&&a(this,tt,St).muteSelf(),this.logger.info(`Emitting audioUpdate to the UI Kit for self. Audio enabled: ${this.audioEnabled}. Audio track available: ${!!this.audioTrack}.`),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),(t=a(this,et))==null||t.getValue("callstats").audioOff())}async disableVideo(){var t;this.videoEnabled&&(await this.localMediaHandler.disableVideo(),a(this,Fe,Je)&&await a(this,tt,St).pauseWebcam(),this.logger.info(`Emitting videoUpdate to the UI Kit for self. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(t=a(this,et))==null||t.getValue("callstats").videoOff())}async disableScreenShare(){var t;this.screenShareEnabled&&(await this.localMediaHandler.disableScreenShare(),a(this,Fe,Je)&&await a(this,tt,St).disableScreenShare(),this.logger.info(`Emitting screenShareUpdate to the UI Kit for self. Screen sharing enabled: ${this.screenShareEnabled}. Video track available: ${!!((t=this.screenShareTracks)!=null&&t.video)}.`),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var i;f(this,Oa,t);const r=t?"pinned":"unpinned";(i=a(this,_r,Vn))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}get isPinned(){return a(this,Oa)}async pin(){if(!a(this,Fe,Je))throw new C("Can`t pin participants without joining room","1105");return this.show(),a(this,tt,St).pinPeer(this.id)}async unpin(){if(!a(this,Fe,Je))throw new C("Can`t unpin participants without joining room","1105");return a(this,tt,St).pinPeer(null)}async hide(){if(!a(this,Fe,Je))throw new C("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})}show(){if(!a(this,Fe,Je))throw new C("Can`t toggle participant tile without joining room","1105");this.hidden=!1,this.emit("toggleTile",{hidden:this.hidden})}async setDevice(t){var r,i,n;if(!t)throw new C("No device selected","1104");const e=this.getCurrentDevices();switch(t.deviceId&&(((r=e==null?void 0:e.audio)==null?void 0:r.deviceId)===t.deviceId||((i=e==null?void 0:e.video)==null?void 0:i.deviceId)===t.deviceId||((n=e==null?void 0:e.speaker)==null?void 0:n.deviceId)===t.deviceId)&&this.logger.warn("Self.setDevice.setting_to_in_use_device",{devices:[t]}),t.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(t,{saveDevicePreference:!0})}catch(o){a(this,Fe,Je)&&await a(this,tt,St).muteSelf(),this.logger.info(`Emitting audioUpdate to the UI Kit for self. Audio enabled: ${this.audioEnabled}. Audio track available: ${!!this.audioTrack}.`),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":await this.localMediaHandler.setSpeakerDevice(t,{saveDevicePreference:!0});break;case"videoinput":try{await this.localMediaHandler.setVideoDevice(t,{saveDevicePreference:!0})}catch(o){a(this,Fe,Je)&&await a(this,tt,St).pauseWebcam(),this.logger.info(`Emitting videoUpdate to the UI Kit for self. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}}cleanUpTracks(){var t,e,r,i;(t=this.audioTrack)==null||t.stop(),(e=this.rawAudioTrack)==null||e.stop(),(r=this.videoTrack)==null||r.stop(),(i=this.rawVideoTrack)==null||i.stop()}playAudio(){var t;return(t=a(this,Da,rh))==null?void 0:t.play()}registerVideoElement(t,e=!1){var r,i;t&&(e?a(this,Na).add(t):a(this,La).add(t),this.updateVideo(t),e||(i=a(this,_r,Vn))==null||i.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(r=this.raised)!=null?r:!1))}deregisterVideoElement(t,e=!1){if(!t){a(this,_r,Vn).removeSource(this.id);return}t.srcObject=void 0,e?a(this,Na).delete(t):(a(this,La).delete(t),a(this,_r,Vn).removeSource(this.id))}updateVideo(t,e=!1){var r,i,n;if(this.videoEnabled){if(this.videoTrack==null)return;const o=(r=t.srcObject)==null?void 0:r.getTracks()[0];if((o==null?void 0:o.id)===this.videoTrack.id)return;const c=new MediaStream;c.addTrack(this.videoTrack),t.srcObject=c,e||(i=a(this,_r,Vn))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(n=a(this,_r,Vn))==null||n.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},Ma=new WeakMap,kt=new WeakMap,Oa=new WeakMap,et=new WeakMap,_r=new WeakSet,Vn=function(){return a(this,et).getValue("pip")},tt=new WeakSet,St=function(){return a(this,et).getValue("roomNodeClient")},Da=new WeakSet,rh=function(){return a(this,et).getValue("audioPlayback")},Fe=new WeakSet,Je=function(){var t;return((t=a(this,et).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Na=new WeakMap,La=new WeakMap,gc=new WeakSet,sm=function(){Array.from(a(this,La)).forEach(t=>this.updateVideo(t,!1)),Array.from(a(this,Na)).forEach(t=>this.updateVideo(t,!0))},XS);yt([E.trace("Self.cleanupEvents")],ze.prototype,"cleanupEvents",1),yt([E.trace("Self.setupEvents")],ze.prototype,"setupEvents",1),yt([E.trace("Self.setupTracks")],ze.prototype,"setupTracks",1),yt([E.trace("Self.destructMediaHandler")],ze.prototype,"destructMediaHandler",1),yt([E.trace("Self.removeDocumentEventListeners")],ze.prototype,"removeDocumentEventListeners",1),yt([ur.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"Self.toggleAudio",timeout:3e3}),E.trace("Self.enableAudio")],ze.prototype,"enableAudio",1),yt([ur.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"Self.toggleVideo",timeout:3e3}),E.trace("Self.enableVideo")],ze.prototype,"enableVideo",1),yt([E.trace("Self.updateVideoConstraints")],ze.prototype,"updateVideoConstraints",1),yt([E.trace("Self.enableScreenShare"),ur.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3})],ze.prototype,"enableScreenShare",1),yt([E.trace("Self.updateScreenshareConstraints")],ze.prototype,"updateScreenshareConstraints",1),yt([ur.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"Self.toggleAudio",timeout:3e3}),E.trace("Self.disableAudio")],ze.prototype,"disableAudio",1),yt([ur.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"Self.toggleVideo",timeout:3e3}),E.trace("Self.disableVideo")],ze.prototype,"disableVideo",1),yt([ur.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3}),E.trace("Self.disableScreenShare")],ze.prototype,"disableScreenShare",1),yt([E.trace("Self.setDevice")],ze.prototype,"setDevice",1),ze=yt([pt("1100")],ze);class bp extends Error{constructor(t){super(t!=null?t:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,bp)}}class wp extends Error{constructor(t){super(t!=null?t:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,wp)}}class Pp{constructor(t,e=!1){p(this,"pendingTasks",new Map);p(this,"nextTaskId",0);p(this,"stopping",!1);m(this,fc,void 0);this.log=e,f(this,fc,{info:e&&t?t.info:()=>{}})}get size(){return this.pendingTasks.size}async push(t,e,r){if(e=e!=null?e:t.name,typeof t!="function")throw new TypeError("given task is not a function");if(e)try{Object.defineProperty(t,"name",{value:e})}catch(i){}return new Promise((i,n)=>{const o={id:this.nextTaskId++,task:t,metadata:r,name:e,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:c=>{if(o.completed)return;o.completed=!0,this.pendingTasks.delete(o.id),i(c);const[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)},reject:c=>{if(!o.completed&&(o.completed=!0,this.pendingTasks.delete(o.id),n(c),!this.stopping)){const[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)}}};this.pendingTasks.set(o.id,o),this.pendingTasks.size===1&&this.execute(o)})}stop(){this.stopping=!0;for(const t of this.pendingTasks.values())t.reject(new bp);this.stopping=!1}remove(t){const e=Array.from(this.pendingTasks.values())[t];e&&e.reject(new wp)}get(t){return Array.from(this.pendingTasks.values())[t]}dump(){const t=Date.now();let e=0;return Array.from(this.pendingTasks.values()).map(r=>({idx:e++,task:r.task,name:r.name,enqueuedTime:r.executedAt?r.executedAt-r.enqueuedAt:t-r.enqueuedAt,executionTime:r.executedAt?t-r.executedAt:0}))}async execute(t){if(t.executedAt)throw new Error("task already being executed");t.executedAt=Date.now();try{const e=this.pendingTasks.size,r=await t.task(),i=Date.now();a(this,fc).info(`AwaitQueue.push(${t.name})_timings`,{awaitQueueTask:{id:t.id,metadata:t.metadata,queueSizeAtStart:e,execTime:(i-t.executedAt)/1e3,taskStartTime:(t.executedAt-t.enqueuedAt)/1e3}}),t.resolve(r)}catch(e){t.reject(e)}}}fc=new WeakMap;class Ao extends Error{constructor(t){super(t),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Ao):this.stack=new Error(t).stack}}class Nt extends Error{constructor(t){super(t),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Nt):this.stack=new Error(t).stack}}class Jr extends Error{constructor(t){super(t),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Nt):this.stack=new Error(t).stack}}const tS=s=>new Promise(t=>setTimeout(t,s));async function kl(s,t){return new Promise(async(e,r)=>{const{strategy:i,maxRetryCount:n,delayTime:o}={strategy:"linear",maxRetryCount:3,delayTime:10,...t};let c=0,d,l=!1;const u=h=>{l=!0,r(h)};for(;c<n;){try{const h=await s(c,u);return e(h)}catch(h){if(d=h,l)break;if(c<n)i==="linear"?await tS(o*(c+1)):i==="exponential"&&await tS(o*(c+Math.max(0,c-1)));else break}c+=1}return r(d)})}const _l={VP8:"video/VP8",VP9:"video/VP9",H264:"video/H264",H265:"video/H265",AV1:"video/AV1"},Fi={OPUS:"audio/opus",PCMA:"audio/PCMA",PCMU:"audio/PCMU"},sS={video:_l.VP8,audio:Fi.OPUS,screenshareVideo:_l.VP8,screenshareAudio:Fi.OPUS};function J1(s,t){return typeof s=="string"&&Object.prototype.hasOwnProperty.call(t,s)}function Cl(s,t,e){const r=s||e;if(!J1(r,t))return{valid:!1,message:`Invalid codec "${String(r)}". Expected one of: ${Object.keys(t).join(", ")}.`};const i=t[r],n=i.startsWith("audio/")?"audio":"video",o=RTCRtpSender.getCapabilities(n);return o!=null&&o.codecs.some(c=>c.mimeType.toLowerCase()===i.toLowerCase())?{valid:!0,mimeType:i}:{valid:!1,message:`Codec "${r}" (${i}) is not supported for sending ${n} in this browser.`}}function K1(s){var n,o,c,d;const t=Cl((n=s==null?void 0:s.video)==null?void 0:n.codec,_l,"VP8");if(t.valid===!1)return{valid:!1,message:`defaults.mediaProducerConfiguration.video.codec: ${t.message}`};const e=Cl((o=s==null?void 0:s.audio)==null?void 0:o.codec,Fi,"OPUS");if(e.valid===!1)return{valid:!1,message:`defaults.mediaProducerConfiguration.audio.codec: ${e.message}`};const r=Cl((c=s==null?void 0:s.screenshareVideo)==null?void 0:c.codec,_l,"VP8");if(r.valid===!1)return{valid:!1,message:`defaults.mediaProducerConfiguration.screenshareVideo.codec: ${r.message}`};const i=Cl((d=s==null?void 0:s.screenshareAudio)==null?void 0:d.codec,Fi,"OPUS");return i.valid===!1?{valid:!1,message:`defaults.mediaProducerConfiguration.screenshareAudio.codec: ${i.message}`}:{valid:!0,codecs:{video:t.mimeType,audio:e.mimeType,screenshareVideo:r.mimeType,screenshareAudio:i.mimeType}}}function z1(s){return s.map(t=>({channels:t.channels,clockRate:t.clockRate,mimeType:t.mimeType,sdpFmtpLine:t.sdpFmtpLine}))}function Y1(s){return s.map(t=>({uri:t.uri}))}function Rl(s,t){const e=t?s.codecs.filter(({mimeType:i})=>t.some(n=>n.toLowerCase()===i.toLowerCase())):s.codecs;return{codecs:z1(e),headerExtensions:Y1(s.headerExtensions?s.headerExtensions:[])}}function Q1(s=sS){const t=RTCRtpReceiver.getCapabilities("audio"),e=RTCRtpReceiver.getCapabilities("video"),r=RTCRtpSender.getCapabilities("audio"),i=RTCRtpSender.getCapabilities("video"),n={audio:Rl(t),video:Rl(e)};return{sender:{audio:Rl(r,[s.audio,s.screenshareAudio]),video:Rl(i,[s.video,s.screenshareVideo])},receiver:n}}var rS={},Il={},X1={get exports(){return Il},set exports(s){Il=s}},iS=X1.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(s){return s.encoding?"rtpmap:%d %s/%s/%s":s.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(s){return s.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(s){return s.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(s){return"extmap:%d"+(s.direction?"/%s":"%v")+(s["encrypt-uri"]?" %s":"%v")+" %s"+(s.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(s){return s.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{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(s){var t="candidate:%s %d %s %d %s %d typ %s";return t+=s.raddr!=null?" raddr %s rport %d":"%v%v",t+=s.tcptype!=null?" tcptype %s":"%v",s.generation!=null&&(t+=" generation %d"),t+=s["network-id"]!=null?" network-id %d":"%v",t+=s["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(s){var t="ssrc:%d";return s.attribute!=null&&(t+=" %s",s.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(s){return s.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(s){return s.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(s){return"imageattr:%s %s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(s){return"simulcast:%s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(s){return"ts-refclk:%s"+(s.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(s){var t="mediaclk:";return t+=s.id!=null?"id=%s %s":"%v%s",t+=s.mediaClockValue!=null?"=%s":"",t+=s.rateNumerator!=null?" rate=%s":"",t+=s.rateDenominator!=null?"/%s":"",t}},{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(iS).forEach(function(s){var t=iS[s];t.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})}),function(s){var t=function(c){return String(Number(c))===c?Number(c):c},e=function(c,d,l,u){if(u&&!l)d[u]=t(c[1]);else for(var h=0;h<l.length;h+=1)c[h+1]!=null&&(d[l[h]]=t(c[h+1]))},r=function(c,d,l){var u=c.name&&c.names;c.push&&!d[c.push]?d[c.push]=[]:u&&!d[c.name]&&(d[c.name]={});var h=c.push?{}:u?d[c.name]:d;e(l.match(c.reg),h,c.names,c.name),c.push&&d[c.push].push(h)},i=Il,n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);s.parse=function(c){var d={},l=[],u=d;return c.split(/(\r\n|\r|\n)/).filter(n).forEach(function(h){var g=h[0],v=h.slice(2);g==="m"&&(l.push({rtp:[],fmtp:[]}),u=l[l.length-1]);for(var y=0;y<(i[g]||[]).length;y+=1){var k=i[g][y];if(k.reg.test(v))return r(k,u,v)}}),d.media=l,d};var o=function(c,d){var l=d.split(/=(.+)/,2);return l.length===2?c[l[0]]=t(l[1]):l.length===1&&d.length>1&&(c[l[0]]=void 0),c};s.parseParams=function(c){return c.split(/;\s?/).reduce(o,{})},s.parseFmtpConfig=s.parseParams,s.parsePayloads=function(c){return c.toString().split(" ").map(Number)},s.parseRemoteCandidates=function(c){for(var d=[],l=c.split(" ").map(t),u=0;u<l.length;u+=3)d.push({component:l[u],ip:l[u+1],port:l[u+2]});return d},s.parseImageAttributes=function(c){return c.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(o,{})})},s.parseSimulcastStreamList=function(c){return c.split(";").map(function(d){return d.split(",").map(function(l){var u,h=!1;return l[0]!=="~"?u=t(l):(u=t(l.substring(1,l.length)),h=!0),{scid:u,paused:h}})})}}(rS);var kp=Il,Z1=/%[sdv%]/g,eN=function(s){var t=1,e=arguments,r=e.length;return s.replace(Z1,function(i){if(t>=r)return i;var n=e[t];switch(t+=1,i){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}})},Mo=function(s,t,e){var r=t.format instanceof Function?t.format(t.push?e:e[t.name]):t.format,i=[s+"="+r];if(t.names)for(var n=0;n<t.names.length;n+=1){var o=t.names[n];t.name?i.push(e[t.name][o]):i.push(e[t.names[n]])}else i.push(e[t.name]);return eN.apply(null,i)},tN=["v","o","s","i","u","e","p","c","b","t","r","z","a"],sN=["i","c","b","a"],rN=function(s,t){t=t||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(n){n.payloads==null&&(n.payloads="")});var e=t.outerOrder||tN,r=t.innerOrder||sN,i=[];return e.forEach(function(n){kp[n].forEach(function(o){o.name in s&&s[o.name]!=null?i.push(Mo(n,o,s)):o.push in s&&s[o.push]!=null&&s[o.push].forEach(function(c){i.push(Mo(n,o,c))})})}),s.media.forEach(function(n){i.push(Mo("m",kp.m[0],n)),r.forEach(function(o){kp[o].forEach(function(c){c.name in n&&n[c.name]!=null?i.push(Mo(o,c,n)):c.push in n&&n[c.push]!=null&&n[c.push].forEach(function(d){i.push(Mo(o,c,d))})})})}),i.join(`\r
|
|
9
|
+
`)),this.pc2.setLocalDescription(t),this.pc1.setRemoteDescription(t)}establishConnection(){this.pc1.createOffer().then(this.gotOffer.bind(this),this.reportFatal.bind(this))}reportFatal(t){console.error("Error:",t)}async getRoundTripTime(){const[t,e]=await Promise.all([this.pc1.getStats(),this.pc2.getStats()]);let r,i;if(t.forEach(n=>{n.type==="candidate-pair"&&n.nominated===!0&&n.bytesSent>0&&(r=n)}),e.forEach(n=>{n.type==="candidate-pair"&&n.nominated===!0&&n.bytesReceived>0&&(i=n)}),r&&i)try{if(r.currentRoundTripTime&&i.currentRoundTripTime)return{rtt:r.currentRoundTripTime,backendRTT:i.currentRoundTripTime};const n=(i.lastPacketReceivedTimestamp-r.lastPacketSentTimestamp)/1e3;return{rtt:n,backendRTT:n}}catch(n){return}}close(){this.pc1.close(),this.pc2.close()}}class ig extends Tt{constructor(e){super();p(this,"call");p(this,"timeOut");this.call=new tr(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 Ry=8,Iy=1/1e3;class Ay extends ig{constructor(e){super(e);p(this,"senderChannel");p(this,"recieveChannel");p(this,"startTime");p(this,"lastBitrateMeasureTime");p(this,"sentPayloadBytes",0);p(this,"recievedPayloadBytes",0);p(this,"lastReceivedPayloadBytes",0);p(this,"stopSending",!1);p(this,"testProgress",0);p(this,"samplePacket","");p(this,"finalBitrateSum",0);p(this,"bitRateSampels",0);p(this,"maxNumberOfPacketsToSend",0);p(this,"bytesToKeepBuffered",0);p(this,"testDurationSeconds",5);this.call.setIceCandidateFilter(tr.isNotHostCandidate),this.senderChannel=this.call.pc1.createDataChannel(null);for(let r=0;r<262144;r+=1)this.samplePacket+="h";this.maxNumberOfPacketsToSend=1,this.bytesToKeepBuffered=1024*this.maxNumberOfPacketsToSend,this.testDurationSeconds=4,this.senderChannel.addEventListener("open",this.sendingStep.bind(this)),this.call.pc2.addEventListener("datachannel",this.onRecieverChannel.bind(this))}sendingStep(){const e=new Date;this.startTime||(this.startTime=e,this.lastBitrateMeasureTime=e);for(let i=0;i!==this.maxNumberOfPacketsToSend&&!(this.senderChannel.bufferedAmount>=this.bytesToKeepBuffered);i+=1){this.sentPayloadBytes+=this.samplePacket.length;try{this.senderChannel.send(this.samplePacket)}catch(n){}}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,i=r.getTime()-this.lastBitrateMeasureTime.getTime();if(i>=1e3){const o=(this.recievedPayloadBytes-this.lastReceivedPayloadBytes)*Ry/(i/1e3);this.finalBitrateSum+=o,this.bitRateSampels+=1,this.lastReceivedPayloadBytes=this.recievedPayloadBytes,this.lastBitrateMeasureTime=r}if(this.stopSending&&this.sentPayloadBytes===this.recievedPayloadBytes){const n=this.finalBitrateSum/this.bitRateSampels;this.testComplete({throughput:Math.round(n*Iy)})}}testComplete(e){this.call.getRoundTripTime().then(({rtt:r,backendRTT:i})=>super.testComplete({RTT:r,backendRTT:i,throughput:e.throughput}))}onRecieverChannel(e){this.recieveChannel=e.channel,this.recieveChannel.addEventListener("message",this.onMessageRecieved.bind(this))}}class ch extends ig{constructor(e,r=tr.noFilter){super(e);p(this,"ch1");p(this,"ch2");this.call.setIceCandidateFilter(r);const i=this.call.pc1.createDataChannel(null);this.ch1=i,i.addEventListener("open",()=>{i.send("hello")}),i.addEventListener("message",this.onCh1Recieve.bind(this)),this.call.pc2.addEventListener("datachannel",this.dataChannelHandler.bind(this))}onCh1Recieve(e){e.data!=="world"?this.hangup("Invalid data transmitted."):this.testComplete({connectivity:!0})}onCh2Recieve(e){if(e.data!=="hello")this.hangup("Invalid data transmitted.");else try{this.ch2.send("world")}catch(r){}}dataChannelHandler(e){const r=e.channel;this.ch2=r,r.addEventListener("message",this.onCh2Recieve.bind(this))}hangup(e){this.testFailed(e)}}class My extends ch{constructor(t){super(t,tr.isHost)}}class Oy extends ch{constructor(t){super(t,tr.isRelay)}}class Dy extends ch{constructor(t){super(t,tr.isReflexive)}}const ng=[{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"}];class ag{constructor(){p(this,"transport");p(this,"candidatePair");p(this,"outboundVideoRtp",new Map);p(this,"inboundVideoRtp",new Map);p(this,"outboundAudioRtp",new Map);p(this,"inboundAudioRtp",new Map);p(this,"remoteInboundRtp",new Map);p(this,"producerStreamMap",new Map);p(this,"consumerStreamMap",new Map);p(this,"staleProducerStreamMap",!1);p(this,"staleConsumerStreamMap",!1)}}class og extends Tt{constructor(){super();p(this,"observer");p(this,"outboundProducerMap",new Map);p(this,"inboundConsumerMap",new Map);p(this,"consumerPeerIdMap",new Map);p(this,"pausedConsumerMap",new Map);p(this,"pausedProducerMap",new Map);p(this,"overallProducingTransportsStatsMap",{});p(this,"overallConsumingTransportsStatsMap",{});p(this,"overallConsumersStatsMap",{});p(this,"overallProducersStatsMap",{});p(this,"videoProducerToStatsMap",new Map);p(this,"audioProducerToStatsMap",new Map);p(this,"videoConsumerToStatsMap",new Map);p(this,"audioConsumerToStatsMap",new Map);p(this,"consumerIdsWithFreezedVideo",new Set);p(this,"consumerIdsWithFreezedAudio",new Set);p(this,"producerIdsWithFreezedVideo",new Set);p(this,"producerIdsWithFreezedAudio",new Set);p(this,"freezedProducingTransportIds",new Set);p(this,"freezedConsumingTransportIds",new Set);p(this,"screenShareProducers",new Set);p(this,"screenShareConsumers",new Set);p(this,"callStatsInstance");this.observer=new Tt}async registerProducer(e){await this.generateProducerStreamMap(e),e.on("close",this.deregisterProducer.bind(this,e)),e.on("pause",this.pauseProducer.bind(this,e.id)),e.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)}pauseProducer(e){this.pausedProducerMap.set(e,{lastReportCalculated:!1})}resumeProducer(e){this.pausedProducerMap.delete(e)}processInboundConsumerVideoStats(e,r,i){var o,c;const n=((c=(o=this==null?void 0:this.callStatsInstance)==null?void 0:o.consumerSharedMediaStatesMap)==null?void 0:c.get(e))||{};r.totalVideoPacketsReceived===i.packetsReceived?(this.consumerIdsWithFreezedVideo.add(e),this.callStatsInstance&&n.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","pause",e))):(r.totalVideoPacketsReceived=i.packetsReceived,this.consumerIdsWithFreezedVideo.has(e)&&(this.consumerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&n.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","resume",e))))}processInboundConsumerAudioStats(e,r,i){var o,c;const n=((c=(o=this==null?void 0:this.callStatsInstance)==null?void 0:o.consumerSharedMediaStatesMap)==null?void 0:c.get(e))||{};r.totalAudioPacketsReceived===i.packetsReceived?(this.consumerIdsWithFreezedAudio.add(e),this.callStatsInstance&&n.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","pause",e))):(r.totalAudioPacketsReceived=i.packetsReceived,this.consumerIdsWithFreezedAudio.has(e)&&(this.consumerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&n.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","resume",e))))}processOutboundProducerVideoStats(e,r,i){var o;const n=((o=this==null?void 0:this.callStatsInstance)==null?void 0:o.currentUserMediaStates)||{};r.totalVideoPacketsSent===i.packetsSent?(this.producerIdsWithFreezedVideo.add(e),this.callStatsInstance&&n.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","pause",e))):(r.totalVideoPacketsSent=i.packetsSent,this.producerIdsWithFreezedVideo.has(e)&&(this.producerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&n.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","resume",e))))}processOutboundProducerAudioStats(e,r,i){var o;const n=((o=this==null?void 0:this.callStatsInstance)==null?void 0:o.currentUserMediaStates)||{};r.totalAudioPacketsSent===i.packetsSent?(this.producerIdsWithFreezedAudio.add(e),this.callStatsInstance&&n.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","pause",e))):(r.totalAudioPacketsSent=i.packetsSent,this.producerIdsWithFreezedAudio.has(e)&&(this.producerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&n.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","resume",e))))}processProducingTransportStats(e,r,i){var u;const n=((u=this==null?void 0:this.callStatsInstance)==null?void 0:u.currentUserMediaStates)||{},{audio:o,video:c,screen:d}=n,l=o||c||d;r.totalPacketsSent===i.packetsSent?(this.freezedProducingTransportIds.add(e),this.callStatsInstance&&l&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","pause",e))):(r.totalPacketsSent=i.packetsSent,this.freezedProducingTransportIds.has(e)&&(this.freezedProducingTransportIds.delete(e),this.callStatsInstance&&l&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","resume",e))))}processConsumingTransportStats(e,r,i){var c,d;const o=!!Array.from(((d=(c=this==null?void 0:this.callStatsInstance)==null?void 0:c.consumerSharedMediaStatesMap)==null?void 0:d.values())||[]).reduce((l,u)=>l||u.audio||u.video||u.screen,!1);r.totalPacketsReceived===i.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=i.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))))}async registerConsumer(e){await this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.on("close",this.deregisterConsumer.bind(this,e)),e.on("pause",this.pauseConsumer.bind(this,e.id)),e.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)}pauseConsumer(e){this.pausedConsumerMap.set(e,{lastReportCalculated:!1})}resumeConsumer(e){this.pausedConsumerMap.delete(e)}async generateProducerStreamMap(e,r=!1){const i=await e.getStats(),n=r?this.getProducerStatsFromReport(this.parseRTCReport(i,["outbound-rtp","remote-inbound-rtp"],!1,e.id))[0]:void 0;for(const o of i.values())switch(o.type){case"outbound-rtp":{this.outboundProducerMap.set(o.id,e.id);break}}return n}async generateConsumerStreamMap(e,r=!1){const i=await e.getStats(),n=r?this.getConsumerStatsFromReport(this.parseRTCReport(i,["inbound-rtp"],!1,e.id))[0]:void 0;for(const o of i.values())switch(o.type){case"inbound-rtp":{this.inboundConsumerMap.set(o.id,e.id);break}}return n}deregisterProducer(e){this.outboundProducerMap.forEach((r,i)=>{r===e.id&&this.outboundProducerMap.delete(i)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.inboundConsumerMap.forEach((r,i)=>{r===e.id&&this.inboundConsumerMap.delete(i)}),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(i=>{const n=i.framesEncoded>0,o=i.packetsSent>0,c=i.frameWidth&&i.frameHeight;return n&&o&&!!c})||e[e.length-1]}parseRTCReport(e,r=[],i=!1,n=void 0,o=void 0){var k,I,D,N,B,U,j,Z,re,F,ee,we,vt;const c=e,d=new ag,l=r.length?new Set(r):void 0,u=[],h=[],g=[],v=new Map,y=new Map;for(const A of c.values()){if(l){if(l.size===0)break;if(l.has(A.type))i&&l.delete(A.type);else continue}switch(A.type){case"local-candidate":{u.push(this.getIceCandidateStats(A));break}case"remote-candidate":{h.push(this.getIceCandidateStats(A));break}case"candidate-pair":{const{nominated:S}=A,{selected:w}=A,$=A,ce={nominated:S!=null?S:w,currentRoundTripTime:$.currentRoundTripTime,totalRoundTripTime:$.totalRoundTripTime,bytesReceived:$.bytesReceived,bytesSent:$.bytesSent,availableOutgoingBitrate:$.availableOutgoingBitrate,availableIncomingBitrate:$.availableIncomingBitrate,lastPacketReceivedTimestamp:$.lastPacketReceivedTimestamp,lastPacketSentTimestamp:$.lastPacketSentTimestamp,localCandidateId:$.localCandidateId,remoteCandidateId:$.remoteCandidateId,bytesDiscardedOnSend:$.bytesDiscardedOnSend,packetsSent:$.packetsSent,packetsReceived:$.packetsReceived,packetsDiscardedOnSend:$.packetsDiscardedOnSend};g.push(ce),(A.nominated===!0||A.selected===!0)&&(d.candidatePair=ce);break}case"transport":{const S=A;o&&(o.producing&&(this.overallProducingTransportsStatsMap[o.id]||(this.overallProducingTransportsStatsMap[o.id]={totalPacketsSent:0})),o.consuming&&(this.overallConsumingTransportsStatsMap[o.id]||(this.overallConsumingTransportsStatsMap[o.id]={totalPacketsReceived:0})));const w={bytesReceived:S.bytesReceived,bytesSent:S.bytesSent,packetsSent:S.packetsSent,packetsReceived:S.packetsReceived,dtlsCipher:S.dtlsCipher,dtlsState:S.dtlsState,iceRole:S.iceRole};if(d.transport=w,o){if(o.producing){const $=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,$,w)}if(o.consuming){const $=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,$,w)}}break}case"remote-inbound-rtp":{const S=A,w={jitter:S.jitter,fractionLost:S.fractionLost,roundTripTime:S.roundTripTime,roundTripTimeMeasurements:S.roundTripTimeMeasurements,totalRoundTripTime:S.totalRoundTripTime,packetsLost:S.packetsLost};d.remoteInboundRtp.set(S.localId,w);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(A.id))break;const S=A,w=n||this.outboundProducerMap.get(A.id),$=this.pausedProducerMap.get(w);if($){if($.lastReportCalculated===!0)break;this.pausedProducerMap.set(w,{lastReportCalculated:!0})}this.overallProducersStatsMap[w]||(this.overallProducersStatsMap[w]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const ce=this.overallProducersStatsMap[w];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.outboundProducerMap.has(A.id)){d.staleProducerStreamMap=!0;break}const fe=this.callStatsInstance.producers.get(w);if(((k=fe==null?void 0:fe.track)==null?void 0:k.readyState)==="ended")break;d.producerStreamMap.has(w)||d.producerStreamMap.set(w,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const V={bytesSent:S.bytesSent,packetsSent:S.packetsSent,nackCount:S.nackCount,ssrc:S.ssrc,mid:S.mid,active:S.active,codecId:S.codecId,headerBytesSent:S.headerBytesSent||0,totalPacketSendDelay:S.totalPacketSendDelay||0};if(S.mediaType==="video"||S.kind==="video"){const _=S,He={frameHeight:_.frameHeight,frameWidth:_.frameWidth,framesEncoded:_.framesEncoded,framesDropped:_.framesDropped,framesPerSecond:_.framesPerSecond,framesSent:_.framesSent,keyFramesEncoded:_.keyFramesEncoded,firCount:_.firCount,encoderImplementation:_.encoderImplementation,hugeFramesSent:_.hugeFramesSent,pliCount:_.pliCount,qpSum:_.qpSum,qualityLimitationDurations:_.qualityLimitationDurations,qualityLimitationReason:_.qualityLimitationReason,qualityLimitationResolutionChanges:_.qualityLimitationResolutionChanges,totalEncodeTime:_.targetBitrate,totalPacketSendDelay:_.totalPacketSendDelay,retransmittedBytesSent:_.retransmittedBytesSent,retransmittedPacketsSent:_.retransmittedPacketsSent,scalabilityMode:_.scalabilityMode,powerEfficientEncoder:_.powerEfficientEncoder,...V};d.outboundVideoRtp.set(A.id,He),d.producerStreamMap.get(w).outboundVideoRtpId.push(A.id),this.processOutboundProducerVideoStats(w,ce,He)}else if(S.mediaType==="audio"||S.kind==="audio"){const _=S,He={retransmittedBytesSent:_.retransmittedBytesSent,retransmittedPacketsSent:_.retransmittedPacketsSent,...V};d.outboundAudioRtp.set(A.id,He),d.producerStreamMap.get(w).outboundAudioRtpId.push(A.id),this.processOutboundProducerAudioStats(w,ce,He)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(A.id))break;const S=A,w=n||this.inboundConsumerMap.get(A.id),$=this.pausedConsumerMap.get(w);if($){if($.lastReportCalculated===!0)break;this.pausedConsumerMap.set(w,{lastReportCalculated:!0})}if(S.ssrc===1234)break;this.overallConsumersStatsMap[w]||(this.overallConsumersStatsMap[w]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const ce=this.overallConsumersStatsMap[w];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.inboundConsumerMap.has(A.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(w)||d.consumerStreamMap.set(w,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const fe={bytesReceived:S.bytesReceived,packetsReceived:S.packetsReceived,packetsLost:S.packetsLost>=0?S.packetsLost:0,jitter:S.jitter,nackCount:S.nackCount,jitterBufferDelay:S.jitterBufferDelay,jitterBufferEmittedCount:S.jitterBufferEmittedCount,lastPacketReceivedTimestamp:S.lastPacketReceivedTimestamp,ssrc:S.ssrc,mid:S.mid,codecId:S.codecId,headerBytesReceived:S.headerBytesReceived||0,packetsDiscarded:S.packetsDiscarded||0,jitterBufferMinimumDelay:S.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:S.jitterBufferTargetDelay||0};if(S.mediaType==="video"||S.kind==="video"){const V=S,_={frameHeight:V.frameHeight,frameWidth:V.frameWidth,framesDecoded:V.framesDecoded,framesDropped:V.framesDropped,framesPerSecond:V.framesPerSecond,framesReceived:V.framesReceived,keyFramesDecoded:V.keyFramesDecoded,firCount:V.firCount,decoderImplementation:V.decoderImplementation,pliCount:V.pliCount,totalProcessingDelay:V.totalProcessingDelay,qpSum:V.qpSum||0,totalAssemblyTime:V.totalAssemblyTime||0,totalDecodeTime:V.totalDecodeTime||0,totalFreezesDuration:V.totalFreezesDuration||0,totalInterFrameDelay:V.totalInterFrameDelay||0,totalPausesDuration:V.totalPausesDuration||0,totalSquaredInterFrameDelay:V.totalSquaredInterFrameDelay||0,freezeCount:V.freezeCount||0,pauseCount:V.pauseCount||0,powerEfficientDecoder:V.powerEfficientDecoder,...fe};_.score=rg({frameWidth:_.frameWidth||0,framesDecoded:(_.framesDecoded||0)-(((I=this.videoConsumerToStatsMap.get(w))==null?void 0:I.framesDecoded)||0),framesPerSecond:_.framesPerSecond||0,packetsLost:(_.packetsLost||0)-(((D=this.videoConsumerToStatsMap.get(w))==null?void 0:D.packetsLost)||0),packetsReceived:(_.packetsReceived||0)-(((N=this.videoConsumerToStatsMap.get(w))==null?void 0:N.packetsReceived)||0),jitter:_.jitter||0,isScreenShare:this.screenShareConsumers.has(w)}),y.set(w,{score:+(_.score*10).toFixed(),frameWidth:_.frameWidth||0,frameHeight:_.frameHeight||0,framesPerSecond:_.framesPerSecond||0,packetsLostPercentage:Nd({packetsLost:(_.packetsLost||0)-(((B=this.videoConsumerToStatsMap.get(w))==null?void 0:B.packetsLost)||0),packetsReceived:(_.packetsReceived||0)-(((U=this.videoConsumerToStatsMap.get(w))==null?void 0:U.packetsReceived)||0)}),jitter:_.jitter||0,isScreenShare:this.screenShareConsumers.has(w),bitrate:((_.bytesReceived||0)-(((j=this.videoConsumerToStatsMap.get(w))==null?void 0:j.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(w,_),d.inboundVideoRtp.set(A.id,_),d.consumerStreamMap.get(w).inboundVideoRtpId.push(A.id),this.processInboundConsumerVideoStats(w,ce,_)}else if(S.mediaType==="audio"||S.kind==="audio"){const V=S,_={audioLevel:V.audioLevel,concealedSamples:V.concealedSamples,concealmentEvents:V.concealmentEvents,totalAudioEnergy:V.totalAudioEnergy,totalSamplesDuration:V.totalSamplesDuration,totalSamplesReceived:V.totalSamplesReceived,fecPacketsDiscarded:V.fecPacketsDiscarded||0,fecPacketsReceived:V.fecPacketsReceived||0,insertedSamplesForDeceleration:V.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:V.removedSamplesForAcceleration||0,silentConcealedSamples:V.silentConcealedSamples||0,playoutId:V.playoutId,...fe};_.score=sg({concealmentEvents:(_.concealmentEvents||0)-(((Z=this.audioConsumerToStatsMap.get(w))==null?void 0:Z.concealmentEvents)||0),packetsLost:(_.packetsLost||0)-(((re=this.audioConsumerToStatsMap.get(w))==null?void 0:re.packetsLost)||0),packetsReceived:(_.packetsReceived||0)-(((F=this.audioConsumerToStatsMap.get(w))==null?void 0:F.packetsReceived)||0),jitter:_.jitter||0}),y.set(w,{score:+(_.score*10).toFixed(),packetsLostPercentage:Nd({packetsLost:(_.packetsLost||0)-(((ee=this.audioConsumerToStatsMap.get(w))==null?void 0:ee.packetsLost)||0),packetsReceived:(_.packetsReceived||0)-(((we=this.audioConsumerToStatsMap.get(w))==null?void 0:we.packetsReceived)||0)}),jitter:_.jitter||0,isScreenShare:this.screenShareConsumers.has(w),bitrate:((_.bytesReceived||0)-(((vt=this.audioConsumerToStatsMap.get(w))==null?void 0:vt.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(w,_),d.inboundAudioRtp.set(A.id,_),d.consumerStreamMap.get(w).inboundAudioRtpId.push(A.id),this.processInboundConsumerAudioStats(w,ce,_)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}}}if(d.producerStreamMap.forEach((A,S)=>{var w,$,ce,fe,V,_,He,ad,od,cd,dd,ld,ud,hd,pd,md,gd,fd,vd,Sd,Td,yd,Ed;if(A.outboundVideoRtpId.length>0){const Te=[];A.outboundVideoRtpId.forEach(Wp=>{Te.push(d.outboundVideoRtp.get(Wp))});const se=this.getWorkingSimulcastVideoStats(Te);se.score=eg({frameWidth:se.frameWidth||0,framesPerSecond:se.framesPerSecond||0,jitter:((w=se.remoteData)==null?void 0:w.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsSent:(se.packetsSent||0)-((($=this.videoProducerToStatsMap.get(S))==null?void 0:$.packetsSent)||0),packetsLost:(((ce=se.remoteData)==null?void 0:ce.packetsLost)||0)-(((V=(fe=this.videoProducerToStatsMap.get(S))==null?void 0:fe.remoteData)==null?void 0:V.packetsLost)||0),framesEncoded:(se.framesEncoded||0)-(((_=this.videoProducerToStatsMap.get(S))==null?void 0:_.framesEncoded)||0)}),v.set(S,{score:+(se.score*10).toFixed(),frameWidth:se.frameWidth||0,frameHeight:se.frameHeight||0,framesPerSecond:se.framesPerSecond||0,jitter:((He=se.remoteData)==null?void 0:He.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsLostPercentage:Dd({packetsSent:(se.packetsSent||0)-(((ad=this.videoProducerToStatsMap.get(S))==null?void 0:ad.packetsSent)||0),packetsLost:(((od=se.remoteData)==null?void 0:od.packetsLost)||0)-(((dd=(cd=this.videoProducerToStatsMap.get(S))==null?void 0:cd.remoteData)==null?void 0:dd.packetsLost)||0)}),bitrate:((se.bytesSent||0)-(((ld=this.videoProducerToStatsMap.get(S))==null?void 0:ld.bytesSent)||0))*8/7,cpuLimitations:se.qualityLimitationReason==="cpu",bandwidthLimitations:se.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(S,se)}else if(A.outboundAudioRtpId.length>0){const Te=d.outboundAudioRtp.get(A.outboundAudioRtpId[0]);Te.score=Zm({packetsSent:(Te.packetsSent||0)-(((ud=this.audioProducerToStatsMap.get(S))==null?void 0:ud.packetsSent)||0),packetsLost:(((hd=Te.remoteData)==null?void 0:hd.packetsLost)||0)-(((md=(pd=this.audioProducerToStatsMap.get(S))==null?void 0:pd.remoteData)==null?void 0:md.packetsLost)||0),jitter:((gd=Te.remoteData)==null?void 0:gd.jitter)||0}),v.set(S,{score:+(Te.score*10).toFixed(),bitrate:((Te.bytesSent||0)-(((fd=this.audioProducerToStatsMap.get(S))==null?void 0:fd.bytesSent)||0))*8/7,packetsLostPercentage:Dd({packetsSent:(Te.packetsSent||0)-(((vd=this.audioProducerToStatsMap.get(S))==null?void 0:vd.packetsSent)||0),packetsLost:(((Sd=Te.remoteData)==null?void 0:Sd.packetsLost)||0)-(((yd=(Td=this.audioProducerToStatsMap.get(S))==null?void 0:Td.remoteData)==null?void 0:yd.packetsLost)||0)}),jitter:((Ed=Te.remoteData)==null?void 0:Ed.jitter)||0,isScreenShare:this.screenShareProducers.has(S)}),this.audioProducerToStatsMap.set(S,Te)}}),g.forEach(A=>{const S=u.find($=>$.id===A.localCandidateId?(A.localCandidateId=$.id,$):null),w=h.find($=>$.id===A.remoteCandidateId?(A.remoteCandidateId=$.id,$):null);S&&(A.localCandidateType=S.type,A.localCandidateAddress=Un(S.address),A.localCandidatePort=S.port,A.localCandidateProtocol=S.protocol,A.localCandidateUrl=S.url,A.localCandidateNetworkType=S.networkType,A.localCandidateRelatedAddress=Un(S.relatedAddress),A.localCandidateRelatedPort=S.relatedPort),w&&(A.remoteCandidateType=w.type,A.remoteCandidateAddress=Un(w.address),A.remoteCandidatePort=w.port,A.remoteCandidateProtocol=w.protocol,A.remoteCandidateUrl=w.url)}),d.candidatePair&&(d.transport?(d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.availableIncomingBitrate=d.candidatePair.availableIncomingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:d.candidatePair.availableIncomingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=g),d.transport&&!d.transport.roundTripTime){let A=0,S=0;d.remoteInboundRtp.forEach((w,$)=>{w.roundTripTime&&w.roundTripTime>A&&(A=w.roundTripTime,S=w.totalRoundTripTime)}),d.transport.roundTripTime=A,d.transport.totalRoundTripTime=S}if(y.size>0)try{this.observer.emit("consumer_score",y)}catch(A){}if(v.size>0)try{this.observer.emit("producer_score",v)}catch(A){}return d}async getProducersReport(e){const r=e.map(i=>this.generateProducerStreamMap(i,!0));return r.length>0?Promise.all(r):void 0}async getConsumersReport(e){const r=e.map(i=>this.generateConsumerStreamMap(i,!0));return r.length>0?Promise.all(r):void 0}async getTransportReport(e){return e.getStats()}async getProcessedStats(e,r,i){const n=await this.getTransportReport(e),o={producing:i,consuming:r,id:e.id},c=n,d=this.parseRTCReport(c,["transport","candidate-pair","inbound-rtp","outbound-rtp","remote-inbound-rtp","local-candidate","remote-candidate"],!1,void 0,o);if(!d)return;const l={stats:d.transport,transportId:e.id,consuming:r,producing:i},u=d.staleProducerStreamMap?void 0:this.getProducerStatsFromReport(d),h=d.staleConsumerStreamMap?void 0:this.getConsumerStatsFromReport(d);return{transportReport:l,producerReport:u,consumerReport:h}}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((i,n)=>{var o,c;r.push({producerId:n,videoStats:i.outboundVideoRtpId.map(d=>e.outboundVideoRtp.get(d)),audioStats:i.outboundAudioRtpId.map(d=>e.outboundAudioRtp.get(d)),appData:((c=(o=this.callStatsInstance.producers)==null?void 0:o.get(n))==null?void 0:c.appData)||null})})}catch(i){this.callStatsInstance.logger.error("callStats::measurements::getProducerStatsFromReport",{error:{reason:i.reason,message:i.message}})}return r}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((i,n)=>{const{peerId:o,producerId:c,appData:d}=this.consumerPeerIdMap.get(n);r.push({consumerId:n,peerId:o,producerId:c,appData:d,videoStats:i.inboundVideoRtpId.map(l=>e.inboundVideoRtp.get(l)),audioStats:i.inboundAudioRtpId.map(l=>e.inboundAudioRtp.get(l))})})}catch(i){console.error("getConsumersReport: ",i,e)}return r}async getUserLocation(){return new Promise((e,r)=>{try{navigator.geolocation?navigator.geolocation.getCurrentPosition(i=>{e(i)}):r()}catch(i){r(i)}})}async getConnectivity(e){try{const r={iceServers:e||ng},i=new Promise((u,h)=>{try{const g=new My(r);g.addListener("done",u),g.addListener("failed",()=>{u({connectivity:!1})}),g.start(2e3)}catch(g){h(g)}}),n=new Promise((u,h)=>{try{const g=new Oy(r);g.addListener("done",u),g.addListener("failed",()=>{u({connectivity:!1})}),g.start(2e3)}catch(g){h(g)}}),o=new Promise((u,h)=>{try{const g=new Dy(r);g.addListener("done",u),g.addListener("failed",()=>{u({connectivity:!1})}),g.start(2e3)}catch(g){h(g)}}),[c,d,l]=await Promise.all([i,n,o]);return{host:c==null?void 0:c.connectivity,relay:d==null?void 0:d.connectivity,reflexive:l==null?void 0:l.connectivity}}catch(r){return{host:!1,relay:!1,reflexive:!1}}}async getThroughput(e){try{const i=await new Promise((n,o)=>{try{const c={iceServers:e||ng},d=new Ay(c);d.addListener("done",n),d.addListener("failed",o),d.start(1e4)}catch(c){o(c)}});return{throughput:i.throughput,fractionalLoss:0,RTT:i.RTT,jitter:0,backendRTT:i.backendRTT}}catch(r){return}}async getNetworkQuality(e){const[r,i]=await Promise.all([this.getConnectivity(e),this.getThroughput(e)]);return{connectivity:r,throughput:i==null?void 0:i.throughput,fractionalLoss:i==null?void 0:i.fractionalLoss,RTT:i==null?void 0:i.RTT,jitter:i==null?void 0:i.jitter,backendRTT:i==null?void 0:i.backendRTT}}async getNetworkInfo(e,r=!1){var o,c;if(r)return{effectiveNetworkType:(o=navigator.connection)==null?void 0:o.effectiveType};const[i,n]=await Promise.all([this.getConnectivity(e),this.getThroughput(e)]);return{effectiveNetworkType:(c=navigator.connection)==null?void 0:c.effectiveType,turnConnectivity:i?i.host||i.relay||i.reflexive:!1,connectivity:i,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}}}class Ny extends og{}class cg extends og{constructor(){super(...arguments);p(this,"producerMap",new Map);p(this,"consumerMap",new Map)}async registerProducer(e){this.producerMap.set(e.id,e),await this.generateProducerStreamMap(e),e.on("close",this.deregisterProducer.bind(this,e)),e.on("pause",this.pauseProducer.bind(this,e.id)),e.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)}async registerConsumer(e){this.consumerMap.set(e.id,e),await this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.on("close",this.deregisterConsumer.bind(this,e)),e.on("pause",this.pauseConsumer.bind(this,e.id)),e.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)}async generateConsumerStreamMap(e,r=!1){const i=await e.getStats(),n=this.parseRTCReport(i,["inbound-rtp"],!1,e.id),o=[...n.consumerStreamMap.values()][0],c=r?this.getConsumerStatsFromParsedConsumerStats(n,o,e.id):void 0;for(const d of i.values())switch(d.type){case"inbound-rtp":{this.inboundConsumerMap.set(d.id,e.id);break}}return c}deregisterProducer(e){this.producerMap.delete(e.id),this.outboundProducerMap.forEach((r,i)=>{r===e.id&&this.outboundProducerMap.delete(i)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.consumerMap.delete(e.id),this.inboundConsumerMap.forEach((r,i)=>{r===e.id&&this.inboundConsumerMap.delete(i)}),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=[],i=!1,n=void 0,o=void 0){var k,I,D,N,B,U,j,Z,re,F,ee,we,vt;const c=e,d=new ag,l=r.length?new Set(r):void 0,u=[],h=[],g=[],v=new Map,y=new Map;for(const A of c.values()){if(l){if(l.size===0)break;if(l.has(A.type))i&&l.delete(A.type);else continue}switch(A.type){case"local-candidate":{u.push(this.getIceCandidateStats(A));break}case"remote-candidate":{h.push(this.getIceCandidateStats(A));break}case"candidate-pair":{const{nominated:S}=A,{selected:w}=A,$=A,ce={nominated:S!=null?S:w,currentRoundTripTime:$.currentRoundTripTime,totalRoundTripTime:$.totalRoundTripTime,bytesReceived:$.bytesReceived,bytesSent:$.bytesSent,availableOutgoingBitrate:$.availableOutgoingBitrate,availableIncomingBitrate:$.availableIncomingBitrate,lastPacketReceivedTimestamp:$.lastPacketReceivedTimestamp,lastPacketSentTimestamp:$.lastPacketSentTimestamp,localCandidateId:$.localCandidateId,remoteCandidateId:$.remoteCandidateId,bytesDiscardedOnSend:$.bytesDiscardedOnSend,packetsSent:$.packetsSent,packetsReceived:$.packetsReceived,packetsDiscardedOnSend:$.packetsDiscardedOnSend};g.push(ce),(A.nominated===!0||A.selected===!0)&&(d.candidatePair=ce);break}case"transport":{const S=A;o&&(o.producing&&(this.overallProducingTransportsStatsMap[o.id]||(this.overallProducingTransportsStatsMap[o.id]={totalPacketsSent:0})),o.consuming&&(this.overallConsumingTransportsStatsMap[o.id]||(this.overallConsumingTransportsStatsMap[o.id]={totalPacketsReceived:0})));const w={bytesReceived:S.bytesReceived,bytesSent:S.bytesSent,packetsSent:S.packetsSent,packetsReceived:S.packetsReceived,dtlsCipher:S.dtlsCipher,dtlsState:S.dtlsState,iceRole:S.iceRole};if(d.transport=w,o){if(o.producing){const $=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,$,w)}if(o.consuming){const $=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,$,w)}}break}case"remote-inbound-rtp":{const S=A,w={jitter:S.jitter,fractionLost:S.fractionLost,roundTripTime:S.roundTripTime,roundTripTimeMeasurements:S.roundTripTimeMeasurements,totalRoundTripTime:S.totalRoundTripTime,packetsLost:S.packetsLost};d.remoteInboundRtp.set(S.localId,w);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(A.id))break;const S=A,w=n||this.outboundProducerMap.get(A.id),$=this.pausedProducerMap.get(w);if($){if($.lastReportCalculated===!0)break;this.pausedProducerMap.set(w,{lastReportCalculated:!0})}this.overallProducersStatsMap[w]||(this.overallProducersStatsMap[w]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const ce=this.overallProducersStatsMap[w];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.outboundProducerMap.has(A.id)){d.staleProducerStreamMap=!0;break}const fe=this.callStatsInstance.producers.get(w);if(((k=fe==null?void 0:fe.track)==null?void 0:k.readyState)==="ended")break;d.producerStreamMap.has(w)||d.producerStreamMap.set(w,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const V={bytesSent:S.bytesSent,packetsSent:S.packetsSent,nackCount:S.nackCount,ssrc:S.ssrc,mid:S.mid,active:S.active,codecId:S.codecId,headerBytesSent:S.headerBytesSent||0,totalPacketSendDelay:S.totalPacketSendDelay||0};if(S.mediaType==="video"||S.kind==="video"){const _=S,He={frameHeight:_.frameHeight,frameWidth:_.frameWidth,framesEncoded:_.framesEncoded,framesDropped:_.framesDropped?_.framesDropped:_.droppedFrames,framesPerSecond:_.framesPerSecond?_.framesPerSecond:_.framerateMean,framesSent:_.framesSent,keyFramesEncoded:_.keyFramesEncoded,firCount:_.firCount,encoderImplementation:_.encoderImplementation,hugeFramesSent:_.hugeFramesSent,pliCount:_.pliCount,qpSum:_.qpSum,qualityLimitationReason:_.qualityLimitationReason,qualityLimitationDurations:_.qualityLimitationDurations,qualityLimitationResolutionChanges:_.qualityLimitationResolutionChanges,totalEncodeTime:_.totalEncodeTime,totalPacketSendDelay:_.totalEncodeTime,retransmittedBytesSent:_.retransmittedBytesSent,retransmittedPacketsSent:_.retransmittedPacketsSent,scalabilityMode:_.scalabilityMode,powerEfficientEncoder:_.powerEfficientEncoder,...V};d.outboundVideoRtp.set(A.id,He),d.producerStreamMap.get(w).outboundVideoRtpId.push(A.id),this.processOutboundProducerVideoStats(w,ce,He)}else if(S.mediaType==="audio"||S.kind==="audio"){const _=S,He={retransmittedBytesSent:_.retransmittedBytesSent,retransmittedPacketsSent:_.retransmittedPacketsSent,...V};d.outboundAudioRtp.set(A.id,He),d.producerStreamMap.get(w).outboundAudioRtpId.push(A.id),this.processOutboundProducerAudioStats(w,ce,He)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(A.id))break;const S=A,w=n||this.inboundConsumerMap.get(A.id),$=this.pausedConsumerMap.get(w);if($){if($.lastReportCalculated===!0)break;this.pausedConsumerMap.set(w,{lastReportCalculated:!0})}if(S.ssrc===1234)break;this.overallConsumersStatsMap[w]||(this.overallConsumersStatsMap[w]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const ce=this.overallConsumersStatsMap[w];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.inboundConsumerMap.has(A.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(w)||d.consumerStreamMap.set(w,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const fe={bytesReceived:S.bytesReceived,packetsReceived:S.packetsReceived,packetsLost:S.packetsLost>=0?S.packetsLost:0,jitter:S.jitter,nackCount:S.nackCount,jitterBufferDelay:S.jitterBufferDelay,jitterBufferEmittedCount:S.jitterBufferEmittedCount,lastPacketReceivedTimestamp:S.lastPacketReceivedTimestamp,ssrc:S.ssrc,mid:S.mid,codecId:S.codecId,headerBytesReceived:S.headerBytesReceived||0,packetsDiscarded:S.packetsDiscarded||0,jitterBufferMinimumDelay:S.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:S.jitterBufferTargetDelay||0};if(S.mediaType==="video"||S.kind==="video"){const V=S,_={frameHeight:V.frameHeight,frameWidth:V.frameWidth,framesDecoded:V.framesDecoded,framesDropped:V.framesDropped?V.framesDropped:V.droppedFrames,framesPerSecond:V.framesPerSecond?V.framesPerSecond:V.framerateMean,framesReceived:V.framesReceived,keyFramesDecoded:V.keyFramesDecoded,firCount:V.firCount,decoderImplementation:V.decoderImplementation,pliCount:V.pliCount,totalProcessingDelay:V.totalProcessingDelay,qpSum:V.qpSum||0,totalAssemblyTime:V.totalAssemblyTime||0,totalDecodeTime:V.totalDecodeTime||0,totalFreezesDuration:V.totalFreezesDuration||0,totalInterFrameDelay:V.totalInterFrameDelay||0,totalPausesDuration:V.totalPausesDuration||0,totalSquaredInterFrameDelay:V.totalSquaredInterFrameDelay||0,freezeCount:V.freezeCount||0,pauseCount:V.pauseCount||0,powerEfficientDecoder:V.powerEfficientDecoder,...fe};_.score=rg({frameWidth:_.frameWidth||0,framesDecoded:(_.framesDecoded||0)-(((I=this.videoConsumerToStatsMap.get(w))==null?void 0:I.framesDecoded)||0),framesPerSecond:_.framesPerSecond||0,packetsLost:(_.packetsLost||0)-(((D=this.videoConsumerToStatsMap.get(w))==null?void 0:D.packetsLost)||0),packetsReceived:(_.packetsReceived||0)-(((N=this.videoConsumerToStatsMap.get(w))==null?void 0:N.packetsReceived)||0),jitter:_.jitter||0,isScreenShare:this.screenShareConsumers.has(w)}),y.set(w,{score:+(_.score*10).toFixed(),frameWidth:_.frameWidth||0,frameHeight:_.frameHeight||0,framesPerSecond:_.framesPerSecond||0,packetsLostPercentage:Nd({packetsLost:(_.packetsLost||0)-(((B=this.videoConsumerToStatsMap.get(w))==null?void 0:B.packetsLost)||0),packetsReceived:(_.packetsReceived||0)-(((U=this.videoConsumerToStatsMap.get(w))==null?void 0:U.packetsReceived)||0)}),jitter:_.jitter||0,isScreenShare:this.screenShareConsumers.has(w),bitrate:((_.bytesReceived||0)-(((j=this.videoConsumerToStatsMap.get(w))==null?void 0:j.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(w,_),d.inboundVideoRtp.set(A.id,_),d.consumerStreamMap.get(w).inboundVideoRtpId.push(A.id),this.processInboundConsumerVideoStats(w,ce,_)}else if(S.mediaType==="audio"||S.kind==="audio"){const V=S,_={audioLevel:V.audioLevel,concealedSamples:V.concealedSamples,concealmentEvents:V.concealmentEvents,totalAudioEnergy:V.totalAudioEnergy,totalSamplesDuration:V.totalSamplesDuration,totalSamplesReceived:V.totalSamplesReceived,fecPacketsDiscarded:V.fecPacketsDiscarded||0,fecPacketsReceived:V.fecPacketsReceived||0,insertedSamplesForDeceleration:V.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:V.removedSamplesForAcceleration||0,silentConcealedSamples:V.silentConcealedSamples||0,playoutId:V.playoutId,...fe};_.score=sg({concealmentEvents:(_.concealmentEvents||0)-(((Z=this.audioConsumerToStatsMap.get(w))==null?void 0:Z.concealmentEvents)||0),packetsLost:(_.packetsLost||0)-(((re=this.audioConsumerToStatsMap.get(w))==null?void 0:re.packetsLost)||0),packetsReceived:(_.packetsReceived||0)-(((F=this.audioConsumerToStatsMap.get(w))==null?void 0:F.packetsReceived)||0),jitter:_.jitter||0}),y.set(w,{score:+(_.score*10).toFixed(),packetsLostPercentage:Nd({packetsLost:(_.packetsLost||0)-(((ee=this.audioConsumerToStatsMap.get(w))==null?void 0:ee.packetsLost)||0),packetsReceived:(_.packetsReceived||0)-(((we=this.audioConsumerToStatsMap.get(w))==null?void 0:we.packetsReceived)||0)}),jitter:_.jitter||0,isScreenShare:this.screenShareConsumers.has(w),bitrate:((_.bytesReceived||0)-(((vt=this.audioConsumerToStatsMap.get(w))==null?void 0:vt.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(w,_),d.inboundAudioRtp.set(A.id,_),d.consumerStreamMap.get(w).inboundAudioRtpId.push(A.id),this.processInboundConsumerAudioStats(w,ce,_)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}}}if(d.producerStreamMap.forEach((A,S)=>{var w,$,ce,fe,V,_,He,ad,od,cd,dd,ld,ud,hd,pd,md,gd,fd,vd,Sd,Td,yd,Ed;if(A.outboundVideoRtpId.length>0){const Te=[];A.outboundVideoRtpId.forEach(Wp=>{Te.push(d.outboundVideoRtp.get(Wp))});const se=this.getWorkingSimulcastVideoStats(Te);se.score=eg({frameWidth:se.frameWidth||0,framesPerSecond:se.framesPerSecond||0,jitter:((w=se.remoteData)==null?void 0:w.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsSent:(se.packetsSent||0)-((($=this.videoProducerToStatsMap.get(S))==null?void 0:$.packetsSent)||0),packetsLost:(((ce=se.remoteData)==null?void 0:ce.packetsLost)||0)-(((V=(fe=this.videoProducerToStatsMap.get(S))==null?void 0:fe.remoteData)==null?void 0:V.packetsLost)||0),framesEncoded:(se.framesEncoded||0)-(((_=this.videoProducerToStatsMap.get(S))==null?void 0:_.framesEncoded)||0)}),v.set(S,{score:+(se.score*10).toFixed(),frameWidth:se.frameWidth||0,frameHeight:se.frameHeight||0,framesPerSecond:se.framesPerSecond||0,jitter:((He=se.remoteData)==null?void 0:He.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsLostPercentage:Dd({packetsSent:(se.packetsSent||0)-(((ad=this.videoProducerToStatsMap.get(S))==null?void 0:ad.packetsSent)||0),packetsLost:(((od=se.remoteData)==null?void 0:od.packetsLost)||0)-(((dd=(cd=this.videoProducerToStatsMap.get(S))==null?void 0:cd.remoteData)==null?void 0:dd.packetsLost)||0)}),bitrate:((se.bytesSent||0)-(((ld=this.videoProducerToStatsMap.get(S))==null?void 0:ld.bytesSent)||0))*8/7,cpuLimitations:se.qualityLimitationReason==="cpu",bandwidthLimitations:se.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(S,se)}else if(A.outboundAudioRtpId.length>0){const Te=d.outboundAudioRtp.get(A.outboundAudioRtpId[0]);Te.score=Zm({packetsSent:(Te.packetsSent||0)-(((ud=this.audioProducerToStatsMap.get(S))==null?void 0:ud.packetsSent)||0),packetsLost:(((hd=Te.remoteData)==null?void 0:hd.packetsLost)||0)-(((md=(pd=this.audioProducerToStatsMap.get(S))==null?void 0:pd.remoteData)==null?void 0:md.packetsLost)||0),jitter:((gd=Te.remoteData)==null?void 0:gd.jitter)||0}),v.set(S,{score:+(Te.score*10).toFixed(),bitrate:((Te.bytesSent||0)-(((fd=this.audioProducerToStatsMap.get(S))==null?void 0:fd.bytesSent)||0))*8/7,packetsLostPercentage:Dd({packetsSent:(Te.packetsSent||0)-(((vd=this.audioProducerToStatsMap.get(S))==null?void 0:vd.packetsSent)||0),packetsLost:(((Sd=Te.remoteData)==null?void 0:Sd.packetsLost)||0)-(((yd=(Td=this.audioProducerToStatsMap.get(S))==null?void 0:Td.remoteData)==null?void 0:yd.packetsLost)||0)}),jitter:((Ed=Te.remoteData)==null?void 0:Ed.jitter)||0,isScreenShare:this.screenShareProducers.has(S)}),this.audioProducerToStatsMap.set(S,Te)}}),g.forEach(A=>{const S=u.find($=>$.id===A.localCandidateId?(A.localCandidateId=$.id,$):null),w=h.find($=>$.id===A.remoteCandidateId?(A.remoteCandidateId=$.id,$):null);S&&(A.localCandidateType=S.type,A.localCandidateAddress=Un(S.address),A.localCandidatePort=S.port,A.localCandidateProtocol=S.protocol,A.localCandidateUrl=S.url,A.localCandidateNetworkType=S.networkType,A.localCandidateRelatedAddress=Un(S.relatedAddress),A.localCandidateRelatedPort=S.relatedPort),w&&(A.remoteCandidateType=w.type,A.remoteCandidateAddress=Un(w.address),A.remoteCandidatePort=w.port,A.remoteCandidateProtocol=w.protocol,A.remoteCandidateUrl=w.url)}),d.candidatePair&&(d.transport?(d.transport.bytesReceived=d.candidatePair.bytesReceived,d.transport.bytesSent=d.candidatePair.bytesSent,d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.availableIncomingBitrate=d.candidatePair.availableIncomingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:d.candidatePair.availableIncomingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=g),d.transport&&!d.transport.roundTripTime){let A=0,S=0;d.remoteInboundRtp.forEach((w,$)=>{w.roundTripTime&&w.roundTripTime>A&&(A=w.roundTripTime,S=w.totalRoundTripTime)}),d.transport.roundTripTime=A,d.transport.totalRoundTripTime=S}if(y.size>0)try{this.observer.emit("consumer_score",y)}catch(A){}if(v.size>0)try{this.observer.emit("producer_score",v)}catch(A){}return d}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((i,n)=>{const o=this.producerMap.get(n),c=o.track.getSettings(),d=i.outboundVideoRtpId.map(u=>{const h=e.outboundVideoRtp.get(u);return h.frameHeight||(h.frameHeight=c.height,h.frameWidth=c.width,h.framesPerSecond=c.frameRate),h}),l={producerId:n,appData:o.appData,videoStats:d,audioStats:i.outboundAudioRtpId.map(u=>e.outboundAudioRtp.get(u))};r.push(l)})}catch(i){console.error("getProducersReport: ",i,e)}return r}getConsumerStatsFromParsedConsumerStats(e,r,i){let n;try{const{peerId:o,producerId:c,appData:d}=this.consumerPeerIdMap.get(i),l=r==null?void 0:r.inboundVideoRtpId.map(u=>{const g=this.consumerMap.get(i).track.getSettings(),v=e.inboundVideoRtp.get(u);return v.frameHeight||(v.frameHeight=g.height,v.frameWidth=g.width,v.framesPerSecond=g.frameRate),v});n={consumerId:i,peerId:o,producerId:c,appData:d,videoStats:l,audioStats:r==null?void 0:r.inboundAudioRtpId.map(u=>e.inboundAudioRtp.get(u))}}catch(o){console.error("getConsumerStatsFromParsedConsumerStats: ",o,e)}return n}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((i,n)=>{r.push(this.getConsumerStatsFromParsedConsumerStats(e,i,n))})}catch(i){console.error("getConsumerStatsFromReport: ",i,e)}return r}}class Ly extends cg{}function $d(s,t,e,r){if(s!=null&&s.logger&&s.logger.error("Callstats::handleError",{error:r}),typeof e=="function"&&r instanceof t)e.call(null,r,s);else throw r}function dg(s,t,e){const r=s.value;return s.value=function(...i){try{const n=r.apply(this,i);return n&&n instanceof Promise?n.catch(o=>{$d(this,t,e,o)}):n}catch(n){$d(this,t,e,n)}return null},s}const Y=(s,t)=>(e,r,i)=>{const n=i.value;return i.value=function(...o){try{const c=n.apply(this,o);return c&&c instanceof Promise?c.catch(d=>{$d(this,s,t,d)}):c}catch(c){$d(this,s,t,c)}return null},i},Vy=(s,t)=>(e,r,i)=>{if(i)return dg(i,s,t);for(const n of Reflect.ownKeys(e.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(e.prototype,n);o.value instanceof Function&&Object.defineProperty(e.prototype,n,dg(o,s,t))}};var J=globalThis&&globalThis.__decorate||function(s,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(s,t,e,r);else for(var c=s.length-1;c>=0;c--)(o=s[c])&&(n=(i<3?o(n):i>3?o(t,e,n):o(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n};const K=console;let q=class extends Tt{constructor(e="https://api.testingv3.dyte.in",r="Blink",i=Gm.PROD,n,o,c,d,l){super();p(this,"observer");p(this,"eventHandler");p(this,"measurements");p(this,"producingTransport");p(this,"consumingTransport");p(this,"producers",new Map);p(this,"consumers",new Map);p(this,"iceServers");p(this,"connectionInfoPromise");p(this,"pingStatsTimeout");p(this,"logger");p(this,"env");p(this,"apiHostnames");p(this,"peerId");p(this,"consumerSharedMediaStatesMap",new Map);p(this,"currentUserMediaStates",{});if(!l)throw Error("authToken is missing but required to initialize CallStats!");switch(this.env=i,this.apiHostnames=d,this.logger=o,this.peerId=c,this.eventHandler=new Ey({logger:o,peerId:c,apiHostnames:d,authToken:l}),this.logger.debug("callStats::engineName: ",{engineName:r}),r){case"Blink":this.measurements=new Ny;break;case"Gecko":this.measurements=new cg;break;case"WebKit":this.measurements=new Ly;break;default:throw Error(`Unknown engineName! ${r}`)}this.measurements.callStatsInstance=this,this.registerProducer=this.registerProducer.bind(this),this.registerConsumer=this.registerConsumer.bind(this),this.observer=new Tt,this.measurements.observer.on("consumer_score",u=>{o.debug(`callStats::consumer_score ${[...u.entries()]}`),this.eventHandler.emit("consumer_score",u)}),this.measurements.observer.on("producer_score",u=>{o.debug(`callStats::producer_score ${[...u.entries()]}`),this.eventHandler.emit("producer_score",u)})}registerIceServers(e){this.iceServers=e}registerConsumer(e){var r;this.consumerSharedMediaStatesMap.has(e.id)||this.consumerSharedMediaStatesMap.set(e.id,{}),this.consumers.set(e.id,e),this.measurements.registerConsumer(e),this.logger.debug("callStats::registerConsumer",{consumerId:e.id,consumerkind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)}),e.on("close",this.deRegisterConsumer.bind(this,e))}registerProducer(e){var r;this.producers.set(e.id,e),this.measurements.registerProducer(e),this.logger.debug("callStats::registerProducer",{producerId:e.id,producerKind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)}),e.on("close",this.deRegisterProducer.bind(this,e))}sendConsumerSharedMediaStateEvent(e,r){this.consumerSharedMediaStatesMap.has(e)||this.consumerSharedMediaStatesMap.set(e,{});const i=this.consumerSharedMediaStatesMap.get(e);this.consumerSharedMediaStatesMap.set(e,Object.assign(i,r))}registerProducingTransport(e){var i;this.producingTransport=e,e.on("close",this.disconnectProducingTransport.bind(this,e)),e.on("disconnect",this.disconnectProducingTransport.bind(this,e)),Array.from(((i=e._producers)==null?void 0:i.values())||[]).forEach(n=>{this.registerProducer(n)}),e.on("newproducer",this.registerProducer)}registerConsumingTransport(e){var i;this.consumingTransport=e,e.on("close",this.disconnectConsumingTransport.bind(this,e)),e.on("disconnect",this.disconnectConsumingTransport.bind(this,e)),Array.from(((i=e._consumers)==null?void 0:i.values())||[]).forEach(n=>{this.registerConsumer(n)}),e.on("newconsumer",this.registerConsumer)}deRegisterConsumer(e){this.consumers.delete(e.id)}deRegisterProducer(e){var r;this.producers.delete(e.id),this.logger.debug("callStats::deRegisterProducer",{producerId:e.id,producerKind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)})}disconnectConsumingTransport(){this.consumingTransport=void 0}disconnectProducingTransport(){this.producingTransport=void 0}callEvent(e){this.eventHandler.callEvent(e)}sendPreCallTestBeginEvent(e=!1,r){this.connectionInfoPromise=this.measurements.getNetworkInfo(this.iceServers,e),this.eventHandler.callEvent({event:L.PRECALL_TEST_BEGIN,timestamp:r}),this.connectionInfoPromise.then(i=>{this.eventHandler.callEvent({event:L.PRECALL_TEST_COMPLETE,metaData:{connectionInfo:i},timestamp:r})})}sendScreenShareToggleEvent(e,r=null,i){this.currentUserMediaStates.screen=e,this.eventHandler.callEvent({event:e?L.SCREENSHARE_STARTED:L.SCREENSHARE_STOPPED,metaData:{ssrc:r},timestamp:i})}sendScreenShareRequestedEvent(e){this.eventHandler.callEvent({event:L.SCREENSHARE_START_REQUESTED,timestamp:e})}sendActiveSpeakerEvent(e,r){this.eventHandler.callEvent({event:L.DOMINANT_SPEAKER,metaData:{peerId:e},timestamp:r})}devices(e,r,i){this.eventHandler.callEvent({event:e===ts.AUDIO&&L.AUDIO_DEVICES_UPDATES||e===ts.VIDEO&&L.VIDEO_DEVICES_UPDATES||e===ts.SPEAKER&&L.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:r},timestamp:i})}selectedDevice(e,r,i){this.eventHandler.callEvent({event:e===ts.AUDIO&&L.SELECTED_MICROHPONE_UPDATE||e===ts.VIDEO&&L.SELECTED_CAMERA_UPDATE||e===ts.SPEAKER&&L.SELECTED_SPEAKER_UPDATE,metaData:{device:r},timestamp:i})}mediaPermission(e,r,i){this.eventHandler.callEvent({event:L.MEDIA_PERMISSION,metaData:{deviceType:e,permission:r},timestamp:i})}mediaPlaybackFailed(e,r){this.eventHandler.callEvent({event:e===ts.AUDIO&&L.AUDIO_PLAY_FAILED||e===ts.VIDEO&&L.VIDEO_PLAY_FAILED,metaData:{deviceType:e},timestamp:r})}mediaTrackMuted(e,r){this.eventHandler.callEvent({event:e===ts.AUDIO&&L.AUDIO_TRACK_MUTED||e===ts.VIDEO&&L.VIDEO_TRACK_MUTED,metaData:{deviceType:e},timestamp:r})}tabChanged(e,r){this.eventHandler.callEvent({event:L.TAB_CHANGE,metaData:{isMeetingsTabActive:e},timestamp:r})}browserBackgrounded(e){this.eventHandler.callEvent({event:L.BROWSER_BACKGROUNDED,timestamp:e})}browserForegrounded(e){this.eventHandler.callEvent({event:L.BROWSER_FOREGROUNDED,timestamp:e})}legacySwitch(e,r){this.eventHandler.callEvent({event:L.LEGACY_SWITCH,metadata:{on:e},timestamp:r})}async getPreCallTestResults(){return this.connectionInfoPromise}sendCallJoinBeginEvent(e,r){e={...e,meetingEnv:this.env},e.deviceInfo={...e.deviceInfo,userAgent:navigator.userAgent,cpus:navigator.hardwareConcurrency,memory:navigator.deviceMemory},this.eventHandler.callEvent({event:L.CALL_JOIN_BEGIN,metaData:{peerMetaData:e},timestamp:r})}sendNetworkQualityTestBeginEvent(e,r){this.eventHandler.callEvent({event:L.NET_QUALITY_TEST_BEGIN,timestamp:r}),new Promise(async(n,o)=>{const c=[];try{for(const d of e)try{if(d.iceServers&&d.iceServers.length>0){const l=await this.measurements.getNetworkQuality(d.iceServers);c.push({...d,networkResults:l})}}catch(l){console.warn("Error handling ",l)}n({regionData:c})}catch(d){console.warn("Error in callstats, ",d),o(d)}}).then(n=>{this.eventHandler.callEvent({event:L.NET_QUALITY_TEST_END,timestamp:r,metaData:n})})}sendWebSocketConnectedEvent(e){this.eventHandler.callEvent({event:L.WEBSOCKET_CONNECTED,timestamp:e})}sendTransportConnectedEvent(e){this.eventHandler.callEvent({event:L.TRANSPORT_CONNECTED,timestamp:e})}sendAudioToggleEvent(e,r){this.currentUserMediaStates.audio=e;let i;e?i=L.AUDIO_ON:i=L.AUDIO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendVideoToggleEvent(e,r){this.currentUserMediaStates.video=e;let i;e?i=L.VIDEO_ON:i=L.VIDEO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendParticipantRoleToggleEvent(e,r){this.eventHandler.callEvent({event:L.PARTICIPANT_ROLE,timestamp:r,metaData:e})}startPingStats(e=7e3){this.sendPingStatsEvent(!1,new Date),this.pingStatsTimeout=setInterval(this.sendPingStatsEvent.bind(this),e)}stopPingStats(){clearInterval(this.pingStatsTimeout)}async sendPingStatsEvent(e=!0,r){var c,d;let i,n;if(this.producingTransport&&(i=await this.measurements.getProcessedStats(this.producingTransport,!1,!0),!i||!((c=i==null?void 0:i.producerReport)!=null&&c.length))){this.logger.debug("callStats::sendPingStatsEvent::staleProducingTransport",{disclaimer:"Stale producer? Regenerating Stream Maps!"});const l=await this.measurements.getProducersReport([...this.producers.values()]);i&&l?i.producerReport=l:(i=await this.measurements.getProcessedStats(this.producingTransport,!1,!0),(!i||!(i!=null&&i.producerReport))&&this.logger.debug("callStats::sendPingStatsEvent::noProducingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}if(this.consumingTransport){const l=new Set(this.measurements.inboundConsumerMap.values()),u=[...this.consumers.values()].filter(g=>!g.paused&&!l.has(g.id));if((await Promise.allSettled(u.map(g=>this.measurements.generateConsumerStreamMap(g)))).forEach((g,v)=>{g.status==="rejected"&&this.logger.error("callStats::sendPingStatsEvent::consumerGetStatsFailed",{consumerId:u[v].id,error:g.reason instanceof Error?g.reason.message:String(g.reason),stack:g.reason instanceof Error?g.reason.stack:void 0})}),n=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),!n||!((d=n.consumerReport)!=null&&d.length)){this.logger.debug("callStats::sendPingStatsEvent::staleConsumingTransport",{disclaimer:"Stale consumer? Regenerating Stream Maps!"});const g=await this.measurements.getConsumersReport([...this.consumers.values()]);n&&g?n.consumerReport=g:(n=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),(!n||!n.consumerReport)&&this.logger.debug("callStats::sendPingStatsEvent::noConsumingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}}const o={producingTransportStats:i?i==null?void 0:i.transportReport:void 0,consumingTransportStats:n?n==null?void 0:n.transportReport:void 0,producerStats:[].concat((i==null?void 0:i.producerReport)||[]).concat((n==null?void 0:n.producerReport)||[]),consumerStats:[].concat((n==null?void 0:n.consumerReport)||[]).concat((i==null?void 0:i.consumerReport)||[])};if(e&&o.producerStats.length===0&&o.consumerStats.length===0){await this.eventHandler.flush();return}this.eventHandler.callEvent({event:L.PING_STAT,metaData:o,timestamp:r})}sendIVSPlayerRebufferEvent(e){this.eventHandler.callEvent({event:L.IVS_PLAYER_REBUFFERING,timestamp:e})}sendIVSPlayerAudioBlockEvent(e){this.eventHandler.callEvent({event:L.IVS_PLAYER_AUDIO_BLOCKED,timestamp:e})}sendIVSPlayerPlaybackBlockedEvent(e){this.eventHandler.callEvent({event:L.IVS_PLAYER_PLAYBACK_BLOCKED,timestamp:e})}sendIVSPlayerNetworkUnavailableEvent(e){this.eventHandler.callEvent({event:L.IVS_PLAYER_NETWORK_UNAVAILABLE,timestamp:e})}sendIVSPlayerInitializedEvent(e){this.eventHandler.callEvent({event:L.IVS_PLAYER_INITIALIZED,timestamp:e})}sendIVSPlayerWorkerErrorEvent(e){this.eventHandler.callEvent({event:L.IVS_PLAYER_WORKER_ERROR,timestamp:e})}sendIVSPlayerErrorEvent(e,r){this.eventHandler.callEvent({event:L.IVS_PLAYER_ERROR,timestamp:r,metaData:e})}sendIVSPlayerRecoverableErrorEvent(e,r){this.eventHandler.callEvent({event:L.IVS_PLAYER_RECOVERABLE_ERROR,timestamp:r,metaData:e})}sendIVSPlayerAnalyticsEvent(e,r){this.eventHandler.callEvent({event:L.IVS_PLAYER_ANALYTICS_EVENT,timestamp:r,metaData:e})}sendIVSPlayerPlaybackRateChangedEvent(e,r){this.eventHandler.callEvent({event:L.IVS_PLAYER_PLAYBACK_RATE_CHANGED,timestamp:r,metaData:{updatedPlaybackRate:e}})}sendIVSPlayerQualityChanged(e,r){this.eventHandler.callEvent({event:L.IVS_PLAYER_QUALITY_CHANGED,timestamp:r,metaData:e})}sendPlayerLiveLatency(e,r){this.eventHandler.callEvent({event:L.LIVESTREAM_LATENCY,timestamp:r,metaData:{latency:e}})}sendDisconnectEvent(e){this.eventHandler.callEvent({event:L.DISCONNECT,timestamp:e})}sendReconnectEvent(e){this.eventHandler.callEvent({event:L.RECONNECT_ATTEMPT,timestamp:e})}expectedVideoResolution(e,r,i){this.eventHandler.callEvent({event:L.EXPECTED_VIDEO_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}expectedScreenshareResolution(e,r,i){this.eventHandler.callEvent({event:L.EXPECTED_SCREENSHARE_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}};J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"registerIceServers",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"registerConsumer",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"registerProducer",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendConsumerSharedMediaStateEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"registerProducingTransport",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"registerConsumingTransport",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"deRegisterConsumer",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"deRegisterProducer",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"disconnectConsumingTransport",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"disconnectProducingTransport",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendPreCallTestBeginEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendScreenShareToggleEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendScreenShareRequestedEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendActiveSpeakerEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"devices",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"selectedDevice",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"mediaPermission",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"mediaPlaybackFailed",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"mediaTrackMuted",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"tabChanged",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"browserBackgrounded",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"browserForegrounded",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"legacySwitch",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"getPreCallTestResults",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendCallJoinBeginEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendNetworkQualityTestBeginEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendWebSocketConnectedEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendTransportConnectedEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendAudioToggleEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendVideoToggleEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendParticipantRoleToggleEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"startPingStats",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"stopPingStats",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendPingStatsEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendIVSPlayerRebufferEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendIVSPlayerAudioBlockEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendIVSPlayerPlaybackBlockedEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendIVSPlayerNetworkUnavailableEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendIVSPlayerInitializedEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendIVSPlayerWorkerErrorEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendIVSPlayerErrorEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendIVSPlayerRecoverableErrorEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendIVSPlayerAnalyticsEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendIVSPlayerQualityChanged",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendPlayerLiveLatency",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendDisconnectEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"sendReconnectEvent",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"expectedVideoResolution",null),J([Y(TypeError,(s,t)=>K.error(t,s))],q.prototype,"expectedScreenshareResolution",null),q=J([Vy(TypeError,(s,t)=>K.error(t,s))],q);const xy=q;class lg extends Tt{constructor(){super(...arguments);p(this,"stats");p(this,"peerId");p(this,"backend");p(this,"iceServers");p(this,"initialized",!1);p(this,"stalled",!1);p(this,"logger")}async initialize({peerId:e,engineName:r,env:i=Gm.PROD,iceServers:n,apiBase:o="https://api.cluster.dyte.in",flags:c,logger:d=console,apiHostnames:l,skipConnectivityChecks:u=!1,authToken:h}){var g,v,y;try{if(this.peerId=e,this.logger=d,!h){this.logger.error("callStats::initialize",{event:"auth_token_missing",peerId:this.peerId}),this.stallCallStats();return}this.backend=new xy(o,r,i,c,d,e,l,h),this.iceServers=n,(g=this.backend)==null||g.registerIceServers(this.iceServers),this.initialized=!0,this.startPreCallTest(u),(y=(v=this.backend)==null?void 0:v.eventHandler)==null||y.emit("initialized"),this.emit("initialized")}catch(k){this.logger.error("callStats::CallStatsIntegration",{peerId:this.peerId,error:k instanceof Error?k.message:String(k),stack:k instanceof Error?k.stack:void 0}),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)})}async candidateRegionalNetworkQualityTest(e){const r=new Date;this.onSafeInitialization(()=>{var i;try{(i=this.backend)==null||i.sendNetworkQualityTestBeginEvent(e,r)}catch(n){this.logger.error("callStats::sendNetworkQualityTestBeginEvent",{error:{reason:n.reason}})}})}async roomJoined(e){const r=new Date;this.onSafeInitialization(()=>{var i,n;(i=this.backend)==null||i.sendCallJoinBeginEvent(e,r),this.backend,(n=this.backend)==null||n.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,i;(r=this.backend)==null||r.stopPingStats(),(i=this.backend)==null||i.sendDisconnectEvent(e)})}screenShareStart(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendScreenShareToggleEvent(!0,e,r)})}consumerSharedMediaState(e,r){this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendConsumerSharedMediaStateEvent(e,r)})}screenShareStop(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.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 i;(i=this.backend)==null||i.sendActiveSpeakerEvent(e,r)})}devices(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.devices(e,r,i)})}selectedDevice(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.selectedDevice(e,r,i)})}mediaPermission(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.mediaPermission(e,r,i)})}mediaPlaybackFailed(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.mediaPlaybackFailed(e,r)})}mediaTrackMuted(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.mediaTrackMuted(e,r)})}tabChanged(e=!1){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.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 i;(i=this.backend)==null||i.legacySwitch(e,r)})}async startPreCallTest(e=!1){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendPreCallTestBeginEvent(e,r)})}onPreCallTestResults(e){return this.onSafeInitialization(()=>{var r,i;(i=(r=this.backend)==null?void 0:r.getPreCallTestResults())==null||i.then(n=>{n&&e({connectionInfo:n})},n=>{this.logger.error("callStats::onPreCallTestResults",{peerId:this.peerId,error:n instanceof Error?n.message:String(n),stack:n instanceof Error?n.stack:void 0})})}),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(!1);else if(!this.stalled){const r=()=>{e(!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 i=new Date;this.onSafeInitialization(()=>{var n,o,c,d,l,u,h,g,v,y,k;switch(e){case"PlayerRebuffering":(n=this.backend)==null||n.sendIVSPlayerRebufferEvent(i);break;case"PlayerAudioBlocked":(o=this.backend)==null||o.sendIVSPlayerAudioBlockEvent(i);break;case"PlayerPlaybackBlocked":(c=this.backend)==null||c.sendIVSPlayerPlaybackBlockedEvent(i);break;case"PlayerNetworkUnavailable":(d=this.backend)==null||d.sendIVSPlayerNetworkUnavailableEvent(i);break;case"PlayerInitialized":(l=this.backend)==null||l.sendIVSPlayerInitializedEvent(i);break;case"PlayerWorkerError":(u=this.backend)==null||u.sendIVSPlayerWorkerErrorEvent(i);break;case"PlayerError":(h=this.backend)==null||h.sendIVSPlayerErrorEvent(r,i);break;case"PlayerRecoverableError":(g=this.backend)==null||g.sendIVSPlayerRecoverableErrorEvent(r,i);break;case"PlayerAnalyticsEvent":(v=this.backend)==null||v.sendIVSPlayerAnalyticsEvent(r,i);break;case"PlayerPlaybackRateChanged":(y=this.backend)==null||y.sendIVSPlayerPlaybackRateChangedEvent(r,i);break;case"PlayerQualityChanged":(k=this.backend)==null||k.sendIVSPlayerQualityChanged(r,i);break}})}livestreamLatency(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendPlayerLiveLatency(e,r)})}expectedVideoResolution(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.expectedVideoResolution(e,r,i)})}expectedScreenshareResolution(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.expectedScreenshareResolution(e,r,i)})}}new lg().setMaxListeners(30);class $y{constructor(){m(this,Ho,void 0)}get telemetry(){var t;return(t=a(this,Ho))==null?void 0:t.getValue("telemetry")}init(t){f(this,Ho,t)}info(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("info",t,e,r)}error(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("error",t,e,r)}debug(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("debug",t,e,r)}log(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("log",t,e,r)}warn(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("warn",t,e,r)}}Ho=new WeakMap;function ug(s,t,e,r){try{t==null||t.error(`EventEmitter listener error on event ${e.toString()}`,{error:r,eventListener:{eventName:e.toString(),listenerCount:s.listenerCount(e)}});return}catch(i){return}}function no(s,t,e,r){const i=s.rawListeners(t);return i.forEach(n=>{try{const o=Reflect.apply(n,s,e);o&&typeof o.then=="function"&&Promise.resolve(o).catch(c=>ug(s,r,t,c))}catch(o){ug(s,r,t,o)}}),i.length>0}class Bn extends Tt.EventEmitter{constructor(e){super();p(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return no(this,"*",[e,...r],this.logger),no(this,e,r,this.logger)}on(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.on(e,r)}addListener(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.addListener(e,r)}off(e,r){return super.off(e,r)}once(e,r){return super.once(e,r)}prependListener(e,r){return super.prependListener(e,r)}prependOnceListener(e,r){return super.prependOnceListener(e,r)}removeListener(e,r){return super.removeListener(e,r)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}class Bt extends Tt.EventEmitter{constructor(e){super();p(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return no(this,"*",[e,...r],this.logger),no(this,e,r,this.logger)}on(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.on(e,r)}addListener(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.addListener(e,r)}off(e,r){return super.off(e,r)}once(e,r){return super.once(e,r)}prependListener(e,r){return super.prependListener(e,r)}prependOnceListener(e,r){return super.prependOnceListener(e,r)}removeListener(e,r){return super.removeListener(e,r)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}class Uy extends Tt.EventEmitter{constructor(e){super();m(this,fr,void 0);m(this,vr,void 0);p(this,"asyncPromiseTimeout");p(this,"logger");this.logger=e,f(this,fr,new Map),f(this,vr,new Map),this.asyncPromiseTimeout=8e3}emit(e,...r){return no(this,e,r,this.logger)}async emitAsync(e,...r){a(this,fr).set(e,[]);const i=a(this,vr).get(e).map(()=>new Promise(n=>{a(this,fr).get(e).push(n)}));this.emit(e,...r),await Promise.race([Promise.all(i),new Promise((n,o)=>setTimeout(()=>o(new Error(`emitAsync failed to resolve for event ${e}.`)),this.asyncPromiseTimeout))]),a(this,fr).delete(e)}onAsync(e,r){const i=a(this,fr),n=async(...o)=>{var d;try{await r(...o)}catch(l){this.logger.error("[onAsync]",{error:l})}const c=(d=i.get(e))==null?void 0:d.shift();c==null||c()};return a(this,vr).get(e)||a(this,vr).set(e,[]),a(this,vr).get(e).push(n),super.on(e,n)}reset(){f(this,fr,new Map),f(this,vr,new Map),super.removeAllListeners()}}fr=new WeakMap,vr=new WeakMap;var By=typeof global=="object"&&global&&global.Object===Object&&global;const hg=By;var Fy=typeof self=="object"&&self&&self.Object===Object&&self,Hy=hg||Fy||Function("return this")();const fs=Hy;var qy=fs.Symbol;const Ms=qy;var pg=Object.prototype,jy=pg.hasOwnProperty,Gy=pg.toString,ao=Ms?Ms.toStringTag:void 0;function Wy(s){var t=jy.call(s,ao),e=s[ao];try{s[ao]=void 0;var r=!0}catch(n){}var i=Gy.call(s);return r&&(t?s[ao]=e:delete s[ao]),i}var Jy=Object.prototype,Ky=Jy.toString;function zy(s){return Ky.call(s)}var Yy="[object Null]",Qy="[object Undefined]",mg=Ms?Ms.toStringTag:void 0;function Ri(s){return s==null?s===void 0?Qy:Yy:mg&&mg in Object(s)?Wy(s):zy(s)}function Os(s){return s!=null&&typeof s=="object"}var Xy="[object Symbol]";function Ud(s){return typeof s=="symbol"||Os(s)&&Ri(s)==Xy}function Zy(s,t){for(var e=-1,r=s==null?0:s.length,i=Array(r);++e<r;)i[e]=t(s[e],e,s);return i}var eE=Array.isArray;const Ft=eE;var tE=1/0,gg=Ms?Ms.prototype:void 0,fg=gg?gg.toString:void 0;function vg(s){if(typeof s=="string")return s;if(Ft(s))return Zy(s,vg)+"";if(Ud(s))return fg?fg.call(s):"";var t=s+"";return t=="0"&&1/s==-tE?"-0":t}var sE=/\s/;function rE(s){for(var t=s.length;t--&&sE.test(s.charAt(t)););return t}var iE=/^\s+/;function nE(s){return s&&s.slice(0,rE(s)+1).replace(iE,"")}function ss(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var Sg=0/0,aE=/^[-+]0x[0-9a-f]+$/i,oE=/^0b[01]+$/i,cE=/^0o[0-7]+$/i,dE=parseInt;function Tg(s){if(typeof s=="number")return s;if(Ud(s))return Sg;if(ss(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=ss(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=nE(s);var e=oE.test(s);return e||cE.test(s)?dE(s.slice(2),e?2:8):aE.test(s)?Sg:+s}function dh(s){return s}var lE="[object AsyncFunction]",uE="[object Function]",hE="[object GeneratorFunction]",pE="[object Proxy]";function lh(s){if(!ss(s))return!1;var t=Ri(s);return t==uE||t==hE||t==lE||t==pE}var mE=fs["__core-js_shared__"];const uh=mE;var yg=function(){var s=/[^.]+$/.exec(uh&&uh.keys&&uh.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function gE(s){return!!yg&&yg in s}var fE=Function.prototype,vE=fE.toString;function Ii(s){if(s!=null){try{return vE.call(s)}catch(t){}try{return s+""}catch(t){}}return""}var SE=/[\\^$.*+?()[\]{}|]/g,TE=/^\[object .+?Constructor\]$/,yE=Function.prototype,EE=Object.prototype,bE=yE.toString,wE=EE.hasOwnProperty,PE=RegExp("^"+bE.call(wE).replace(SE,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function kE(s){if(!ss(s)||gE(s))return!1;var t=lh(s)?PE:TE;return t.test(Ii(s))}function _E(s,t){return s==null?void 0:s[t]}function Ai(s,t){var e=_E(s,t);return kE(e)?e:void 0}var CE=Ai(fs,"WeakMap");const hh=CE;var Eg=Object.create,RE=function(){function s(){}return function(t){if(!ss(t))return{};if(Eg)return Eg(t);s.prototype=t;var e=new s;return s.prototype=void 0,e}}();const IE=RE;function AE(s,t,e){switch(e.length){case 0:return s.call(t);case 1:return s.call(t,e[0]);case 2:return s.call(t,e[0],e[1]);case 3:return s.call(t,e[0],e[1],e[2])}return s.apply(t,e)}function ME(){}function bg(s,t){var e=-1,r=s.length;for(t||(t=Array(r));++e<r;)t[e]=s[e];return t}var OE=800,DE=16,NE=Date.now;function LE(s){var t=0,e=0;return function(){var r=NE(),i=DE-(r-e);if(e=r,i>0){if(++t>=OE)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}function VE(s){return function(){return s}}var xE=function(){try{var s=Ai(Object,"defineProperty");return s({},"",{}),s}catch(t){}}();const Bd=xE;var $E=Bd?function(s,t){return Bd(s,"toString",{configurable:!0,enumerable:!1,value:VE(t),writable:!0})}:dh,UE=LE($E);const BE=UE;function FE(s,t){for(var e=-1,r=s==null?0:s.length;++e<r&&t(s[e],e,s)!==!1;);return s}function HE(s,t,e,r){for(var i=s.length,n=e+(r?1:-1);r?n--:++n<i;)if(t(s[n],n,s))return n;return-1}function qE(s){return s!==s}function jE(s,t,e){for(var r=e-1,i=s.length;++r<i;)if(s[r]===t)return r;return-1}function GE(s,t,e){return t===t?jE(s,t,e):HE(s,qE,e)}function WE(s,t){var e=s==null?0:s.length;return!!e&&GE(s,t,0)>-1}var JE=9007199254740991,KE=/^(?:0|[1-9]\d*)$/;function ph(s,t){var e=typeof s;return t=t==null?JE:t,!!t&&(e=="number"||e!="symbol"&&KE.test(s))&&s>-1&&s%1==0&&s<t}function mh(s,t,e){t=="__proto__"&&Bd?Bd(s,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):s[t]=e}function oo(s,t){return s===t||s!==s&&t!==t}var zE=Object.prototype,YE=zE.hasOwnProperty;function wg(s,t,e){var r=s[t];(!(YE.call(s,t)&&oo(r,e))||e===void 0&&!(t in s))&&mh(s,t,e)}function co(s,t,e,r){var i=!e;e||(e={});for(var n=-1,o=t.length;++n<o;){var c=t[n],d=r?r(e[c],s[c],c,e,s):void 0;d===void 0&&(d=s[c]),i?mh(e,c,d):wg(e,c,d)}return e}var Pg=Math.max;function QE(s,t,e){return t=Pg(t===void 0?s.length-1:t,0),function(){for(var r=arguments,i=-1,n=Pg(r.length-t,0),o=Array(n);++i<n;)o[i]=r[t+i];i=-1;for(var c=Array(t+1);++i<t;)c[i]=r[i];return c[t]=e(o),AE(s,this,c)}}function XE(s,t){return BE(QE(s,t,dh),s+"")}var ZE=9007199254740991;function gh(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=ZE}function lo(s){return s!=null&&gh(s.length)&&!lh(s)}function eb(s,t,e){if(!ss(e))return!1;var r=typeof t;return(r=="number"?lo(e)&&ph(t,e.length):r=="string"&&t in e)?oo(e[t],s):!1}function tb(s){return XE(function(t,e){var r=-1,i=e.length,n=i>1?e[i-1]:void 0,o=i>2?e[2]:void 0;for(n=s.length>3&&typeof n=="function"?(i--,n):void 0,o&&eb(e[0],e[1],o)&&(n=i<3?void 0:n,i=1),t=Object(t);++r<i;){var c=e[r];c&&s(t,c,r,n)}return t})}var sb=Object.prototype;function Fd(s){var t=s&&s.constructor,e=typeof t=="function"&&t.prototype||sb;return s===e}function rb(s,t){for(var e=-1,r=Array(s);++e<s;)r[e]=t(e);return r}var ib="[object Arguments]";function kg(s){return Os(s)&&Ri(s)==ib}var _g=Object.prototype,nb=_g.hasOwnProperty,ab=_g.propertyIsEnumerable,ob=kg(function(){return arguments}())?kg:function(s){return Os(s)&&nb.call(s,"callee")&&!ab.call(s,"callee")};const uo=ob;function cb(){return!1}var Cg=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Rg=Cg&&typeof module=="object"&&module&&!module.nodeType&&module,db=Rg&&Rg.exports===Cg,Ig=db?fs.Buffer:void 0,lb=Ig?Ig.isBuffer:void 0,ub=lb||cb;const Fn=ub;var hb="[object Arguments]",pb="[object Array]",mb="[object Boolean]",gb="[object Date]",fb="[object Error]",vb="[object Function]",Sb="[object Map]",Tb="[object Number]",yb="[object Object]",Eb="[object RegExp]",bb="[object Set]",wb="[object String]",Pb="[object WeakMap]",kb="[object ArrayBuffer]",_b="[object DataView]",Cb="[object Float32Array]",Rb="[object Float64Array]",Ib="[object Int8Array]",Ab="[object Int16Array]",Mb="[object Int32Array]",Ob="[object Uint8Array]",Db="[object Uint8ClampedArray]",Nb="[object Uint16Array]",Lb="[object Uint32Array]",ke={};ke[Cb]=ke[Rb]=ke[Ib]=ke[Ab]=ke[Mb]=ke[Ob]=ke[Db]=ke[Nb]=ke[Lb]=!0,ke[hb]=ke[pb]=ke[kb]=ke[mb]=ke[_b]=ke[gb]=ke[fb]=ke[vb]=ke[Sb]=ke[Tb]=ke[yb]=ke[Eb]=ke[bb]=ke[wb]=ke[Pb]=!1;function Vb(s){return Os(s)&&gh(s.length)&&!!ke[Ri(s)]}function fh(s){return function(t){return s(t)}}var Ag=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ho=Ag&&typeof module=="object"&&module&&!module.nodeType&&module,xb=ho&&ho.exports===Ag,vh=xb&&hg.process,$b=function(){try{var s=ho&&ho.require&&ho.require("util").types;return s||vh&&vh.binding&&vh.binding("util")}catch(t){}}();const Hn=$b;var Mg=Hn&&Hn.isTypedArray,Ub=Mg?fh(Mg):Vb;const Hd=Ub;var Bb=Object.prototype,Fb=Bb.hasOwnProperty;function Og(s,t){var e=Ft(s),r=!e&&uo(s),i=!e&&!r&&Fn(s),n=!e&&!r&&!i&&Hd(s),o=e||r||i||n,c=o?rb(s.length,String):[],d=c.length;for(var l in s)(t||Fb.call(s,l))&&!(o&&(l=="length"||i&&(l=="offset"||l=="parent")||n&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||ph(l,d)))&&c.push(l);return c}function Dg(s,t){return function(e){return s(t(e))}}var Hb=Dg(Object.keys,Object);const qb=Hb;var jb=Object.prototype,Gb=jb.hasOwnProperty;function Ng(s){if(!Fd(s))return qb(s);var t=[];for(var e in Object(s))Gb.call(s,e)&&e!="constructor"&&t.push(e);return t}function qd(s){return lo(s)?Og(s):Ng(s)}function Wb(s){var t=[];if(s!=null)for(var e in Object(s))t.push(e);return t}var Jb=Object.prototype,Kb=Jb.hasOwnProperty;function zb(s){if(!ss(s))return Wb(s);var t=Fd(s),e=[];for(var r in s)r=="constructor"&&(t||!Kb.call(s,r))||e.push(r);return e}function po(s){return lo(s)?Og(s,!0):zb(s)}var Yb=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Qb=/^\w*$/;function Sh(s,t){if(Ft(s))return!1;var e=typeof s;return e=="number"||e=="symbol"||e=="boolean"||s==null||Ud(s)?!0:Qb.test(s)||!Yb.test(s)||t!=null&&s in Object(t)}var Xb=Ai(Object,"create");const mo=Xb;function Zb(){this.__data__=mo?mo(null):{},this.size=0}function ew(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var tw="__lodash_hash_undefined__",sw=Object.prototype,rw=sw.hasOwnProperty;function iw(s){var t=this.__data__;if(mo){var e=t[s];return e===tw?void 0:e}return rw.call(t,s)?t[s]:void 0}var nw=Object.prototype,aw=nw.hasOwnProperty;function ow(s){var t=this.__data__;return mo?t[s]!==void 0:aw.call(t,s)}var cw="__lodash_hash_undefined__";function dw(s,t){var e=this.__data__;return this.size+=this.has(s)?0:1,e[s]=mo&&t===void 0?cw:t,this}function Mi(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}Mi.prototype.clear=Zb,Mi.prototype.delete=ew,Mi.prototype.get=iw,Mi.prototype.has=ow,Mi.prototype.set=dw;function lw(){this.__data__=[],this.size=0}function jd(s,t){for(var e=s.length;e--;)if(oo(s[e][0],t))return e;return-1}var uw=Array.prototype,hw=uw.splice;function pw(s){var t=this.__data__,e=jd(t,s);if(e<0)return!1;var r=t.length-1;return e==r?t.pop():hw.call(t,e,1),--this.size,!0}function mw(s){var t=this.__data__,e=jd(t,s);return e<0?void 0:t[e][1]}function gw(s){return jd(this.__data__,s)>-1}function fw(s,t){var e=this.__data__,r=jd(e,s);return r<0?(++this.size,e.push([s,t])):e[r][1]=t,this}function sr(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}sr.prototype.clear=lw,sr.prototype.delete=pw,sr.prototype.get=mw,sr.prototype.has=gw,sr.prototype.set=fw;var vw=Ai(fs,"Map");const go=vw;function Sw(){this.size=0,this.__data__={hash:new Mi,map:new(go||sr),string:new Mi}}function Tw(s){var t=typeof s;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?s!=="__proto__":s===null}function Gd(s,t){var e=s.__data__;return Tw(t)?e[typeof t=="string"?"string":"hash"]:e.map}function yw(s){var t=Gd(this,s).delete(s);return this.size-=t?1:0,t}function Ew(s){return Gd(this,s).get(s)}function bw(s){return Gd(this,s).has(s)}function ww(s,t){var e=Gd(this,s),r=e.size;return e.set(s,t),this.size+=e.size==r?0:1,this}function rr(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}rr.prototype.clear=Sw,rr.prototype.delete=yw,rr.prototype.get=Ew,rr.prototype.has=bw,rr.prototype.set=ww;var Pw="Expected a function";function Th(s,t){if(typeof s!="function"||t!=null&&typeof t!="function")throw new TypeError(Pw);var e=function(){var r=arguments,i=t?t.apply(this,r):r[0],n=e.cache;if(n.has(i))return n.get(i);var o=s.apply(this,r);return e.cache=n.set(i,o)||n,o};return e.cache=new(Th.Cache||rr),e}Th.Cache=rr;var kw=500;function _w(s){var t=Th(s,function(r){return e.size===kw&&e.clear(),r}),e=t.cache;return t}var Cw=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Rw=/\\(\\)?/g,Iw=_w(function(s){var t=[];return s.charCodeAt(0)===46&&t.push(""),s.replace(Cw,function(e,r,i,n){t.push(i?n.replace(Rw,"$1"):r||e)}),t});const Aw=Iw;function Mw(s){return s==null?"":vg(s)}function Lg(s,t){return Ft(s)?s:Sh(s,t)?[s]:Aw(Mw(s))}var Ow=1/0;function Wd(s){if(typeof s=="string"||Ud(s))return s;var t=s+"";return t=="0"&&1/s==-Ow?"-0":t}function Vg(s,t){t=Lg(t,s);for(var e=0,r=t.length;s!=null&&e<r;)s=s[Wd(t[e++])];return e&&e==r?s:void 0}function Dw(s,t,e){var r=s==null?void 0:Vg(s,t);return r===void 0?e:r}function xg(s,t){for(var e=-1,r=t.length,i=s.length;++e<r;)s[i+e]=t[e];return s}var Nw=Dg(Object.getPrototypeOf,Object);const yh=Nw;var Lw="[object Object]",Vw=Function.prototype,xw=Object.prototype,$g=Vw.toString,$w=xw.hasOwnProperty,Uw=$g.call(Object);function Bw(s){if(!Os(s)||Ri(s)!=Lw)return!1;var t=yh(s);if(t===null)return!0;var e=$w.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&$g.call(e)==Uw}function Fw(){this.__data__=new sr,this.size=0}function Hw(s){var t=this.__data__,e=t.delete(s);return this.size=t.size,e}function qw(s){return this.__data__.get(s)}function jw(s){return this.__data__.has(s)}var Gw=200;function Ww(s,t){var e=this.__data__;if(e instanceof sr){var r=e.__data__;if(!go||r.length<Gw-1)return r.push([s,t]),this.size=++e.size,this;e=this.__data__=new rr(r)}return e.set(s,t),this.size=e.size,this}function vs(s){var t=this.__data__=new sr(s);this.size=t.size}vs.prototype.clear=Fw,vs.prototype.delete=Hw,vs.prototype.get=qw,vs.prototype.has=jw,vs.prototype.set=Ww;function Jw(s,t){return s&&co(t,qd(t),s)}function Kw(s,t){return s&&co(t,po(t),s)}var Ug=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Bg=Ug&&typeof module=="object"&&module&&!module.nodeType&&module,zw=Bg&&Bg.exports===Ug,Fg=zw?fs.Buffer:void 0,Hg=Fg?Fg.allocUnsafe:void 0;function qg(s,t){if(t)return s.slice();var e=s.length,r=Hg?Hg(e):new s.constructor(e);return s.copy(r),r}function Yw(s,t){for(var e=-1,r=s==null?0:s.length,i=0,n=[];++e<r;){var o=s[e];t(o,e,s)&&(n[i++]=o)}return n}function jg(){return[]}var Qw=Object.prototype,Xw=Qw.propertyIsEnumerable,Gg=Object.getOwnPropertySymbols,Zw=Gg?function(s){return s==null?[]:(s=Object(s),Yw(Gg(s),function(t){return Xw.call(s,t)}))}:jg;const Eh=Zw;function eP(s,t){return co(s,Eh(s),t)}var tP=Object.getOwnPropertySymbols,sP=tP?function(s){for(var t=[];s;)xg(t,Eh(s)),s=yh(s);return t}:jg;const Wg=sP;function rP(s,t){return co(s,Wg(s),t)}function Jg(s,t,e){var r=t(s);return Ft(s)?r:xg(r,e(s))}function bh(s){return Jg(s,qd,Eh)}function iP(s){return Jg(s,po,Wg)}var nP=Ai(fs,"DataView");const wh=nP;var aP=Ai(fs,"Promise");const Ph=aP;var oP=Ai(fs,"Set");const qn=oP;var Kg="[object Map]",cP="[object Object]",zg="[object Promise]",Yg="[object Set]",Qg="[object WeakMap]",Xg="[object DataView]",dP=Ii(wh),lP=Ii(go),uP=Ii(Ph),hP=Ii(qn),pP=Ii(hh),Oi=Ri;(wh&&Oi(new wh(new ArrayBuffer(1)))!=Xg||go&&Oi(new go)!=Kg||Ph&&Oi(Ph.resolve())!=zg||qn&&Oi(new qn)!=Yg||hh&&Oi(new hh)!=Qg)&&(Oi=function(s){var t=Ri(s),e=t==cP?s.constructor:void 0,r=e?Ii(e):"";if(r)switch(r){case dP:return Xg;case lP:return Kg;case uP:return zg;case hP:return Yg;case pP:return Qg}return t});const jn=Oi;var mP=Object.prototype,gP=mP.hasOwnProperty;function fP(s){var t=s.length,e=new s.constructor(t);return t&&typeof s[0]=="string"&&gP.call(s,"index")&&(e.index=s.index,e.input=s.input),e}var vP=fs.Uint8Array;const Jd=vP;function kh(s){var t=new s.constructor(s.byteLength);return new Jd(t).set(new Jd(s)),t}function SP(s,t){var e=t?kh(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.byteLength)}var TP=/\w*$/;function yP(s){var t=new s.constructor(s.source,TP.exec(s));return t.lastIndex=s.lastIndex,t}var Zg=Ms?Ms.prototype:void 0,ef=Zg?Zg.valueOf:void 0;function EP(s){return ef?Object(ef.call(s)):{}}function tf(s,t){var e=t?kh(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.length)}var bP="[object Boolean]",wP="[object Date]",PP="[object Map]",kP="[object Number]",_P="[object RegExp]",CP="[object Set]",RP="[object String]",IP="[object Symbol]",AP="[object ArrayBuffer]",MP="[object DataView]",OP="[object Float32Array]",DP="[object Float64Array]",NP="[object Int8Array]",LP="[object Int16Array]",VP="[object Int32Array]",xP="[object Uint8Array]",$P="[object Uint8ClampedArray]",UP="[object Uint16Array]",BP="[object Uint32Array]";function FP(s,t,e){var r=s.constructor;switch(t){case AP:return kh(s);case bP:case wP:return new r(+s);case MP:return SP(s,e);case OP:case DP:case NP:case LP:case VP:case xP:case $P:case UP:case BP:return tf(s,e);case PP:return new r;case kP:case RP:return new r(s);case _P:return yP(s);case CP:return new r;case IP:return EP(s)}}function sf(s){return typeof s.constructor=="function"&&!Fd(s)?IE(yh(s)):{}}var HP="[object Map]";function qP(s){return Os(s)&&jn(s)==HP}var rf=Hn&&Hn.isMap,jP=rf?fh(rf):qP;const GP=jP;var WP="[object Set]";function JP(s){return Os(s)&&jn(s)==WP}var nf=Hn&&Hn.isSet,KP=nf?fh(nf):JP;const zP=KP;var YP=1,QP=2,XP=4,af="[object Arguments]",ZP="[object Array]",ek="[object Boolean]",tk="[object Date]",sk="[object Error]",of="[object Function]",rk="[object GeneratorFunction]",ik="[object Map]",nk="[object Number]",cf="[object Object]",ak="[object RegExp]",ok="[object Set]",ck="[object String]",dk="[object Symbol]",lk="[object WeakMap]",uk="[object ArrayBuffer]",hk="[object DataView]",pk="[object Float32Array]",mk="[object Float64Array]",gk="[object Int8Array]",fk="[object Int16Array]",vk="[object Int32Array]",Sk="[object Uint8Array]",Tk="[object Uint8ClampedArray]",yk="[object Uint16Array]",Ek="[object Uint32Array]",ye={};ye[af]=ye[ZP]=ye[uk]=ye[hk]=ye[ek]=ye[tk]=ye[pk]=ye[mk]=ye[gk]=ye[fk]=ye[vk]=ye[ik]=ye[nk]=ye[cf]=ye[ak]=ye[ok]=ye[ck]=ye[dk]=ye[Sk]=ye[Tk]=ye[yk]=ye[Ek]=!0,ye[sk]=ye[of]=ye[lk]=!1;function fo(s,t,e,r,i,n){var o,c=t&YP,d=t&QP,l=t&XP;if(e&&(o=i?e(s,r,i,n):e(s)),o!==void 0)return o;if(!ss(s))return s;var u=Ft(s);if(u){if(o=fP(s),!c)return bg(s,o)}else{var h=jn(s),g=h==of||h==rk;if(Fn(s))return qg(s,c);if(h==cf||h==af||g&&!i){if(o=d||g?{}:sf(s),!c)return d?rP(s,Kw(o,s)):eP(s,Jw(o,s))}else{if(!ye[h])return i?s:{};o=FP(s,h,c)}}n||(n=new vs);var v=n.get(s);if(v)return v;n.set(s,o),zP(s)?s.forEach(function(I){o.add(fo(I,t,e,I,s,n))}):GP(s)&&s.forEach(function(I,D){o.set(D,fo(I,t,e,D,s,n))});var y=l?d?iP:bh:d?po:qd,k=u?void 0:y(s);return FE(k||s,function(I,D){k&&(D=I,I=s[D]),wg(o,D,fo(I,t,e,D,s,n))}),o}var bk=4;function wk(s){return fo(s,bk)}var Pk=1,kk=4;function _h(s){return fo(s,Pk|kk)}var _k="__lodash_hash_undefined__";function Ck(s){return this.__data__.set(s,_k),this}function Rk(s){return this.__data__.has(s)}function vo(s){var t=-1,e=s==null?0:s.length;for(this.__data__=new rr;++t<e;)this.add(s[t])}vo.prototype.add=vo.prototype.push=Ck,vo.prototype.has=Rk;function Ik(s,t){for(var e=-1,r=s==null?0:s.length;++e<r;)if(t(s[e],e,s))return!0;return!1}function df(s,t){return s.has(t)}var Ak=1,Mk=2;function lf(s,t,e,r,i,n){var o=e&Ak,c=s.length,d=t.length;if(c!=d&&!(o&&d>c))return!1;var l=n.get(s),u=n.get(t);if(l&&u)return l==t&&u==s;var h=-1,g=!0,v=e&Mk?new vo:void 0;for(n.set(s,t),n.set(t,s);++h<c;){var y=s[h],k=t[h];if(r)var I=o?r(k,y,h,t,s,n):r(y,k,h,s,t,n);if(I!==void 0){if(I)continue;g=!1;break}if(v){if(!Ik(t,function(D,N){if(!df(v,N)&&(y===D||i(y,D,e,r,n)))return v.push(N)})){g=!1;break}}else if(!(y===k||i(y,k,e,r,n))){g=!1;break}}return n.delete(s),n.delete(t),g}function Ok(s){var t=-1,e=Array(s.size);return s.forEach(function(r,i){e[++t]=[i,r]}),e}function Ch(s){var t=-1,e=Array(s.size);return s.forEach(function(r){e[++t]=r}),e}var Dk=1,Nk=2,Lk="[object Boolean]",Vk="[object Date]",xk="[object Error]",$k="[object Map]",Uk="[object Number]",Bk="[object RegExp]",Fk="[object Set]",Hk="[object String]",qk="[object Symbol]",jk="[object ArrayBuffer]",Gk="[object DataView]",uf=Ms?Ms.prototype:void 0,Rh=uf?uf.valueOf:void 0;function Wk(s,t,e,r,i,n,o){switch(e){case Gk:if(s.byteLength!=t.byteLength||s.byteOffset!=t.byteOffset)return!1;s=s.buffer,t=t.buffer;case jk:return!(s.byteLength!=t.byteLength||!n(new Jd(s),new Jd(t)));case Lk:case Vk:case Uk:return oo(+s,+t);case xk:return s.name==t.name&&s.message==t.message;case Bk:case Hk:return s==t+"";case $k:var c=Ok;case Fk:var d=r&Dk;if(c||(c=Ch),s.size!=t.size&&!d)return!1;var l=o.get(s);if(l)return l==t;r|=Nk,o.set(s,t);var u=lf(c(s),c(t),r,i,n,o);return o.delete(s),u;case qk:if(Rh)return Rh.call(s)==Rh.call(t)}return!1}var Jk=1,Kk=Object.prototype,zk=Kk.hasOwnProperty;function Yk(s,t,e,r,i,n){var o=e&Jk,c=bh(s),d=c.length,l=bh(t),u=l.length;if(d!=u&&!o)return!1;for(var h=d;h--;){var g=c[h];if(!(o?g in t:zk.call(t,g)))return!1}var v=n.get(s),y=n.get(t);if(v&&y)return v==t&&y==s;var k=!0;n.set(s,t),n.set(t,s);for(var I=o;++h<d;){g=c[h];var D=s[g],N=t[g];if(r)var B=o?r(N,D,g,t,s,n):r(D,N,g,s,t,n);if(!(B===void 0?D===N||i(D,N,e,r,n):B)){k=!1;break}I||(I=g=="constructor")}if(k&&!I){var U=s.constructor,j=t.constructor;U!=j&&"constructor"in s&&"constructor"in t&&!(typeof U=="function"&&U instanceof U&&typeof j=="function"&&j instanceof j)&&(k=!1)}return n.delete(s),n.delete(t),k}var Qk=1,hf="[object Arguments]",pf="[object Array]",Kd="[object Object]",Xk=Object.prototype,mf=Xk.hasOwnProperty;function Zk(s,t,e,r,i,n){var o=Ft(s),c=Ft(t),d=o?pf:jn(s),l=c?pf:jn(t);d=d==hf?Kd:d,l=l==hf?Kd:l;var u=d==Kd,h=l==Kd,g=d==l;if(g&&Fn(s)){if(!Fn(t))return!1;o=!0,u=!1}if(g&&!u)return n||(n=new vs),o||Hd(s)?lf(s,t,e,r,i,n):Wk(s,t,d,e,r,i,n);if(!(e&Qk)){var v=u&&mf.call(s,"__wrapped__"),y=h&&mf.call(t,"__wrapped__");if(v||y){var k=v?s.value():s,I=y?t.value():t;return n||(n=new vs),i(k,I,e,r,n)}}return g?(n||(n=new vs),Yk(s,t,e,r,i,n)):!1}function zd(s,t,e,r,i){return s===t?!0:s==null||t==null||!Os(s)&&!Os(t)?s!==s&&t!==t:Zk(s,t,e,r,zd,i)}var e_=1,t_=2;function s_(s,t,e,r){var i=e.length,n=i,o=!r;if(s==null)return!n;for(s=Object(s);i--;){var c=e[i];if(o&&c[2]?c[1]!==s[c[0]]:!(c[0]in s))return!1}for(;++i<n;){c=e[i];var d=c[0],l=s[d],u=c[1];if(o&&c[2]){if(l===void 0&&!(d in s))return!1}else{var h=new vs;if(r)var g=r(l,u,d,s,t,h);if(!(g===void 0?zd(u,l,e_|t_,r,h):g))return!1}}return!0}function gf(s){return s===s&&!ss(s)}function r_(s){for(var t=qd(s),e=t.length;e--;){var r=t[e],i=s[r];t[e]=[r,i,gf(i)]}return t}function ff(s,t){return function(e){return e==null?!1:e[s]===t&&(t!==void 0||s in Object(e))}}function i_(s){var t=r_(s);return t.length==1&&t[0][2]?ff(t[0][0],t[0][1]):function(e){return e===s||s_(e,s,t)}}function n_(s,t){return s!=null&&t in Object(s)}function a_(s,t,e){t=Lg(t,s);for(var r=-1,i=t.length,n=!1;++r<i;){var o=Wd(t[r]);if(!(n=s!=null&&e(s,o)))break;s=s[o]}return n||++r!=i?n:(i=s==null?0:s.length,!!i&&gh(i)&&ph(o,i)&&(Ft(s)||uo(s)))}function o_(s,t){return s!=null&&a_(s,t,n_)}var c_=1,d_=2;function l_(s,t){return Sh(s)&&gf(t)?ff(Wd(s),t):function(e){var r=Dw(e,s);return r===void 0&&r===t?o_(e,s):zd(t,r,c_|d_)}}function u_(s){return function(t){return t==null?void 0:t[s]}}function h_(s){return function(t){return Vg(t,s)}}function p_(s){return Sh(s)?u_(Wd(s)):h_(s)}function m_(s){return typeof s=="function"?s:s==null?dh:typeof s=="object"?Ft(s)?l_(s[0],s[1]):i_(s):p_(s)}function g_(s){return function(t,e,r){for(var i=-1,n=Object(t),o=r(t),c=o.length;c--;){var d=o[s?c:++i];if(e(n[d],d,n)===!1)break}return t}}var f_=g_();const v_=f_;var S_=function(){return fs.Date.now()};const Ih=S_;var T_="Expected a function",y_=Math.max,E_=Math.min;function Ah(s,t,e){var r,i,n,o,c,d,l=0,u=!1,h=!1,g=!0;if(typeof s!="function")throw new TypeError(T_);t=Tg(t)||0,ss(e)&&(u=!!e.leading,h="maxWait"in e,n=h?y_(Tg(e.maxWait)||0,t):n,g="trailing"in e?!!e.trailing:g);function v(Z){var re=r,F=i;return r=i=void 0,l=Z,o=s.apply(F,re),o}function y(Z){return l=Z,c=setTimeout(D,t),u?v(Z):o}function k(Z){var re=Z-d,F=Z-l,ee=t-re;return h?E_(ee,n-F):ee}function I(Z){var re=Z-d,F=Z-l;return d===void 0||re>=t||re<0||h&&F>=n}function D(){var Z=Ih();if(I(Z))return N(Z);c=setTimeout(D,k(Z))}function N(Z){return c=void 0,g&&r?v(Z):(r=i=void 0,o)}function B(){c!==void 0&&clearTimeout(c),l=0,r=d=i=c=void 0}function U(){return c===void 0?o:N(Ih())}function j(){var Z=Ih(),re=I(Z);if(r=arguments,i=this,d=Z,re){if(c===void 0)return y(d);if(h)return clearTimeout(c),c=setTimeout(D,t),v(d)}return c===void 0&&(c=setTimeout(D,t)),o}return j.cancel=B,j.flush=U,j}function Mh(s,t,e){(e!==void 0&&!oo(s[t],e)||e===void 0&&!(t in s))&&mh(s,t,e)}function b_(s){return Os(s)&&lo(s)}function Oh(s,t){if(!(t==="constructor"&&typeof s[t]=="function")&&t!="__proto__")return s[t]}function w_(s){return co(s,po(s))}function P_(s,t,e,r,i,n,o){var c=Oh(s,e),d=Oh(t,e),l=o.get(d);if(l){Mh(s,e,l);return}var u=n?n(c,d,e+"",s,t,o):void 0,h=u===void 0;if(h){var g=Ft(d),v=!g&&Fn(d),y=!g&&!v&&Hd(d);u=d,g||v||y?Ft(c)?u=c:b_(c)?u=bg(c):v?(h=!1,u=qg(d,!0)):y?(h=!1,u=tf(d,!0)):u=[]:Bw(d)||uo(d)?(u=c,uo(c)?u=w_(c):(!ss(c)||lh(c))&&(u=sf(d))):h=!1}h&&(o.set(d,u),i(u,d,r,n,o),o.delete(d)),Mh(s,e,u)}function vf(s,t,e,r,i){s!==t&&v_(t,function(n,o){if(i||(i=new vs),ss(n))P_(s,t,o,e,vf,r,i);else{var c=r?r(Oh(s,o),n,o+"",s,t,i):void 0;c===void 0&&(c=n),Mh(s,o,c)}},po)}function k_(s,t,e){for(var r=-1,i=s==null?0:s.length;++r<i;)if(e(t,s[r]))return!0;return!1}var __="[object Map]",C_="[object Set]",R_=Object.prototype,I_=R_.hasOwnProperty;function A_(s){if(s==null)return!0;if(lo(s)&&(Ft(s)||typeof s=="string"||typeof s.splice=="function"||Fn(s)||Hd(s)||uo(s)))return!s.length;var t=jn(s);if(t==__||t==C_)return!s.size;if(Fd(s))return!Ng(s).length;for(var e in s)if(I_.call(s,e))return!1;return!0}function M_(s,t){return zd(s,t)}var O_=tb(function(s,t,e){vf(s,t,e)});const Ur=O_;var D_=1/0,N_=qn&&1/Ch(new qn([,-0]))[1]==D_?function(s){return new qn(s)}:ME;const L_=N_;var V_=200;function x_(s,t,e){var r=-1,i=WE,n=s.length,o=!0,c=[],d=c;if(e)o=!1,i=k_;else if(n>=V_){var l=t?null:L_(s);if(l)return Ch(l);o=!1,i=df,d=new vo}else d=t?[]:c;e:for(;++r<n;){var u=s[r],h=t?t(u):u;if(u=e||u!==0?u:0,o&&h===h){for(var g=d.length;g--;)if(d[g]===h)continue e;t&&d.push(h),c.push(u)}else i(d,h,e)||(d!==c&&d.push(h),c.push(u))}return c}function $_(s,t){return s&&s.length?x_(s,m_(t)):[]}function Yd(s){const t={};return typeof(s==null?void 0:s.code)=="number"&&(t.code=s.code),typeof(s==null?void 0:s.code)=="string"&&(t.code=s.code.substring(0,100)),typeof(s==null?void 0:s.name)=="string"&&(t.name=s.name.substring(0,500)),typeof(s==null?void 0:s.message)=="string"&&(t.message=s.message.substring(0,500)),typeof(s==null?void 0:s.reason)=="string"&&(t.reason=s.reason.substring(0,500)),typeof(s==null?void 0:s.stack)=="string"&&(t.stack=s.stack.substring(0,500)),t}const U_={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},Sf={STAGING:"staging",PROD:"prod"},B_={pip:!0,poll:!0,chat:!0,stage:!0,theme:!0,plugin:!0,tracing:!0,internals:!0,recording:!0,livestream:!0,participant:!0,connectedMeetings:!0,devTools:{logs:!1}};function So(s,t){const e=s.getValue("overrides");return e&&e[t]?e[t]:!1}function F_({baseURI:s}){return s.includes("staging.realtime")?Sf.STAGING:Sf.PROD}function Tf({servicePrefix:s,baseURI:t}){return`${s}.${t}`}function Dh({servicePrefix:s,baseURI:t}){const e=s==="ws"?"wss":"https",r=Tf({servicePrefix:"api",baseURI:t});return`${e}://${r}/${s}`}function H_(s){const t=s.getValue("baseURI");return{daCollector:Dh({servicePrefix:"telemetry",baseURI:t}).replace("https://","")}}const q_='<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>',j_='<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>',Qd=s=>{if(!s)return;if(!s.startsWith("<svg"))return new Promise(n=>{n(s)});const e=new Blob([s],{type:"image/svg+xml"}),r=new Image,i=window.URL.createObjectURL(e);return new Promise((n,o)=>{r.onload=()=>{n(r),window.URL.revokeObjectURL(i)},r.onerror=()=>{o(),window.URL.revokeObjectURL(i)},r.src=i})},Di={logs:"https://api.realtime.cloudflare.com/logs",mock:{url:"https://api.realtime.cloudflare.com/mock",domain:"mock.realtime.cloudflare.com",app:"https://examples.realtime.cloudflare.com/meeting",stagingApp:"https://examples.staging.realtime.cloudflare.com/meeting"},apiBase:{prod:"https://api.realtime.cloudflare.com",staging:"https://api.staging.realtime.cloudflare.com",prodAlternate:"https://api.realtime.cloudflare.com"},baseURI:{prod:"realtime.cloudflare.com",staging:"staging.realtime.cloudflare.com"}},G_=/\b(?:1[7-9](?:\.\d+)?|[2-9]\d(?:\.\d+)?|[1-9]\d{2,}(?:\.\d+)?)\b/,Nh="__rtk_plugins__",W_=[Nh];function yf(s){var r,i,n;const t=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((r=window.location.host)==null?void 0:r.includes(Di.baseURI.staging)),e=!!((n=(i=s==null?void 0:s.getValue("modules"))==null?void 0:i.devTools)!=null&&n.logs);return t||e}function J_(s,t){var r;const e=(r=s==null?void 0:s.getValue("telemetry"))==null?void 0:r.logLevel;if(e==="off")return!1;if(e!=="all"){const i=["debug","log","info","warn","error"],n=i.indexOf(t.toLowerCase()),o=i.indexOf(e);if(n<o)return!1}return!0}function Ef(s,t,e={}){return Object.getOwnPropertyNames(s).forEach(r=>{var n;if([null,void 0,NaN].includes(s[r])||t&&(((n=t.match(/\./g))==null?void 0:n.length)||0)>=10)return;const i=t?`${t}.${r}`:r;typeof s[r]=="object"?Ef(s[r],i,e):["number","string","boolean"].includes(typeof s[r])&&(e[i]=s[r])}),e}function bf(s,t,e={},r=""){const i={};try{const n=JSON.stringify(e),o=JSON.parse(n),c=Ef(o,r),d=JSON.stringify(c);if(!(t==null?void 0:t.startsWith("[SDP]"))&&d.length>5e3){const u=`Log named: "${t}" is trying to log an flattened object of size
|
|
10
|
+
${d.length} chars that is beyond permitted limit of 5000 chars. Please optimize.`;throw yf(s)&&console.error(u,{log:e,flattened:d}),new Error(u)}return JSON.parse(d)}catch(n){const o=Yd(n);i[`${r}.error.message`]=o.message||"",i[`${r}.error.stack`]=o.stack||"",i[`${r}.error.reason`]=o.reason||"",i[`${r}.error.source`]="safelyFlattenObjForOpenTelemetry"}return i}class E{constructor(){p(this,"logsCache",[]);p(this,"logsProcessorTimer");p(this,"compressionSupported",null);p(this,"tracingEnabled",!0);p(this,"initialized",!1);p(this,"logLevel","log");p(this,"logsProcessingInterval",7e3);p(this,"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"]);p(this,"meetingMetadata",{})}isCompressionSupported(){if(this.compressionSupported===null)try{this.compressionSupported=typeof CompressionStream!="undefined"&&typeof Blob!="undefined"&&typeof Blob.prototype.stream=="function"&&typeof Response!="undefined"}catch(t){this.compressionSupported=!1,this.addLogInCurrentSpan("warn","Compression feature detection failed, using uncompressed logs",{error:t})}return this.compressionSupported}get logsEndpoint(){const t=Br.getContext(this.meetingMetadata.peerId);return Dh({servicePrefix:"logs",baseURI:t.getValue("baseURI")})}get logsBatchSize(){return this.isCompressionSupported()?50:25}resetPeerId(t){this.meetingMetadata.peerId=t}setUiKitMetadata({sdkVersion:t,sdkName:e}){this.meetingMetadata.uikit={sdkName:e!=null?e:"unknown",sdkVersion:t!=null?t:"unknown"}}init(t,e,r,i){this.tracingEnabled=!0,this.initialized=!1,i&&(this.logLevel=i),this.logsCache=[];const n=t.getValue("peerId");this.meetingMetadata=e,this.tracingEnabled=r,this.meetingMetadata.peerId=n,this.meetingMetadata.sdkVersion=t.getValue("sdkVersion"),this.meetingMetadata.uikit={sdkName:"unknown",sdkVersion:"unknown"};const{RNDeviceInfoImpl:o}=navigator;this.meetingMetadata.deviceInfo=navigator.isReactNative?o==null?void 0:o.getDeviceInfo():Pe.getDeviceInfo(),this.meetingMetadata.visitedUrl=!navigator.isReactNative&&typeof window!="undefined"&&window.location.href,this.logsProcessorTimer=setInterval(()=>this.processCachedLogs().catch(()=>{}),this.logsProcessingInterval),r&&(this.initialized=!0)}static trace(t,e=void 0){return(r,i,n)=>{const o=n.value;return n.value=function(...d){const l=this==null?void 0:this.telemetry;if(!l||!l.initialized||navigator.isReactNative||!l.tracingEnabled)return o.apply(this,d);l.addLogInCurrentSpan("info",t,e);const u=performance.now(),h=o.apply(this,d);return Promise.resolve(h).then(()=>{const g=performance.now();g-u>10&&l.addLogInCurrentSpan("info",`${t}_timing`,{execTime:g-u})}).catch(()=>{const g=performance.now();l.addLogInCurrentSpan("info",`${t}_timing`,{execTime:g-u})}),h},n}}injectContext(t){var i;const e=Ci().replace(/-/g,"").substring(0,16),r=(i=this.meetingMetadata.peerId)==null?void 0:i.replace(/-/g,"");t.TRACEPARENT=`00-${r}-${e}-01`}addLogInCurrentSpan(t,e,r={},i=!1){r!=null&&r.error&&Object.assign(r,{error:Yd(r.error)});const n=Br.getContext(this.meetingMetadata.peerId);if(yf(n)&&(A_(r)?console[t]("InternalLogs:: ",t,e):console[t]("InternalLogs:: ",t,e,r)),!!J_(n,t))try{const c=bf(n,e,r,"metadata"),d=new Date,l={message:e,level:t,...c,loggedAt:d.toISOString(),loggedAtTzOffset:d.getTimezoneOffset()};i?this.sendOtelLogsToNewRelic([l],{isInDestructionMode:!1}).catch(()=>{}):this.logsCache.push(l)}catch(c){this.addLogInCurrentSpan("error","opentelemetry::addLogInCurrentSpan_failed",{error:Yd(c)})}}async sendOtelLogsToNewRelic(t,{isInDestructionMode:e=!1}={isInDestructionMode:!1}){const r=new AbortController,i=setTimeout(()=>r.abort("Logs request timed out after 8 seconds"),8e3);try{const n=Br.getContext(this.meetingMetadata.peerId),o=JSON.stringify({meetingMetadata:bf(n,"sendOtelLogsToNewRelic",this.meetingMetadata,"meetingMetadata"),serviceName:n.getValue("sdkName"),logs:t});let c;const d={Authorization:`Bearer ${n.getValue("authToken")}`};if(this.isCompressionSupported()){const l=new Blob([o]).stream().pipeThrough(new CompressionStream("gzip"));c=await new Response(l).arrayBuffer(),d["Content-Type"]="application/gzip",d["Content-Encoding"]="gzip"}else c=o,d["Content-Type"]="application/json";await fetch(this.logsEndpoint,{method:"POST",headers:d,body:c,signal:r.signal,keepalive:!!e})}catch(n){e||(this.addLogInCurrentSpan("error","opentelemetry::sendOtelLogToNewRelic_failed",{error:Yd(n)}),this.logsCache.push(...t))}finally{clearTimeout(i)}}async processCachedLogs({isInDestructionMode:t=!1}={isInDestructionMode:!1}){const e=this.logsCache.splice(0,this.logsBatchSize);e!=null&&e.length&&await this.sendOtelLogsToNewRelic(e,{isInDestructionMode:t})}async destruct(){for(clearInterval(this.logsProcessorTimer);this.logsCache.length;)await this.processCachedLogs({isInDestructionMode:!0})}}function K_(s){const t={...s},e=new Map,r=(l,u)=>(e.has(l)||e.set(l,new Set),e.get(l).add(u),()=>{var h;return(h=e.get(l))==null?void 0:h.delete(u)}),i=(l,u)=>{var h;(h=e.get(l))==null||h.delete(u)},n=l=>{var u;(u=e.get(l))==null||u.forEach(h=>{try{h(t[l])}catch(g){}})};return{subscribe:r,unsubscribe:i,notify:n,setValue:(l,u,h=!0)=>{t[l]=u,h&&n(l)},getValue:l=>t[l],getAllValues:()=>t}}class z_{constructor(){p(this,"contexts",new Map);p(this,"mostRecentPeerId",null)}createContext(t,e){if(this.contexts.has(t))return this.contexts.get(t);const r=new E,i=new $y;this.contexts.set(t,K_(e)),this.contexts.get(t).setValue("peerSessionStore",new Uy(i));const n=new lg;return n.setMaxListeners(50),this.contexts.get(t).setValue("logger",i),this.contexts.get(t).setValue("telemetry",r),this.contexts.get(t).setValue("callstats",n),this.mostRecentPeerId=t,this.contexts.get(t)}remapContext(t,e){const r=e.getValue("peerId");r!==t&&(e.setValue("peerId",t),this.mostRecentPeerId=t,this.contexts.set(t,e),this.contexts.delete(r))}getContext(t){return this.contexts.get(t)}getMostRecentPeerId(){return this.mostRecentPeerId}}const Br=new z_,Y_={"00":"Client","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"},Xd={"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","0014":"Failed to establish media connection.","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","0600":"Internal exception","0601":"Permission denied.","0602":"Auth token not set for plugin","0603":"Iframe was not provided","0604":"Active plugins store is not available yet","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(Xd).forEach(s=>{Xd[s]=`{${Y_[s.slice(0,2)]}} ${Xd[s]}`});class C extends Error{constructor(e,r,i=void 0,n=!1,o=void 0){super(e);p(this,"code");p(this,"reason");this.code=r,this.name="ClientError",this.reason=o;const c=this.code?`[ERR${this.code}]`:"[ERR]",d=this.code?Xd[this.code]:"";this.message=`${c}: ${d}
|
|
11
|
+
${this.message}`;try{let l=n&&!!i;r&&r.endsWith("00")&&i&&(l=!0),l&&i.error("ClientError",{error:{message:this.message,name:this.name,code:r}});const u=Br.getContext(Br.getMostRecentPeerId());if(u){const h=u.getValue("onError");try{h(this)}catch(g){}}typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("ClientError",{detail:this}))}catch(l){}}}function Zd(s,t,e,r){if(r instanceof C)throw r;if(r instanceof t){const i=new C(r.message,e);throw i.stack=r.stack,i}else throw r}function wf(s,t,e){if(!s.value){const i=s.get,n=s.set;return i&&(s.get=function(){try{return i.apply(this)}catch(o){Zd(this,t,e,o)}}),n&&(s.set=function(o){try{return n.apply(this,[o])}catch(c){Zd(this,t,e,c)}}),s}const r=s.value;return s.value=function(...i){try{const n=r.apply(this,i);return n&&n instanceof Promise?n.catch(o=>{Zd(this,t,e,o)}):n}catch(n){Zd(this,t,e,n)}},s}function Q_(s,t){return(e,r,i)=>{if(i)return wf(i,s,t);for(const n of Reflect.ownKeys(e.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(e.prototype,n);(o.value instanceof Function||o.get instanceof Function||o.set instanceof Function)&&Object.defineProperty(e.prototype,n,wf(o,s,t))}}}const pt=s=>Q_(Error,s);var Ss=(s=>(s.GroupCall="GROUP_CALL",s.Webinar="WEBINAR",s.AudioRoom="AUDIO_ROOM",s.Livestream="LIVESTREAM",s.Chat="CHAT",s))(Ss||{}),G=(s=>(s.Allowed="ALLOWED",s.NotAllowed="NOT_ALLOWED",s.CanRequest="CAN_REQUEST",s))(G||{});typeof process!="undefined"&&(US=process==null?void 0:process.env)!=null&&US.FLAGSMITH_ENVIRONMENT_KEY&&process.env.FLAGSMITH_ENVIRONMENT_KEY;var Pf=[-2,-1,0,1,2],X_=[0,1,2,3,4];function Z_(s){s=s.trim();let t="0",e="0",r="0";return s.length==4?(t=`0x${s[1]}${s[1]}`,e=`0x${s[2]}${s[2]}`,r=`0x${s[3]}${s[3]}`):s.length>6&&(t=`0x${s[1]}${s[2]}`,e=`0x${s[3]}${s[4]}`,r=`0x${s[5]}${s[6]}`),[+t,+e,+r]}var eC=(s,t,e)=>{let r,i,n;if(t==0)r=i=n=e;else{const o=(l,u,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?l+(u-l)*6*h:h<.5?u:h<.6666666666666666?l+(u-l)*(.6666666666666666-h)*6:l),c=e<.5?e*(1+t):e+t-e*t,d=2*e-c;r=o(d,c,s+1/3),i=o(d,c,s),n=o(d,c,s-1/3)}return[Math.round(r*255),Math.round(i*255),Math.round(n*255)]},tC=(s,t,e)=>{s/=255,t/=255,e/=255;const r=Math.max(s,t,e),i=Math.min(s,t,e);let n,o;const c=(r+i)/2;if(r==i)n=o=0;else{const d=r-i;switch(o=c>.5?d/(2-r-i):d/(r+i),r){case s:n=(t-e)/d+(t<e?6:0);break;case t:n=(e-s)/d+2;break;case e:n=(s-t)/d+4;break}n/=6}return[n,o,c]},sC=(s,t,e)=>{const r=i=>i.toString(16).padStart(2,"0");return`#${r(s)}${r(t)}${r(e)}`},kf=(s,t=Pf,e=.4)=>{const r=[],[i,n,o]=Z_(s),[c,d,l]=tC(i,n,o),u=Math.round(l*100);u>70?e=.8:u>60?e=.9:u<10?e=.075:u<42&&(e=.3);const h=t.findIndex(I=>I===0);if(h===-1)throw new Error("Invalid reducer provided, it must contain atleast one zero");const g=5-h,v=h+1,y=(100-u)/g,k=u/v;for(const I of t){let D;I<0?D=u+I*k*e:I>0?D=u+I*y*e:D=u;const[N,B,U]=eC(c,d,D/100);r.push(sC(N,B,U))}return r},_f={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"}},rC=s=>{const[t,e,r,i,n]=kf(s,Pf);return{300:t,400:e,500:r,600:i,700:n}},iC=s=>{if(s==="#FFFFFF")return _f.light.background;if(s==="#000000")return _f.dark.background;const[t,e,r,i,n]=kf(s,X_);return{1e3:t,900:e,800:r,700:i,600:n}},nC={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:rC("#2160FD"),background:iC("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function Cf(){return _h(nC)}var aC={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:Cf(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:30,simulcast:!1},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"hybrid"};function oC(){return _h(aC)}var cC={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:Cf(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:30,simulcast:!1},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"2.0.0"};function Lh(){return _h(cC)}function dC(){Pe.isElectron()&&window.electronGetDisplayMediaSource&&(navigator.mediaDevices.getDisplayMedia=async()=>{const s=await window.electronGetDisplayMediaSource({types:["window","screen"]});let t=[];if(s&&(Array.isArray(s)?t=s:t=[s]),!(t!=null&&t.length))throw new Error("Couldn't find any media source for screen share.");let e=t.find(n=>{var o;return(o=n.id)==null?void 0:o.includes("screen")});e=e!=null?e:t[0];const r={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e.id}}};return await navigator.mediaDevices.getUserMedia(r)})}var P=(s=>(s.NEW_PRODUCER="NEW_PRODUCER",s.PRODUCER_HANDOVER="PRODUCER_HANDOVER",s.ROOM_NODE_CONNECTION_ERROR="ROOM_NODE_CONNECTION_ERROR",s.SOCKET_SERVICE_ROOM_JOINED="SOCKET_SERVICE_ROOM_JOINED",s.SOCKET_SERVICE_RECONNECTED="SOCKET_SERVICE_RECONNECTED",s.SOCKET_SERVICE_DISCONNECTED="SOCKET_SERVICE_DISCONNECTED",s.SOCKET_SERVICE_FAILED="SOCKET_SERVICE_FAILED",s.SOCKET_STATE_UPDATE="SOCKET_STATE_UPDATE",s.ROOM_NODE_RECONNECTED="ROOM_NODE_RECONNECTED",s.ROOM_NODE_DISCONNECTED="ROOM_NODE_DISCONNECTED",s.ROOM_NODE_FAILED="ROOM_NODE_FAILED",s.MEDIA_ROOM_JOIN_FAILED="MEDIA_ROOM_JOIN_FAILED",s.TRANSPORT_STATE_UPDATE="TRANSPORT_STATE_UPDATE",s.PRODUCER_SCORE_UPDATE="PRODUCER_SCORE_UPDATE",s.CONSUMER_SCORE_UPDATE="CONSUMER_SCORE_UPDATE",s.PRODUCER_STATUS_UPDATE="PRODUCER_STATUS_UPDATE",s.CONSUMER_STATUS_UPDATE="CONSUMER_STATUS_UPDATE",s.LOW_CONSUMER_SCORE="LOW_CONSUMER_SCORE",s.MEDIA_PERMISSION_ERROR="MEDIA_PERMISSION_ERROR",s.MEDIA_PERMISSION_UPDATE="MEDIA_PERMISSION_UPDATE",s.MESSAGE="websocket/message",s.ROOM_MESSAGE="websocket/room-message",s.PEER_JOINED_INTERNAL="peer/joined-internal",s.PEER_CLOSED="websocket/peer-closed",s.CONSUMER_CLOSED="websocket/consumer-closed",s.CONSUMER_PAUSED="websocket/consumer-paused",s.CONSUMER_RESUMED="websocket/consumer-resumed",s.NEW_CONSUMER_CREATED="NEW_CONSUMER_CREATED",s.PRODUCER_CLOSED="websocket/producer-closed",s.PRODUCER_SCORE="websocket/producer-score",s.CONSUMER_SCORE="websocket/consumer-score",s.PRODUCER_TOGGLE="cf/producer-toggle",s.UPDATE_ACTIVE="media/update-active",s.RESET_PRODUCER_STATE="cf/reset-producer-state",s.ROOM_STATE="sockethub/room-state",s.GET_STAGE_REQUESTS="GET_STAGE_REQUESTS",s.UPDATE_STAGE_REQUESTS="UPDATE_STAGE_REQUESTS",s.KICK_PEER="KICK_PEER",s.UPDATE_PEER_STAGE_STATUS="UPDATE_PEER_STAGE_STATUS",s.JOIN_MEDIA_ROOM="JOIN_MEDIA_ROOM",s.LEAVE_MEDIA_ROOM="LEAVE_MEDIA_ROOM",s.PIP_HANGUP="PIP_HANGUP",s.E2EE_ACTIVE_PRODUCER="E2EE_ACTIVE_PRODUCER",s.E2EE_INACTIVE_PRODUCER="E2EE_INACTIVE_PRODUCER",s.E2EE_ACTIVE_CONSUMER="E2EE_ACTIVE_CONSUMER",s.E2EE_INACTIVE_CONSUMER="E2EE_INACTIVE_CONSUMER",s.ENABLE_E2EE_CRYPTOR_ON_NEW_CONSUMER="ENABLE_E2EE_CRYPTOR_ON_NEW_CONSUMER",s.SOCKET_PEERS="SOCKET_PEERS",s.UPDATE_PERMISSIONS="UPDATE_PERMISSIONS",s.MAX_SPATIAL_LAYER_CHANGE="MAX_SPATIAL_LAYER_CHANGE",s.MUTE_SELF="MUTE_SELF",s.MUTE_SELF_VIDEO="MUTE_SELF_VIDEO",s))(P||{});const Rf=(s,t)=>!s.includes("currentColor")||!t?s:s.replace(/currentColor/g,t);function lC(s,t=2){return s.replace(/[^\u00BF-\u1FFF\u2C00-\uD7FF\w\s]/g,"").trim().split(/\s+/).slice(0,t).map(i=>i.charAt(0)).join("").toUpperCase()}const If=1080,Af=1920,uC=(s,t,e,r,i,n)=>{let o=.5,c=.5;const d=i,l=n,u=Math.min(e/d,r/l);let h=d*u,g=l*u,v,y,k,I,D=1;return h<e&&(D=e/h),Math.abs(D-1)<1e-14&&g<r&&(D=r/g),h*=D,g*=D,k=d/(h/e),I=l/(g/r),v=(d-k)*o,y=(l-I)*c,v<0&&(v=0),y<0&&(y=0),k>d&&(k=d),I>l&&(I=l),[v,y,k,I,s,t,e,r]},qp=class extends Bt{constructor(e,r,i,n){const o=e.getValue("logger");super(o);m(this,Lt,void 0);m(this,ei,void 0);m(this,gt,void 0);m(this,os,void 0);m(this,Le,{height:If,width:Af});m(this,cs,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"});m(this,Sr,void 0);m(this,je,{});m(this,Ue,void 0);m(this,ia,void 0);m(this,na,void 0);m(this,aa,void 0);m(this,Tr,void 0);m(this,oa,!1);m(this,Yl,e=>{const r=a(this,ia);if(f(this,ia,e),!r||r===e)return;const i=a(this,je)[r];i&&(delete a(this,je)[r],!a(this,je)[e]&&(a(this,je)[e]={...i,id:e}))});p(this,"cleanupEventListeners",()=>{a(this,ei).unsubscribe("stageStatus",this.handlePipMediaControls),a(this,Ue).removeListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,Ue).removeListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,Ue).removeListener("roomLeft",a(this,qo))});m(this,qo,({state:e})=>{e!=="disconnected"&&this.disable()});p(this,"enablePipMediaControls",()=>{this.mountAudioEvents(),this.mountVideoEvents()});p(this,"onSelfVideoUpdateListener",({videoEnabled:e})=>{this.updateMediaSession("CAMERA",e)});p(this,"onSelfAudioUpdateListener",({audioEnabled:e})=>{this.updateMediaSession("MIC",e)});p(this,"handlePipMediaControls",e=>{e==="ON_STAGE"?this.enablePipMediaControls():this.unmountEvents()});p(this,"eventCallback",e=>{e==="CAMERA"&&(a(this,Ue).videoEnabled?a(this,Ue).disableVideo():a(this,Ue).enableVideo(),this.emit("cameraToggled")),e==="MIC"&&(a(this,Ue).audioEnabled?a(this,Ue).disableAudio():a(this,Ue).enableAudio(),this.emit("micToggled")),e==="END"&&(a(this,ei).getValue("peerSessionStore").emit(P.PIP_HANGUP),this.cleanupEventListeners(),this.emit("hangup"),this.cleanup())});p(this,"unmountEvents",()=>{navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("togglemicrophone",void 0),navigator.mediaSession.setActionHandler("togglecamera",void 0))});p(this,"animate",()=>{if(!this.isActive&&a(this,Tr)==="active"){this.disable(!0);return}a(this,je)!==void 0&&this.paintCanvas(),a(this,Sr)!==void 0&&f(this,Sr,requestAnimationFrame(()=>this.animate()))});p(this,"disable",(e=!1)=>{f(this,Tr,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(a(this,Sr)),e!==!0&&document.body.removeChild(a(this,gt)),f(this,Sr,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()});f(this,ei,e),f(this,Tr,"idle"),f(this,Ue,r),f(this,ia,e.getValue("peerId")),a(this,ei).subscribe("peerId",a(this,Yl)),f(this,cs,{brand:r.config.designTokens.colors.brand[500],background:r.config.designTokens.colors.background[1e3],text:r.config.designTokens.colors.text,videoBackground:r.config.designTokens.colors.videoBg,textOnBrand:r.config.designTokens.colors.textOnBrand}),i&&this.setupIcon("pin",i),n&&this.setupIcon("handRaise",n)}static async _init(e,r){var o,c,d;let i,n;try{const l=(d=(c=(o=r.config)==null?void 0:o.designTokens)==null?void 0:c.colors)==null?void 0:d.textOnBrand;i=await Qd(Rf(q_,l)),n=await Qd(Rf(j_,l))}catch(l){}return new qp(e,r,i,n)}async setupIcon(e,r){switch(e){case"handRaise":f(this,aa,r);break;case"pin":f(this,na,r);break}}async overrideIcon(e,r){switch(e){case"handRaise":f(this,aa,await Qd(r));break;case"pin":f(this,na,await Qd(r));break}}constructImage(e){const r=new Image,i=new Blob([e],{type:"image/svg+xml"}),n=window.URL.createObjectURL(i);return new Promise(o=>{r.onload=()=>{o(r),window.URL.revokeObjectURL(n)},r.src=n})}createVideoContainer(){f(this,gt,document.createElement("div")),a(this,gt).style.width="0.1px",a(this,gt).style.height="0.1px",a(this,gt).style.overflow="hidden",a(this,gt).style.position="absolute",a(this,gt).style.bottom="0",a(this,gt).style.right="0",a(this,gt).style.opacity="0",a(this,gt).appendChild(a(this,os))}setupEventListeners(){a(this,ei).subscribe("stageStatus",this.handlePipMediaControls),a(this,Ue).addListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,Ue).addListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,Ue).addListener("roomLeft",a(this,qo))}createCanvas(){const e=document.createElement("canvas");e.height=a(this,Le).height,e.width=a(this,Le).width,f(this,Lt,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||a(this,Ue).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||a(this,Ue).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const r=Object.values(a(this,je)).reduce((i,n)=>(i[n.pinned?"pinned":"regular"].push(n),i),{pinned:[],regular:[]});return[...r.pinned,...r.regular]}drawEmptyTile(e,r,i,n){if(a(this,Lt)===void 0)return;const o=a(this,Lt).getContext("2d"),c=a(this,Lt).width,d=0,l=0,u=r-d*2,h=i-d*2,g=Math.floor(c/u),v=Math.floor(e/g),k=e%g*(u+d)+d,I=v*(h+d)+d,{displayText:D,image:N}=n!=null?n:{};o.fillStyle=D||N?a(this,cs).videoBackground:a(this,cs).background,o.strokeStyle=a(this,cs).brand,o.beginPath(),o.moveTo(k+l,I),o.arcTo(k+u,I,k+u,I+l,l),o.arcTo(k+u,I+h,k+u-l,I+h,l),o.arcTo(k,I+h,k,I+h-l,l),o.arcTo(k,I,k+l,I,l),o.closePath(),o.fill(),o.stroke();const B=u/6,U=u/2+k,j=h/2+I;o.save(),(D||N)&&(o.beginPath(),o.arc(U,j,B,0,Math.PI*2),o.fillStyle=a(this,cs).brand,o.fill(),N?(o.clip(),o.drawImage(N,U-B,j-B,B*2,B*2),o.restore()):D&&(o.fillStyle=a(this,cs).textOnBrand,o.font=`${B/2}px sans-serif`,o.textAlign="center",o.textBaseline="middle",o.fillText(D,U,j)),this.drawIcons(n,k,I,Math.max(u,h)))}drawIcons(e,r,i,n){const o=Math.min(Math.max(n*.15,100),200),c=o*.2,d=o*.2;let l=r+c;const u=i+c,h=g=>{const v=a(this,Lt).getContext("2d");v.save(),v.fillStyle=a(this,cs).background,v.beginPath(),v.moveTo(l+d,u),v.arcTo(l+o,u,l+o,u+d,d),v.arcTo(l+o,u+o,l+o-d,u+o,d),v.arcTo(l,u+o,l,u+o-d,d),v.arcTo(l,u,l+d,u,d),v.closePath(),v.fill(),typeof g=="string"?(v.font=`${o/1.5}px sans-serif`,v.fillStyle=a(this,cs).text,v.textAlign="center",v.textBaseline="top",v.fillText(g,o/2+l,u+c)):v.drawImage(g,l+c,u+c,o-c*2,o-c*2),l+=o+c,v.restore()};e.pinned&&h(a(this,na)),e.handRaised&&h(a(this,aa)),e.reaction&&h(e.reaction)}drawTile(e,r,i){var l,u;if(a(this,Lt)===void 0)return;const n=a(this,Lt).getContext("2d");n.fillStyle=a(this,cs).background,n.fillRect(0,0,a(this,Lt).width,a(this,Lt).height);const o=this.getSources();let c=0,d=0;for(;c<a(this,Le).height-5;){let h=0;for(;h<a(this,Le).width-5&&d<i;){if((l=o[d])!=null&&l.enabled){const g=o[d].element,[v,y,k,I,D,N,B,U]=uC(h,c,e,r,g.videoWidth,g.videoHeight);((u=g==null?void 0:g.classList)==null?void 0:u.contains("mirror"))?(n.save(),n.scale(-1,1),n.drawImage(g,v,y,k,I,-1*D,N,-1*B,U),n.restore()):n.drawImage(g,v,y,k,I,D,N,B,U),this.drawIcons(o[d],D,N,Math.max(B,U))}else this.drawEmptyTile(d,e,r,o[d]);d+=1,h+=e}c+=r}}calcGridElemSize(e){switch(e){case 0:case 1:return[a(this,Le).width,a(this,Le).height];case 2:return[Math.floor(a(this,Le).width/2),a(this,Le).height];case 3:case 4:return[Math.floor(a(this,Le).width/2),Math.floor(a(this,Le).height/2)];case 5:case 6:return[Math.floor(a(this,Le).width/3),Math.floor(a(this,Le).height/2)];case 7:case 8:case 9:return[Math.floor(a(this,Le).width/3),Math.floor(a(this,Le).height/3)];default:return[Math.floor(a(this,Le).width/3),Math.floor(a(this,Le).height/2)]}}paintCanvas(){let e=this.getSources().length;e!==1&&(e=e%2>0?e+1:e);const[r,i]=this.calcGridElemSize(e);this.drawTile(r,i,e)}isSupported(){var e;return!!window.chrome&&document.pictureInPictureEnabled&&((e=a(this,Ue).config)==null?void 0:e.viewType)!=="LIVESTREAM"}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(f(this,oa,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),a(this,gt))try{document.body.removeChild(a(this,gt))}catch(e){}this.removeAllSources(),f(this,Lt,void 0),f(this,os,void 0),f(this,Sr,void 0)}init({height:e,width:r}={}){if(!this.isSupported())throw this.logger.error("Pip.unsupported"),new Error("Picture-in-picture is not available in this environment");if(a(this,oa))return;f(this,oa,!0),this.createCanvas();const i=document.createElement("video");f(this,Le,{height:e!=null?e:If,width:r!=null?r:Af}),i.height=a(this,Le).height,i.width=a(this,Le).width,i.autoplay=!0,i.muted=!0,i.srcObject=a(this,Lt).captureStream(24),f(this,os,i),a(this,os).onloadedmetadata=()=>{try{this.emit("pipStarted"),a(this,os).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch(n){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){a(this,je)[e]!==void 0&&(a(this,je)[e].enabled=!0)}disableSource(e){a(this,je)[e]!==void 0&&(a(this,je)[e].enabled=!1)}async generateAvatar(e,r){if(!r)return;const i=new Image;try{const n=await(await fetch(r)).blob(),o=window.URL.createObjectURL(n);i.onload=()=>{this.updateSource(e,{image:i}),window.URL.revokeObjectURL(o)},i.src=o}catch(n){this.logger.error("Pip::GenerateAvatar",{error:n})}}addSource(e,r,i,n=!1,o=void 0,c=void 0,d=!1){this.logger.debug("Pip::AddSource",{pip:{id:e,handRaised:d}}),a(this,je)[e]={id:e,element:r,enabled:i,pinned:n,displayText:o?lC(o):void 0,imageUrl:c,handRaised:d},c&&this.generateAvatar(e,c)}updateSource(e,r){this.logger.info("Pip::UpdateSource",{pip:{id:e,handRaised:r.handRaised,reaction:r.reaction}});const i=a(this,je)[e];i&&(a(this,je)[e]={...i,...r})}removeSource(e){delete a(this,je)[e]}removePinnedSource(){Object.values(a(this,je)).forEach(r=>{r.pinned&&this.removeSource(r.id)})}removeAllSources(){f(this,je,{})}enable(){f(this,Tr,"activating"),this.setupEventListeners(),this.setupMediaSessionEvents(),this.updateMediaSession("CAMERA",a(this,Ue).videoEnabled),this.updateMediaSession("MIC",a(this,Ue).audioEnabled),document.body.appendChild(a(this,gt)),f(this,Sr,requestAnimationFrame(()=>this.animate())),a(this,os).onloadedmetadata=()=>{a(this,os).requestPictureInPicture().then(()=>{f(this,Tr,"active")})},a(this,os).readyState===4&&a(this,os).requestPictureInPicture().then(()=>{f(this,Tr,"active")})}};let Vh=qp;Lt=new WeakMap,ei=new WeakMap,gt=new WeakMap,os=new WeakMap,Le=new WeakMap,cs=new WeakMap,Sr=new WeakMap,je=new WeakMap,Ue=new WeakMap,ia=new WeakMap,na=new WeakMap,aa=new WeakMap,Tr=new WeakMap,oa=new WeakMap,Yl=new WeakMap,qo=new WeakMap;function xh(s){let t=typeof s;if(t=="object"){if(Array.isArray(s))return"array";if(s===null)return"null"}return t}function hC(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}let ir="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),el=[];for(let s=0;s<ir.length;s++)el[ir[s].charCodeAt(0)]=s;el["-".charCodeAt(0)]=ir.indexOf("+"),el["_".charCodeAt(0)]=ir.indexOf("/");function pC(s){let t=s.length*3/4;s[s.length-2]=="="?t-=2:s[s.length-1]=="="&&(t-=1);let e=new Uint8Array(t),r=0,i=0,n,o=0;for(let c=0;c<s.length;c++){if(n=el[s.charCodeAt(c)],n===void 0)switch(s[c]){case"=":i=0;case`
|
|
12
|
+
`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(i){case 0:o=n,i=1;break;case 1:e[r++]=o<<2|(n&48)>>4,o=n,i=2;break;case 2:e[r++]=(o&15)<<4|(n&60)>>2,o=n,i=3;break;case 3:e[r++]=(o&3)<<6|n,i=0;break}}if(i==1)throw Error("invalid base64 string.");return e.subarray(0,r)}function mC(s){let t="",e=0,r,i=0;for(let n=0;n<s.length;n++)switch(r=s[n],e){case 0:t+=ir[r>>2],i=(r&3)<<4,e=1;break;case 1:t+=ir[i|r>>4],i=(r&15)<<2,e=2;break;case 2:t+=ir[i|r>>6],t+=ir[r&63],e=0;break}return e&&(t+=ir[i],t+="=",e==1&&(t+="=")),t}var tl;(function(s){s.symbol=Symbol.for("protobuf-ts/unknown"),s.onRead=(e,r,i,n,o)=>{(t(r)?r[s.symbol]:r[s.symbol]=[]).push({no:i,wireType:n,data:o})},s.onWrite=(e,r,i)=>{for(let{no:n,wireType:o,data:c}of s.list(r))i.tag(n,o).raw(c)},s.list=(e,r)=>{if(t(e)){let i=e[s.symbol];return r?i.filter(n=>n.no==r):i}return[]},s.last=(e,r)=>s.list(e,r).slice(-1)[0];const t=e=>e&&Array.isArray(e[s.symbol])})(tl||(tl={}));var $e;(function(s){s[s.Varint=0]="Varint",s[s.Bit64=1]="Bit64",s[s.LengthDelimited=2]="LengthDelimited",s[s.StartGroup=3]="StartGroup",s[s.EndGroup=4]="EndGroup",s[s.Bit32=5]="Bit32"})($e||($e={}));function gC(){let s=0,t=0;for(let r=0;r<28;r+=7){let i=this.buf[this.pos++];if(s|=(i&127)<<r,!(i&128))return this.assertBounds(),[s,t]}let e=this.buf[this.pos++];if(s|=(e&15)<<28,t=(e&112)>>4,!(e&128))return this.assertBounds(),[s,t];for(let r=3;r<=31;r+=7){let i=this.buf[this.pos++];if(t|=(i&127)<<r,!(i&128))return this.assertBounds(),[s,t]}throw new Error("invalid varint")}function $h(s,t,e){for(let n=0;n<28;n=n+7){const o=s>>>n,c=!(!(o>>>7)&&t==0),d=(c?o|128:o)&255;if(e.push(d),!c)return}const r=s>>>28&15|(t&7)<<4,i=!!(t>>3);if(e.push((i?r|128:r)&255),!!i){for(let n=3;n<31;n=n+7){const o=t>>>n,c=!!(o>>>7),d=(c?o|128:o)&255;if(e.push(d),!c)return}e.push(t>>>31&1)}}const sl=(1<<16)*(1<<16);function Mf(s){let t=s[0]=="-";t&&(s=s.slice(1));const e=1e6;let r=0,i=0;function n(o,c){const d=Number(s.slice(o,c));i*=e,r=r*e+d,r>=sl&&(i=i+(r/sl|0),r=r%sl)}return n(-24,-18),n(-18,-12),n(-12,-6),n(-6),[t,r,i]}function Uh(s,t){if(t>>>0<=2097151)return""+(sl*t+(s>>>0));let e=s&16777215,r=(s>>>24|t<<8)>>>0&16777215,i=t>>16&65535,n=e+r*6777216+i*6710656,o=r+i*8147497,c=i*2,d=1e7;n>=d&&(o+=Math.floor(n/d),n%=d),o>=d&&(c+=Math.floor(o/d),o%=d);function l(u,h){let g=u?String(u):"";return h?"0000000".slice(g.length)+g:g}return l(c,0)+l(o,c)+l(n,1)}function Of(s,t){if(s>=0){for(;s>127;)t.push(s&127|128),s=s>>>7;t.push(s)}else{for(let e=0;e<9;e++)t.push(s&127|128),s=s>>7;t.push(1)}}function fC(){let s=this.buf[this.pos++],t=s&127;if(!(s&128))return this.assertBounds(),t;if(s=this.buf[this.pos++],t|=(s&127)<<7,!(s&128))return this.assertBounds(),t;if(s=this.buf[this.pos++],t|=(s&127)<<14,!(s&128))return this.assertBounds(),t;if(s=this.buf[this.pos++],t|=(s&127)<<21,!(s&128))return this.assertBounds(),t;s=this.buf[this.pos++],t|=(s&15)<<28;for(let e=5;s&128&&e<10;e++)s=this.buf[this.pos++];if(s&128)throw new Error("invalid varint");return this.assertBounds(),t>>>0}let ve;function vC(){const s=new DataView(new ArrayBuffer(8));ve=globalThis.BigInt!==void 0&&typeof s.getBigInt64=="function"&&typeof s.getBigUint64=="function"&&typeof s.setBigInt64=="function"&&typeof s.setBigUint64=="function"?{MIN:BigInt("-9223372036854775808"),MAX:BigInt("9223372036854775807"),UMIN:BigInt("0"),UMAX:BigInt("18446744073709551615"),C:BigInt,V:s}:void 0}vC();function Df(s){if(!s)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const Nf=/^-?[0-9]+$/,rl=4294967296,il=2147483648;class Lf{constructor(t,e){this.lo=t|0,this.hi=e|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let t=this.hi*rl+(this.lo>>>0);if(!Number.isSafeInteger(t))throw new Error("cannot convert to safe number");return t}}class mt extends Lf{static from(t){if(ve)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=ve.C(t);case"number":if(t===0)return this.ZERO;t=ve.C(t);case"bigint":if(!t)return this.ZERO;if(t<ve.UMIN)throw new Error("signed value for ulong");if(t>ve.UMAX)throw new Error("ulong too large");return ve.V.setBigUint64(0,t,!0),new mt(ve.V.getInt32(0,!0),ve.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!Nf.test(t))throw new Error("string is no integer");let[e,r,i]=Mf(t);if(e)throw new Error("signed value for ulong");return new mt(r,i);case"number":if(t==0)return this.ZERO;if(!Number.isSafeInteger(t))throw new Error("number is no integer");if(t<0)throw new Error("signed value for ulong");return new mt(t,t/rl)}throw new Error("unknown value "+typeof t)}toString(){return ve?this.toBigInt().toString():Uh(this.lo,this.hi)}toBigInt(){return Df(ve),ve.V.setInt32(0,this.lo,!0),ve.V.setInt32(4,this.hi,!0),ve.V.getBigUint64(0,!0)}}mt.ZERO=new mt(0,0);class Ee extends Lf{static from(t){if(ve)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=ve.C(t);case"number":if(t===0)return this.ZERO;t=ve.C(t);case"bigint":if(!t)return this.ZERO;if(t<ve.MIN)throw new Error("signed long too small");if(t>ve.MAX)throw new Error("signed long too large");return ve.V.setBigInt64(0,t,!0),new Ee(ve.V.getInt32(0,!0),ve.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!Nf.test(t))throw new Error("string is no integer");let[e,r,i]=Mf(t);if(e){if(i>il||i==il&&r!=0)throw new Error("signed long too small")}else if(i>=il)throw new Error("signed long too large");let n=new Ee(r,i);return e?n.negate():n;case"number":if(t==0)return this.ZERO;if(!Number.isSafeInteger(t))throw new Error("number is no integer");return t>0?new Ee(t,t/rl):new Ee(-t,-t/rl).negate()}throw new Error("unknown value "+typeof t)}isNegative(){return(this.hi&il)!==0}negate(){let t=~this.hi,e=this.lo;return e?e=~e+1:t+=1,new Ee(e,t)}toString(){if(ve)return this.toBigInt().toString();if(this.isNegative()){let t=this.negate();return"-"+Uh(t.lo,t.hi)}return Uh(this.lo,this.hi)}toBigInt(){return Df(ve),ve.V.setInt32(0,this.lo,!0),ve.V.setInt32(4,this.hi,!0),ve.V.getBigInt64(0,!0)}}Ee.ZERO=new Ee(0,0);const Vf={readUnknownField:!0,readerFactory:s=>new TC(s)};function SC(s){return s?Object.assign(Object.assign({},Vf),s):Vf}class TC{constructor(t,e){this.varint64=gC,this.uint32=fC,this.buf=t,this.len=t.length,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.textDecoder=e!=null?e:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let t=this.uint32(),e=t>>>3,r=t&7;if(e<=0||r<0||r>5)throw new Error("illegal tag: field no "+e+" wire type "+r);return[e,r]}skip(t){let e=this.pos;switch(t){case $e.Varint:for(;this.buf[this.pos++]&128;);break;case $e.Bit64:this.pos+=4;case $e.Bit32:this.pos+=4;break;case $e.LengthDelimited:let r=this.uint32();this.pos+=r;break;case $e.StartGroup:let i;for(;(i=this.tag()[1])!==$e.EndGroup;)this.skip(i);break;default:throw new Error("cant skip wire type "+t)}return this.assertBounds(),this.buf.subarray(e,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)}int64(){return new Ee(...this.varint64())}uint64(){return new mt(...this.varint64())}sint64(){let[t,e]=this.varint64(),r=-(t&1);return t=(t>>>1|(e&1)<<31)^r,e=e>>>1^r,new Ee(t,e)}bool(){let[t,e]=this.varint64();return t!==0||e!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new mt(this.sfixed32(),this.sfixed32())}sfixed64(){return new Ee(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 t=this.uint32(),e=this.pos;return this.pos+=t,this.assertBounds(),this.buf.subarray(e,e+t)}string(){return this.textDecoder.decode(this.bytes())}}function ne(s,t){if(!s)throw new Error(t)}const yC=34028234663852886e22,EC=-34028234663852886e22,bC=4294967295,wC=2147483647,PC=-2147483648;function To(s){if(typeof s!="number")throw new Error("invalid int 32: "+typeof s);if(!Number.isInteger(s)||s>wC||s<PC)throw new Error("invalid int 32: "+s)}function nl(s){if(typeof s!="number")throw new Error("invalid uint 32: "+typeof s);if(!Number.isInteger(s)||s>bC||s<0)throw new Error("invalid uint 32: "+s)}function Bh(s){if(typeof s!="number")throw new Error("invalid float 32: "+typeof s);if(Number.isFinite(s)&&(s>yC||s<EC))throw new Error("invalid float 32: "+s)}const xf={writeUnknownFields:!0,writerFactory:()=>new _C};function kC(s){return s?Object.assign(Object.assign({},xf),s):xf}class _C{constructor(t){this.stack=[],this.textEncoder=t!=null?t:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let t=0;for(let i=0;i<this.chunks.length;i++)t+=this.chunks[i].length;let e=new Uint8Array(t),r=0;for(let i=0;i<this.chunks.length;i++)e.set(this.chunks[i],r),r+=this.chunks[i].length;return this.chunks=[],e}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let t=this.finish(),e=this.stack.pop();if(!e)throw new Error("invalid state, fork stack empty");return this.chunks=e.chunks,this.buf=e.buf,this.uint32(t.byteLength),this.raw(t)}tag(t,e){return this.uint32((t<<3|e)>>>0)}raw(t){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(t),this}uint32(t){for(nl(t);t>127;)this.buf.push(t&127|128),t=t>>>7;return this.buf.push(t),this}int32(t){return To(t),Of(t,this.buf),this}bool(t){return this.buf.push(t?1:0),this}bytes(t){return this.uint32(t.byteLength),this.raw(t)}string(t){let e=this.textEncoder.encode(t);return this.uint32(e.byteLength),this.raw(e)}float(t){Bh(t);let e=new Uint8Array(4);return new DataView(e.buffer).setFloat32(0,t,!0),this.raw(e)}double(t){let e=new Uint8Array(8);return new DataView(e.buffer).setFloat64(0,t,!0),this.raw(e)}fixed32(t){nl(t);let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),this.raw(e)}sfixed32(t){To(t);let e=new Uint8Array(4);return new DataView(e.buffer).setInt32(0,t,!0),this.raw(e)}sint32(t){return To(t),t=(t<<1^t>>31)>>>0,Of(t,this.buf),this}sfixed64(t){let e=new Uint8Array(8),r=new DataView(e.buffer),i=Ee.from(t);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(e)}fixed64(t){let e=new Uint8Array(8),r=new DataView(e.buffer),i=mt.from(t);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(e)}int64(t){let e=Ee.from(t);return $h(e.lo,e.hi,this.buf),this}sint64(t){let e=Ee.from(t),r=e.hi>>31,i=e.lo<<1^r,n=(e.hi<<1|e.lo>>>31)^r;return $h(i,n,this.buf),this}uint64(t){let e=mt.from(t);return $h(e.lo,e.hi,this.buf),this}}const $f={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},Uf={ignoreUnknownFields:!1};function CC(s){return s?Object.assign(Object.assign({},Uf),s):Uf}function RC(s){return s?Object.assign(Object.assign({},$f),s):$f}const Bf=Symbol.for("protobuf-ts/message-type");function Ff(s){let t=!1;const e=[];for(let r=0;r<s.length;r++){let i=s.charAt(r);i=="_"?t=!0:/\d/.test(i)?(e.push(i),t=!0):t?(e.push(i.toUpperCase()),t=!1):r==0?e.push(i.toLowerCase()):e.push(i)}return e.join("")}var O;(function(s){s[s.DOUBLE=1]="DOUBLE",s[s.FLOAT=2]="FLOAT",s[s.INT64=3]="INT64",s[s.UINT64=4]="UINT64",s[s.INT32=5]="INT32",s[s.FIXED64=6]="FIXED64",s[s.FIXED32=7]="FIXED32",s[s.BOOL=8]="BOOL",s[s.STRING=9]="STRING",s[s.BYTES=12]="BYTES",s[s.UINT32=13]="UINT32",s[s.SFIXED32=15]="SFIXED32",s[s.SFIXED64=16]="SFIXED64",s[s.SINT32=17]="SINT32",s[s.SINT64=18]="SINT64"})(O||(O={}));var Ds;(function(s){s[s.BIGINT=0]="BIGINT",s[s.STRING=1]="STRING",s[s.NUMBER=2]="NUMBER"})(Ds||(Ds={}));var al;(function(s){s[s.NO=0]="NO",s[s.PACKED=1]="PACKED",s[s.UNPACKED=2]="UNPACKED"})(al||(al={}));function IC(s){var t,e,r,i;return s.localName=(t=s.localName)!==null&&t!==void 0?t:Ff(s.name),s.jsonName=(e=s.jsonName)!==null&&e!==void 0?e:Ff(s.name),s.repeat=(r=s.repeat)!==null&&r!==void 0?r:al.NO,s.opt=(i=s.opt)!==null&&i!==void 0?i:s.repeat||s.oneof?!1:s.kind=="message",s}function AC(s){if(typeof s!="object"||s===null||!s.hasOwnProperty("oneofKind"))return!1;switch(typeof s.oneofKind){case"string":return s[s.oneofKind]===void 0?!1:Object.keys(s).length==2;case"undefined":return Object.keys(s).length==1;default:return!1}}class MC{constructor(t){var e;this.fields=(e=t.fields)!==null&&e!==void 0?e:[]}prepare(){if(this.data)return;const t=[],e=[],r=[];for(let i of this.fields)if(i.oneof)r.includes(i.oneof)||(r.push(i.oneof),t.push(i.oneof),e.push(i.oneof));else switch(e.push(i.localName),i.kind){case"scalar":case"enum":(!i.opt||i.repeat)&&t.push(i.localName);break;case"message":i.repeat&&t.push(i.localName);break;case"map":t.push(i.localName);break}this.data={req:t,known:e,oneofs:Object.values(r)}}is(t,e,r=!1){if(e<0)return!0;if(t==null||typeof t!="object")return!1;this.prepare();let i=Object.keys(t),n=this.data;if(i.length<n.req.length||n.req.some(o=>!i.includes(o))||!r&&i.some(o=>!n.known.includes(o)))return!1;if(e<1)return!0;for(const o of n.oneofs){const c=t[o];if(!AC(c))return!1;if(c.oneofKind===void 0)continue;const d=this.fields.find(l=>l.localName===c.oneofKind);if(!d||!this.field(c[c.oneofKind],d,r,e))return!1}for(const o of this.fields)if(o.oneof===void 0&&!this.field(t[o.localName],o,r,e))return!1;return!0}field(t,e,r,i){let n=e.repeat;switch(e.kind){case"scalar":return t===void 0?e.opt:n?this.scalars(t,e.T,i,e.L):this.scalar(t,e.T,e.L);case"enum":return t===void 0?e.opt:n?this.scalars(t,O.INT32,i):this.scalar(t,O.INT32);case"message":return t===void 0?!0:n?this.messages(t,e.T(),r,i):this.message(t,e.T(),r,i);case"map":if(typeof t!="object"||t===null)return!1;if(i<2)return!0;if(!this.mapKeys(t,e.K,i))return!1;switch(e.V.kind){case"scalar":return this.scalars(Object.values(t),e.V.T,i,e.V.L);case"enum":return this.scalars(Object.values(t),O.INT32,i);case"message":return this.messages(Object.values(t),e.V.T(),r,i)}break}return!0}message(t,e,r,i){return r?e.isAssignable(t,i):e.is(t,i)}messages(t,e,r,i){if(!Array.isArray(t))return!1;if(i<2)return!0;if(r){for(let n=0;n<t.length&&n<i;n++)if(!e.isAssignable(t[n],i-1))return!1}else for(let n=0;n<t.length&&n<i;n++)if(!e.is(t[n],i-1))return!1;return!0}scalar(t,e,r){let i=typeof t;switch(e){case O.UINT64:case O.FIXED64:case O.INT64:case O.SFIXED64:case O.SINT64:switch(r){case Ds.BIGINT:return i=="bigint";case Ds.NUMBER:return i=="number"&&!isNaN(t);default:return i=="string"}case O.BOOL:return i=="boolean";case O.STRING:return i=="string";case O.BYTES:return t instanceof Uint8Array;case O.DOUBLE:case O.FLOAT:return i=="number"&&!isNaN(t);default:return i=="number"&&Number.isInteger(t)}}scalars(t,e,r,i){if(!Array.isArray(t))return!1;if(r<2)return!0;if(Array.isArray(t)){for(let n=0;n<t.length&&n<r;n++)if(!this.scalar(t[n],e,i))return!1}return!0}mapKeys(t,e,r){let i=Object.keys(t);switch(e){case O.INT32:case O.FIXED32:case O.SFIXED32:case O.SINT32:case O.UINT32:return this.scalars(i.slice(0,r).map(n=>parseInt(n)),e,r);case O.BOOL:return this.scalars(i.slice(0,r).map(n=>n=="true"?!0:n=="false"?!1:n),e,r);default:return this.scalars(i,e,r,Ds.STRING)}}}function Ts(s,t){switch(t){case Ds.BIGINT:return s.toBigInt();case Ds.NUMBER:return s.toNumber();default:return s.toString()}}class OC{constructor(t){this.info=t}prepare(){var t;if(this.fMap===void 0){this.fMap={};const e=(t=this.info.fields)!==null&&t!==void 0?t:[];for(const r of e)this.fMap[r.name]=r,this.fMap[r.jsonName]=r,this.fMap[r.localName]=r}}assert(t,e,r){if(!t){let i=xh(r);throw(i=="number"||i=="boolean")&&(i=r.toString()),new Error(`Cannot parse JSON ${i} for ${this.info.typeName}#${e}`)}}read(t,e,r){this.prepare();const i=[];for(const[n,o]of Object.entries(t)){const c=this.fMap[n];if(!c){if(!r.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${n}`);continue}const d=c.localName;let l;if(c.oneof){if(o===null&&(c.kind!=="enum"||c.T()[0]!=="google.protobuf.NullValue"))continue;if(i.includes(c.oneof))throw new Error(`Multiple members of the oneof group "${c.oneof}" of ${this.info.typeName} are present in JSON.`);i.push(c.oneof),l=e[c.oneof]={oneofKind:d}}else l=e;if(c.kind=="map"){if(o===null)continue;this.assert(hC(o),c.name,o);const u=l[d];for(const[h,g]of Object.entries(o)){this.assert(g!==null,c.name+" map value",null);let v;switch(c.V.kind){case"message":v=c.V.T().internalJsonRead(g,r);break;case"enum":if(v=this.enum(c.V.T(),g,c.name,r.ignoreUnknownFields),v===!1)continue;break;case"scalar":v=this.scalar(g,c.V.T,c.V.L,c.name);break}this.assert(v!==void 0,c.name+" map value",g);let y=h;c.K==O.BOOL&&(y=y=="true"?!0:y=="false"?!1:y),y=this.scalar(y,c.K,Ds.STRING,c.name).toString(),u[y]=v}}else if(c.repeat){if(o===null)continue;this.assert(Array.isArray(o),c.name,o);const u=l[d];for(const h of o){this.assert(h!==null,c.name,null);let g;switch(c.kind){case"message":g=c.T().internalJsonRead(h,r);break;case"enum":if(g=this.enum(c.T(),h,c.name,r.ignoreUnknownFields),g===!1)continue;break;case"scalar":g=this.scalar(h,c.T,c.L,c.name);break}this.assert(g!==void 0,c.name,o),u.push(g)}}else switch(c.kind){case"message":if(o===null&&c.T().typeName!="google.protobuf.Value"){this.assert(c.oneof===void 0,c.name+" (oneof member)",null);continue}l[d]=c.T().internalJsonRead(o,r,l[d]);break;case"enum":if(o===null)continue;let u=this.enum(c.T(),o,c.name,r.ignoreUnknownFields);if(u===!1)continue;l[d]=u;break;case"scalar":if(o===null)continue;l[d]=this.scalar(o,c.T,c.L,c.name);break}}}enum(t,e,r,i){if(t[0]=="google.protobuf.NullValue"&&ne(e===null||e==="NULL_VALUE",`Unable to parse field ${this.info.typeName}#${r}, enum ${t[0]} only accepts null.`),e===null)return 0;switch(typeof e){case"number":return ne(Number.isInteger(e),`Unable to parse field ${this.info.typeName}#${r}, enum can only be integral number, got ${e}.`),e;case"string":let n=e;t[2]&&e.substring(0,t[2].length)===t[2]&&(n=e.substring(t[2].length));let o=t[1][n];return typeof o=="undefined"&&i?!1:(ne(typeof o=="number",`Unable to parse field ${this.info.typeName}#${r}, enum ${t[0]} has no value for "${e}".`),o)}ne(!1,`Unable to parse field ${this.info.typeName}#${r}, cannot parse enum value from ${typeof e}".`)}scalar(t,e,r,i){let n;try{switch(e){case O.DOUBLE:case O.FLOAT:if(t===null)return 0;if(t==="NaN")return Number.NaN;if(t==="Infinity")return Number.POSITIVE_INFINITY;if(t==="-Infinity")return Number.NEGATIVE_INFINITY;if(t===""){n="empty string";break}if(typeof t=="string"&&t.trim().length!==t.length){n="extra whitespace";break}if(typeof t!="string"&&typeof t!="number")break;let o=Number(t);if(Number.isNaN(o)){n="not a number";break}if(!Number.isFinite(o)){n="too large or small";break}return e==O.FLOAT&&Bh(o),o;case O.INT32:case O.FIXED32:case O.SFIXED32:case O.SINT32:case O.UINT32:if(t===null)return 0;let c;if(typeof t=="number"?c=t:t===""?n="empty string":typeof t=="string"&&(t.trim().length!==t.length?n="extra whitespace":c=Number(t)),c===void 0)break;return e==O.UINT32?nl(c):To(c),c;case O.INT64:case O.SFIXED64:case O.SINT64:if(t===null)return Ts(Ee.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return Ts(Ee.from(t),r);case O.FIXED64:case O.UINT64:if(t===null)return Ts(mt.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return Ts(mt.from(t),r);case O.BOOL:if(t===null)return!1;if(typeof t!="boolean")break;return t;case O.STRING:if(t===null)return"";if(typeof t!="string"){n="extra whitespace";break}try{encodeURIComponent(t)}catch(d){d="invalid UTF8";break}return t;case O.BYTES:if(t===null||t==="")return new Uint8Array(0);if(typeof t!="string")break;return pC(t)}}catch(o){n=o.message}this.assert(!1,i+(n?" - "+n:""),t)}}class DC{constructor(t){var e;this.fields=(e=t.fields)!==null&&e!==void 0?e:[]}write(t,e){const r={},i=t;for(const n of this.fields){if(!n.oneof){let l=this.field(n,i[n.localName],e);l!==void 0&&(r[e.useProtoFieldName?n.name:n.jsonName]=l);continue}const o=i[n.oneof];if(o.oneofKind!==n.localName)continue;const c=n.kind=="scalar"||n.kind=="enum"?Object.assign(Object.assign({},e),{emitDefaultValues:!0}):e;let d=this.field(n,o[n.localName],c);ne(d!==void 0),r[e.useProtoFieldName?n.name:n.jsonName]=d}return r}field(t,e,r){let i;if(t.kind=="map"){ne(typeof e=="object"&&e!==null);const n={};switch(t.V.kind){case"scalar":for(const[d,l]of Object.entries(e)){const u=this.scalar(t.V.T,l,t.name,!1,!0);ne(u!==void 0),n[d.toString()]=u}break;case"message":const o=t.V.T();for(const[d,l]of Object.entries(e)){const u=this.message(o,l,t.name,r);ne(u!==void 0),n[d.toString()]=u}break;case"enum":const c=t.V.T();for(const[d,l]of Object.entries(e)){ne(l===void 0||typeof l=="number");const u=this.enum(c,l,t.name,!1,!0,r.enumAsInteger);ne(u!==void 0),n[d.toString()]=u}break}(r.emitDefaultValues||Object.keys(n).length>0)&&(i=n)}else if(t.repeat){ne(Array.isArray(e));const n=[];switch(t.kind){case"scalar":for(let d=0;d<e.length;d++){const l=this.scalar(t.T,e[d],t.name,t.opt,!0);ne(l!==void 0),n.push(l)}break;case"enum":const o=t.T();for(let d=0;d<e.length;d++){ne(e[d]===void 0||typeof e[d]=="number");const l=this.enum(o,e[d],t.name,t.opt,!0,r.enumAsInteger);ne(l!==void 0),n.push(l)}break;case"message":const c=t.T();for(let d=0;d<e.length;d++){const l=this.message(c,e[d],t.name,r);ne(l!==void 0),n.push(l)}break}(r.emitDefaultValues||n.length>0||r.emitDefaultValues)&&(i=n)}else switch(t.kind){case"scalar":i=this.scalar(t.T,e,t.name,t.opt,r.emitDefaultValues);break;case"enum":i=this.enum(t.T(),e,t.name,t.opt,r.emitDefaultValues,r.enumAsInteger);break;case"message":i=this.message(t.T(),e,t.name,r);break}return i}enum(t,e,r,i,n,o){if(t[0]=="google.protobuf.NullValue")return!n&&!i?void 0:null;if(e===void 0){ne(i);return}if(!(e===0&&!n&&!i))return ne(typeof e=="number"),ne(Number.isInteger(e)),o||!t[1].hasOwnProperty(e)?e:t[2]?t[2]+t[1][e]:t[1][e]}message(t,e,r,i){return e===void 0?i.emitDefaultValues?null:void 0:t.internalJsonWrite(e,i)}scalar(t,e,r,i,n){if(e===void 0){ne(i);return}const o=n||i;switch(t){case O.INT32:case O.SFIXED32:case O.SINT32:return e===0?o?0:void 0:(To(e),e);case O.FIXED32:case O.UINT32:return e===0?o?0:void 0:(nl(e),e);case O.FLOAT:Bh(e);case O.DOUBLE:return e===0?o?0:void 0:(ne(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e);case O.STRING:return e===""?o?"":void 0:(ne(typeof e=="string"),e);case O.BOOL:return e===!1?o?!1:void 0:(ne(typeof e=="boolean"),e);case O.UINT64:case O.FIXED64:ne(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let c=mt.from(e);return c.isZero()&&!o?void 0:c.toString();case O.INT64:case O.SFIXED64:case O.SINT64:ne(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let d=Ee.from(e);return d.isZero()&&!o?void 0:d.toString();case O.BYTES:return ne(e instanceof Uint8Array),e.byteLength?mC(e):o?"":void 0}}}function Fh(s,t=Ds.STRING){switch(s){case O.BOOL:return!1;case O.UINT64:case O.FIXED64:return Ts(mt.ZERO,t);case O.INT64:case O.SFIXED64:case O.SINT64:return Ts(Ee.ZERO,t);case O.DOUBLE:case O.FLOAT:return 0;case O.BYTES:return new Uint8Array(0);case O.STRING:return"";default:return 0}}class NC{constructor(t){this.info=t}prepare(){var t;if(!this.fieldNoToField){const e=(t=this.info.fields)!==null&&t!==void 0?t:[];this.fieldNoToField=new Map(e.map(r=>[r.no,r]))}}read(t,e,r,i){this.prepare();const n=i===void 0?t.len:t.pos+i;for(;t.pos<n;){const[o,c]=t.tag(),d=this.fieldNoToField.get(o);if(!d){let g=r.readUnknownField;if(g=="throw")throw new Error(`Unknown field ${o} (wire type ${c}) for ${this.info.typeName}`);let v=t.skip(c);g!==!1&&(g===!0?tl.onRead:g)(this.info.typeName,e,o,c,v);continue}let l=e,u=d.repeat,h=d.localName;switch(d.oneof&&(l=l[d.oneof],l.oneofKind!==h&&(l=e[d.oneof]={oneofKind:h})),d.kind){case"scalar":case"enum":let g=d.kind=="enum"?O.INT32:d.T,v=d.kind=="scalar"?d.L:void 0;if(u){let I=l[h];if(c==$e.LengthDelimited&&g!=O.STRING&&g!=O.BYTES){let D=t.uint32()+t.pos;for(;t.pos<D;)I.push(this.scalar(t,g,v))}else I.push(this.scalar(t,g,v))}else l[h]=this.scalar(t,g,v);break;case"message":if(u){let I=l[h],D=d.T().internalBinaryRead(t,t.uint32(),r);I.push(D)}else l[h]=d.T().internalBinaryRead(t,t.uint32(),r,l[h]);break;case"map":let[y,k]=this.mapEntry(d,t,r);l[h][y]=k;break}}}mapEntry(t,e,r){let i=e.uint32(),n=e.pos+i,o,c;for(;e.pos<n;){let[d,l]=e.tag();switch(d){case 1:t.K==O.BOOL?o=e.bool().toString():o=this.scalar(e,t.K,Ds.STRING);break;case 2:switch(t.V.kind){case"scalar":c=this.scalar(e,t.V.T,t.V.L);break;case"enum":c=e.int32();break;case"message":c=t.V.T().internalBinaryRead(e,e.uint32(),r);break}break;default:throw new Error(`Unknown field ${d} (wire type ${l}) in map entry for ${this.info.typeName}#${t.name}`)}}if(o===void 0){let d=Fh(t.K);o=t.K==O.BOOL?d.toString():d}if(c===void 0)switch(t.V.kind){case"scalar":c=Fh(t.V.T,t.V.L);break;case"enum":c=0;break;case"message":c=t.V.T().create();break}return[o,c]}scalar(t,e,r){switch(e){case O.INT32:return t.int32();case O.STRING:return t.string();case O.BOOL:return t.bool();case O.DOUBLE:return t.double();case O.FLOAT:return t.float();case O.INT64:return Ts(t.int64(),r);case O.UINT64:return Ts(t.uint64(),r);case O.FIXED64:return Ts(t.fixed64(),r);case O.FIXED32:return t.fixed32();case O.BYTES:return t.bytes();case O.UINT32:return t.uint32();case O.SFIXED32:return t.sfixed32();case O.SFIXED64:return Ts(t.sfixed64(),r);case O.SINT32:return t.sint32();case O.SINT64:return Ts(t.sint64(),r)}}}class LC{constructor(t){this.info=t}prepare(){if(!this.fields){const t=this.info.fields?this.info.fields.concat():[];this.fields=t.sort((e,r)=>e.no-r.no)}}write(t,e,r){this.prepare();for(const n of this.fields){let o,c,d=n.repeat,l=n.localName;if(n.oneof){const u=t[n.oneof];if(u.oneofKind!==l)continue;o=u[l],c=!0}else o=t[l],c=!1;switch(n.kind){case"scalar":case"enum":let u=n.kind=="enum"?O.INT32:n.T;if(d)if(ne(Array.isArray(o)),d==al.PACKED)this.packed(e,u,n.no,o);else for(const h of o)this.scalar(e,u,n.no,h,!0);else o===void 0?ne(n.opt):this.scalar(e,u,n.no,o,c||n.opt);break;case"message":if(d){ne(Array.isArray(o));for(const h of o)this.message(e,r,n.T(),n.no,h)}else this.message(e,r,n.T(),n.no,o);break;case"map":ne(typeof o=="object"&&o!==null);for(const[h,g]of Object.entries(o))this.mapEntry(e,r,n,h,g);break}}let i=r.writeUnknownFields;i!==!1&&(i===!0?tl.onWrite:i)(this.info.typeName,t,e)}mapEntry(t,e,r,i,n){t.tag(r.no,$e.LengthDelimited),t.fork();let o=i;switch(r.K){case O.INT32:case O.FIXED32:case O.UINT32:case O.SFIXED32:case O.SINT32:o=Number.parseInt(i);break;case O.BOOL:ne(i=="true"||i=="false"),o=i=="true";break}switch(this.scalar(t,r.K,1,o,!0),r.V.kind){case"scalar":this.scalar(t,r.V.T,2,n,!0);break;case"enum":this.scalar(t,O.INT32,2,n,!0);break;case"message":this.message(t,e,r.V.T(),2,n);break}t.join()}message(t,e,r,i,n){n!==void 0&&(r.internalBinaryWrite(n,t.tag(i,$e.LengthDelimited).fork(),e),t.join())}scalar(t,e,r,i,n){let[o,c,d]=this.scalarInfo(e,i);(!d||n)&&(t.tag(r,o),t[c](i))}packed(t,e,r,i){if(!i.length)return;ne(e!==O.BYTES&&e!==O.STRING),t.tag(r,$e.LengthDelimited),t.fork();let[,n]=this.scalarInfo(e);for(let o=0;o<i.length;o++)t[n](i[o]);t.join()}scalarInfo(t,e){let r=$e.Varint,i,n=e===void 0,o=e===0;switch(t){case O.INT32:i="int32";break;case O.STRING:o=n||!e.length,r=$e.LengthDelimited,i="string";break;case O.BOOL:o=e===!1,i="bool";break;case O.UINT32:i="uint32";break;case O.DOUBLE:r=$e.Bit64,i="double";break;case O.FLOAT:r=$e.Bit32,i="float";break;case O.INT64:o=n||Ee.from(e).isZero(),i="int64";break;case O.UINT64:o=n||mt.from(e).isZero(),i="uint64";break;case O.FIXED64:o=n||mt.from(e).isZero(),r=$e.Bit64,i="fixed64";break;case O.BYTES:o=n||!e.byteLength,r=$e.LengthDelimited,i="bytes";break;case O.FIXED32:r=$e.Bit32,i="fixed32";break;case O.SFIXED32:r=$e.Bit32,i="sfixed32";break;case O.SFIXED64:o=n||Ee.from(e).isZero(),r=$e.Bit64,i="sfixed64";break;case O.SINT32:i="sint32";break;case O.SINT64:o=n||Ee.from(e).isZero(),i="sint64";break}return[r,i,n||o]}}function VC(s){const t=s.messagePrototype?Object.create(s.messagePrototype):Object.defineProperty({},Bf,{value:s});for(let e of s.fields){let r=e.localName;if(!e.opt)if(e.oneof)t[e.oneof]={oneofKind:void 0};else if(e.repeat)t[r]=[];else switch(e.kind){case"scalar":t[r]=Fh(e.T,e.L);break;case"enum":t[r]=0;break;case"map":t[r]={};break}}return t}function Hh(s,t,e){let r,i=e,n;for(let o of s.fields){let c=o.localName;if(o.oneof){const d=i[o.oneof];if((d==null?void 0:d.oneofKind)==null)continue;if(r=d[c],n=t[o.oneof],n.oneofKind=d.oneofKind,r==null){delete n[c];continue}}else if(r=i[c],n=t,r==null)continue;switch(o.repeat&&(n[c].length=r.length),o.kind){case"scalar":case"enum":if(o.repeat)for(let l=0;l<r.length;l++)n[c][l]=r[l];else n[c]=r;break;case"message":let d=o.T();if(o.repeat)for(let l=0;l<r.length;l++)n[c][l]=d.create(r[l]);else n[c]===void 0?n[c]=d.create(r):d.mergePartial(n[c],r);break;case"map":switch(o.V.kind){case"scalar":case"enum":Object.assign(n[c],r);break;case"message":let l=o.V.T();for(let u of Object.keys(r))n[c][u]=l.create(r[u]);break}break}}}function xC(s,t,e){if(t===e)return!0;if(!t||!e)return!1;for(let r of s.fields){let i=r.localName,n=r.oneof?t[r.oneof][i]:t[i],o=r.oneof?e[r.oneof][i]:e[i];switch(r.kind){case"enum":case"scalar":let c=r.kind=="enum"?O.INT32:r.T;if(!(r.repeat?qf(c,n,o):Hf(c,n,o)))return!1;break;case"map":if(!(r.V.kind=="message"?jf(r.V.T(),ol(n),ol(o)):qf(r.V.kind=="enum"?O.INT32:r.V.T,ol(n),ol(o))))return!1;break;case"message":let d=r.T();if(!(r.repeat?jf(d,n,o):d.equals(n,o)))return!1;break}}return!0}const ol=Object.values;function Hf(s,t,e){if(t===e)return!0;if(s!==O.BYTES)return!1;let r=t,i=e;if(r.length!==i.length)return!1;for(let n=0;n<r.length;n++)if(r[n]!=i[n])return!1;return!0}function qf(s,t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(!Hf(s,t[r],e[r]))return!1;return!0}function jf(s,t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(!s.equals(t[r],e[r]))return!1;return!0}const Gf=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})),$C=Gf[Bf]={};class T{constructor(t,e,r){this.defaultCheckDepth=16,this.typeName=t,this.fields=e.map(IC),this.options=r!=null?r:{},$C.value=this,this.messagePrototype=Object.create(null,Gf),this.refTypeCheck=new MC(this),this.refJsonReader=new OC(this),this.refJsonWriter=new DC(this),this.refBinReader=new NC(this),this.refBinWriter=new LC(this)}create(t){let e=VC(this);return t!==void 0&&Hh(this,e,t),e}clone(t){let e=this.create();return Hh(this,e,t),e}equals(t,e){return xC(this,t,e)}is(t,e=this.defaultCheckDepth){return this.refTypeCheck.is(t,e,!1)}isAssignable(t,e=this.defaultCheckDepth){return this.refTypeCheck.is(t,e,!0)}mergePartial(t,e){Hh(this,t,e)}fromBinary(t,e){let r=SC(e);return this.internalBinaryRead(r.readerFactory(t),t.byteLength,r)}fromJson(t,e){return this.internalJsonRead(t,CC(e))}fromJsonString(t,e){let r=JSON.parse(t);return this.fromJson(r,e)}toJson(t,e){return this.internalJsonWrite(t,RC(e))}toJsonString(t,e){var r;let i=this.toJson(t,e);return JSON.stringify(i,null,(r=e==null?void 0:e.prettySpaces)!==null&&r!==void 0?r:0)}toBinary(t,e){let r=kC(e);return this.internalBinaryWrite(t,r.writerFactory(),r).finish()}internalJsonRead(t,e,r){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let i=r!=null?r:this.create();return this.refJsonReader.read(t,i,e),i}throw new Error(`Unable to parse message ${this.typeName} from JSON ${xh(t)}.`)}internalJsonWrite(t,e){return this.refJsonWriter.write(t,e)}internalBinaryWrite(t,e,r){return this.refBinWriter.write(t,e,r),e}internalBinaryRead(t,e,r,i){let n=i!=null?i:this.create();return this.refBinReader.read(t,n,r,e),n}}var nr;(function(s){s[s.PUBLISHER=0]="PUBLISHER",s[s.SUBSCRIBER=1]="SUBSCRIBER"})(nr||(nr={}));var Ns;(function(s){s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO"})(Ns||(Ns={}));class UC extends T{constructor(){super("media.Codec",[{no:1,name:"channels",kind:"scalar",opt:!0,T:5},{no:2,name:"clock_rate",kind:"scalar",T:5},{no:3,name:"mime_type",kind:"scalar",T:9},{no:4,name:"sdp_fmtp_line",kind:"scalar",opt:!0,T:9},{no:5,name:"payload_type",kind:"scalar",opt:!0,T:13}])}}const Wf=new UC;class BC extends T{constructor(){super("media.HeaderExtension",[{no:1,name:"direction",kind:"scalar",opt:!0,T:9},{no:2,name:"uri",kind:"scalar",T:9}])}}const FC=new BC;class HC extends T{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new HC;class qC extends T{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",nr]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const ys=new qC;class jC extends T{constructor(){super("media.ProducerPayload",[{no:1,name:"kind",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8},{no:4,name:"msid",kind:"scalar",T:9},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"mime_type",kind:"scalar",opt:!0,T:9}])}}const GC=new jC;class WC extends T{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:()=>ys},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8},{no:5,name:"producers",kind:"message",repeat:1,T:()=>GC}])}}const JC=new WC;class KC extends T{constructor(){super("media.AudioActivityRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"energy",kind:"scalar",T:5},{no:3,name:"silent",kind:"scalar",T:8}])}}const zC=new KC;class YC extends T{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ys},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:4,name:"producer_ids",kind:"scalar",repeat:2,T:9}])}}const Jf=new YC;class QC extends T{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ys}])}}const XC=new QC;class ZC extends T{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ys}])}}new ZC;class eR extends T{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 tR=new eR;class sR extends T{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 rR=new sR;class iR extends T{constructor(){super("media.ProducerEntry",[{no:1,name:"producing_transport_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9}])}}new iR;class nR extends T{constructor(){super("media.ConsumerEntry",[{no:1,name:"consuming_transport_id",kind:"scalar",T:9},{no:2,name:"consumer_id",kind:"scalar",T:9}])}}new nR;class aR extends T{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",Ns]},{no:3,name:"pause",kind:"scalar",T:8},{no:4,name:"screen_share",kind:"scalar",T:8},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9},{no:8,name:"codec",kind:"message",T:()=>Wf}])}}const yo=new aR;class oR extends T{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>yo},{no:3,name:"producer_track",kind:"message",T:()=>rR},{no:4,name:"error_code",kind:"scalar",opt:!0,T:9}])}}const cR=new oR;class dR extends T{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>cR}}])}}const Kf=new dR;class lR extends T{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>Qf},{no:2,name:"receiver",kind:"message",T:()=>Qf}])}}const zf=new lR;class uR extends T{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>Wf},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>FC}])}}const Yf=new uR;class hR extends T{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>Yf},{no:2,name:"video",kind:"message",T:()=>Yf}])}}const Qf=new hR;class pR extends T{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 mR=new pR;class gR extends T{constructor(){super("media.Simulcast",[{no:1,name:"preferred_rid",kind:"scalar",opt:!0,T:9},{no:2,name:"priority_ordering",kind:"scalar",opt:!0,T:9},{no:3,name:"rid_not_available",kind:"scalar",opt:!0,T:9}])}}const Xf=new gR;class fR extends T{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 vR=new fR;class SR extends T{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:()=>vR},{no:9,name:"capabilities",kind:"message",T:()=>zf}])}}const TR=new SR;class yR extends T{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const ER=new yR;class bR extends T{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const wR=new bR;class PR extends T{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 PR;class kR extends T{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:()=>mR},{no:5,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:6,name:"simulcast",kind:"message",T:()=>Xf}])}}const _R=new kR;class CR extends T{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>_R},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const RR=new CR;class IR extends T{constructor(){super("media.edge.UpdateConsumerSimulcastConfigRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"simulcast",kind:"message",T:()=>Xf},{no:3,name:"producing_transport_id",kind:"scalar",T:9},{no:4,name:"mid",kind:"scalar",T:9}])}}const AR=new IR;class MR extends T{constructor(){super("media.edge.UpdateConsumersSimulcastConfigRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>AR},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const OR=new MR;class DR extends T{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:()=>ys},{no:5,name:"msid",kind:"scalar",T:9},{no:6,name:"app_data",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9},{no:8,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const NR=new DR;class LR extends T{constructor(){super("media.edge.SelectedPeersRequest",[])}}new LR;class VR extends T{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const xR=new VR;class $R extends T{constructor(){super("media.edge.ProducerToggleRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const cl=new $R;class UR extends T{constructor(){super("media.edge.ConsumerToggleRequest",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}new UR;class BR extends T{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ys},{no:3,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const FR=new BR;class HR extends T{constructor(){super("media.edge.ConsumerCloseRequest",[{no:1,name:"consumer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"description",kind:"message",T:()=>ys},{no:3,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const qR=new HR;class jR extends T{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new jR;class GR extends T{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const Zf=new GR;class WR extends T{constructor(){super("media.edge.PeerDisplayNameEditRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}const JR=new WR;class KR extends T{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 zR=new KR;class YR extends T{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 QR=new YR;class XR extends T{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 ZR=new XR;class eI extends T{constructor(){super("media.edge.ErrorResponse",[{no:1,name:"error_message",kind:"scalar",T:9},{no:2,name:"event_id",kind:"scalar",T:5}])}}const tI=new eI;class sI extends T{constructor(){super("media.edge.EmptyResponse",[])}}new sI;class rI extends T{constructor(){super("media.edge.RoomParticipants",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"producer_states",kind:"message",repeat:1,T:()=>yo},{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:()=>zf}])}}const ev=new rI;class iI extends T{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 qh=new iI;class nI extends T{constructor(){super("media.edge.SelectedPeersDiffEntry",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"priority",kind:"scalar",T:5}])}}const aI=new nI;class oI extends T{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>aI}])}}const tv=new oI;class cI extends T{constructor(){super("media.edge.PeerJoinResponse",[])}}new cI;class dI extends T{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>ZR},{no:2,name:"participants",kind:"message",repeat:1,T:()=>ev},{no:3,name:"selected_peers",kind:"message",T:()=>qh},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const jh=new dI;class lI extends T{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}new lI;class uI extends T{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Kf}])}}new uI;class hI extends T{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Kf},{no:3,name:"description",kind:"message",T:()=>ys}])}}const pI=new hI;class mI extends T{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:()=>ys}])}}const gI=new mI;class fI extends T{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>tR}])}}new fI;class vI extends T{constructor(){super("media.edge.ActiveSpeakerResponse",[{no:1,name:"responsepeer_id",kind:"scalar",T:9},{no:2,name:"volume",kind:"scalar",T:5}])}}new vI;class SI extends T{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new SI;class TI extends T{constructor(){super("media.edge.ProducerToggleResponse",[])}}new TI;class yI extends T{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new yI;class EI extends T{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>ys}])}}const bI=new EI;class wI extends T{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>ys}])}}const PI=new wI;class kI extends T{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new kI;class _I extends T{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new _I;class CI extends T{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new CI;class RI extends T{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const II=new RI;class AI extends T{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const MI=new AI;class OI extends T{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const DI=new OI;class NI extends T{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>ev},{no:2,name:"producer_handover_from_peer_id",kind:"scalar",opt:!0,T:9}])}}const sv=new NI;class LI extends T{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const rv=new LI;class VI extends T{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>rv},{no:3,name:"screenshare",kind:"message",T:()=>rv}])}}const xI=new VI;class $I extends T{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>Jf},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>xI}])}}new $I;class UI extends T{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>yo},{no:3,name:"producer_handover_from_peer_id",kind:"scalar",opt:!0,T:9}])}}const BI=new UI;class FI extends T{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>yo},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const iv=new FI;class HI extends T{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>yo}])}}const qI=new HI;class jI extends T{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Gh=new jI;class GI extends T{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const nv=new GI;class WI extends T{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new WI;class JI extends T{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new JI;class KI extends T{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new KI;class zI extends T{constructor(){super("media.edge.PeerDisplayNameEditBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}new zI;class YI extends T{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new YI;class QI extends T{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new QI;class XI extends T{constructor(){super("socket.ai.TranscriptSpeaker",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"participant_id",kind:"scalar",T:9},{no:3,name:"custom_participant_id",kind:"scalar",T:9},{no:4,name:"display_name",kind:"scalar",T:9}])}}const ZI=new XI;class e0 extends T{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},{no:4,name:"sentence",kind:"scalar",T:9},{no:5,name:"speaker",kind:"message",T:()=>ZI},{no:6,name:"started_at",kind:"scalar",T:4,L:2},{no:7,name:"ended_at",kind:"scalar",T:4,L:2},{no:8,name:"confidence",kind:"scalar",T:2}])}}const Wh=new e0;class t0 extends T{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 t0;class s0 extends T{constructor(){super("socket.api.ErrorMessage",[{no:1,name:"code",kind:"scalar",opt:!0,T:5},{no:2,name:"message",kind:"scalar",T:9}])}}const r0=new s0;var Ni;(function(s){s[s.BROWSER=0]="BROWSER",s[s.TRACK=1]="TRACK",s[s.COMPOSITE=2]="COMPOSITE"})(Ni||(Ni={}));var ar;(function(s){s[s.UNSPECIFIED=0]="UNSPECIFIED",s[s.ON_STAGE=1]="ON_STAGE",s[s.APPROVED_STAGE=2]="APPROVED_STAGE",s[s.REQUESTED_STAGE=3]="REQUESTED_STAGE",s[s.OFF_STAGE=4]="OFF_STAGE"})(ar||(ar={}));var Jh;(function(s){s[s.NONE=0]="NONE",s[s.RECORDER=1]="RECORDER",s[s.LIVESTREAMER=2]="LIVESTREAMER"})(Jh||(Jh={}));var Kh;(function(s){s[s.PEERS=0]="PEERS",s[s.ROOMS=1]="ROOMS"})(Kh||(Kh={}));var dl;(function(s){s[s.HIVE=0]="HIVE",s[s.CHAT=1]="CHAT",s[s.PING=2]="PING"})(dl||(dl={}));class i0 extends T{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 n0=new i0;class a0 extends T{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",ar,"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:()=>n0}])}}const ll=new a0;class o0 extends T{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>ll}])}}const Gn=new o0;class c0 extends T{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",ar,"STAGE_TYPE_"]}])}}const av=new c0;class d0 extends T{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 l0=new d0;class u0 extends T{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>ll}])}}const zh=new u0;class h0 extends T{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const ov=new h0;class p0 extends T{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 cv=new p0;class m0 extends T{constructor(){super("socket.room.ActiveRecording",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",Ni]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const g0=new m0;class f0 extends T{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>cv}])}}const dv=new f0;class v0 extends T{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const lv=new v0;class S0 extends T{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 S0;class T0 extends T{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>ll},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"organization_id",kind:"scalar",opt:!0,T:9},{no:5,name:"use_hive",kind:"scalar",opt:!0,T:8},{no:6,name:"preset",kind:"scalar",opt:!0,T:12},{no:7,name:"capabilities",kind:"enum",repeat:1,T:()=>["socket.room.Capabilities",dl,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const y0=new T0;class E0 extends T{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>ll},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const b0=new E0;class w0 extends T{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>cv}])}}const ul=new w0;class P0 extends T{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new P0;class k0 extends T{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 Yh=new k0;class _0 extends T{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 C0=new _0;class R0 extends T{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:()=>C0}])}}const uv=new R0;class I0 extends T{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>uv},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>uv}])}}const A0=new I0;class M0 extends T{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const O0=new M0;class D0 extends T{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>O0}])}}const N0=new D0;class L0 extends T{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:()=>Yh}])}}const V0=new L0;class x0 extends T{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>V0}])}}const $0=new x0;class U0 extends T{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 B0=new U0;class F0 extends T{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>B0}])}}const H0=new F0;class q0 extends T{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const j0=new q0;class G0 extends T{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>j0}])}}const W0=new G0;class J0 extends T{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Y0}])}}const K0=new J0;class z0 extends T{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:()=>Yh}])}}const Y0=new z0;class Q0 extends T{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 X0=new Q0;class Z0 extends T{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:()=>X0}])}}const eA=new Z0;class tA extends T{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:()=>Yh}])}}const hv=new tA;class sA extends T{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>hv}])}}new sA;class rA extends T{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 iA=new rA;class nA extends T{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>cA}])}}const aA=new nA;class oA extends T{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 cA=new oA;class dA extends T{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const pv=new dA;class lA extends T{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",Kh,"BROADCAST_TYPE_"]}])}}const Eo=new lA;class uA extends T{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const hA=new uA;class pA extends T{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const mA=new pA;class gA extends T{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 fA=new gA;class vA extends T{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>fA}])}}const mv=new vA;class SA extends T{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 gv=new SA;var Qh;(function(s){s[s.NONE=0]="NONE",s[s.SKIP=1]="SKIP",s[s.ON_PRIVILEGED_USER_ENTRY=2]="ON_PRIVILEGED_USER_ENTRY",s[s.SKIP_ON_ACCEPT=3]="SKIP_ON_ACCEPT"})(Qh||(Qh={}));var Fr;(function(s){s[s.NONE=0]="NONE",s[s.ALLOWED=1]="ALLOWED",s[s.NOT_ALLOWED=2]="NOT_ALLOWED",s[s.CAN_REQUEST=3]="CAN_REQUEST"})(Fr||(Fr={}));class TA extends T{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 yA=new TA;class EA extends T{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 bA=new EA;class wA extends T{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 PA=new wA;class kA extends T{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 _A=new kA;class CA extends T{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>PA},{no:2,name:"private",kind:"message",T:()=>_A}])}}const RA=new CA;class IA extends T{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 AA=new IA;class MA extends T{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Fr,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Fr,"STREAM_PERMISSION_TYPE_"]}])}}const Xh=new MA;class OA extends T{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>Xh},{no:2,name:"audio",kind:"message",T:()=>Xh},{no:3,name:"screenshare",kind:"message",T:()=>Xh}])}}const DA=new OA;class NA extends T{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>yA},{no:2,name:"plugins",kind:"message",T:()=>bA},{no:3,name:"chat",kind:"message",T:()=>RA},{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",Qh,"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",Jh,"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:()=>AA},{no:23,name:"media",kind:"message",T:()=>DA}])}}const Zh=new NA;class LA extends T{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const VA=new LA;class xA extends T{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 $A=new xA;class UA extends T{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>$A}])}}const BA=new UA;class FA extends T{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>Zh}])}}const fv=new FA;class HA extends T{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>fv}])}}const qA=new HA;class jA extends T{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>fv}])}}const vv=new jA;class GA extends T{constructor(){super("socket.preset.PeerUserIDMap",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9}])}}const WA=new GA;class JA extends T{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>WA},{no:2,name:"patch",kind:"message",T:()=>Zh}])}}new JA;class KA extends T{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>Zh}])}}new KA;class zA extends T{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 Hr=new zA;class YA extends T{constructor(){super("socket.chat.GetPaginatedChatMessageFilters",[{no:1,name:"pinned",kind:"scalar",oneof:"filters",T:8},{no:2,name:"user_id",kind:"scalar",oneof:"filters",T:9}])}}const QA=new YA;class XA extends T{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},{no:6,name:"filters",kind:"message",T:()=>QA}])}}const ZA=new XA;class eM extends T{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Hr},{no:2,name:"next",kind:"scalar",T:8}])}}const tM=new eM;class sM extends T{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Hr}])}}const Sv=new sM;class rM extends T{constructor(){super("socket.chat.SendChatMessageToRoomRequest",[{no:1,name:"payload_type",kind:"scalar",T:5},{no:2,name:"payload",kind:"scalar",T:9}])}}const iM=new rM;class nM extends T{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>Hr}])}}const ep=new nM;class aM extends T{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 oM=new aM;class cM extends T{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>Hr}])}}const tp=new cM;class dM extends T{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}])}}new dM;class lM extends T{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>Hr}])}}new lM;class uM extends T{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 hM=new uM;class pM extends T{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 mM=new pM;class gM extends T{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},{no:4,name:"message",kind:"message",T:()=>Hr}])}}const hl=new gM;class fM extends T{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>Hr}])}}const pl=new fM;class vM extends T{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 SM=new vM;class TM extends T{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 ml=new TM;class yM extends T{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 EM=new yM;class bM extends T{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}])}}new bM;class wM extends T{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}new wM;class PM extends T{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}])}}new PM;class kM extends T{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}])}}new kM;class _M extends T{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new _M;class CM extends T{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new CM;class RM extends T{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>Hr},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const IM=new RM;class AM extends T{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:()=>IM},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const MM=new AM;class OM extends T{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>MM}])}}new OM;class DM extends T{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 NM=new DM;class LM extends T{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>NM}])}}new LM;class VM extends T{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}new VM;class xM extends T{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}new xM;class $M extends T{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}new $M;class UM extends T{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}new UM;class BM extends T{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}])}}new BM;class FM extends T{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}])}}new FM;class HM extends T{constructor(){super("socket.plugin.PluginEventToRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}new HM;class qM extends T{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}])}}new qM;class jM extends T{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 sp=new jM;class GM extends T{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:()=>sp}])}}const WM=new GM;class JM extends T{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:()=>sp}])}}const KM=new JM;class zM extends T{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:()=>sp}])}}const YM=new zM;class QM extends T{constructor(){super("socket.plugin.PluginStoreDeleteRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9}])}}new QM;class XM extends T{constructor(){super("socket.plugin.EnablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"enabled_by",kind:"scalar",T:9}])}}const ZM=new XM;class eO extends T{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>ZM}])}}new eO;class tO extends T{constructor(){super("socket.plugin.DisablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"disabled_by",kind:"scalar",T:9}])}}new tO;class sO extends T{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 rO=new sO;class iO extends T{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:()=>rO}])}}const Tv=new iO;class nO extends T{constructor(){super("socket.plugin.PluginEventResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}new nO;class aO extends T{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 yv=new aO;class oO extends T{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const Ev=new oO;class cO extends T{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 dO=new cO;class lO extends T{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>dO}])}}const rp=new lO;class uO extends T{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const hO=new uO;class pO extends T{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const mO=new pO;class gO extends T{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const bv=new gO;class fO extends T{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:()=>SO},{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 wv=new fO;class vO extends T{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:()=>yO}])}}const SO=new vO;class TO extends T{constructor(){super("socket.polls.PollVote",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])}}const yO=new TO;class EO extends T{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 bO=new EO;class wO extends T{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 PO=new wO;class kO extends T{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>wv}])}}const ip=new kO;class _O extends T{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>wv}])}}const CO=new _O;class RO extends T{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",Ni]}])}}const Pv=new RO;class IO extends T{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 t=this.create(),e=Date.now();return t.seconds=Ee.from(Math.floor(e/1e3)).toBigInt(),t.nanos=e%1e3*1e6,t}toDate(t){return new Date(Ee.from(t.seconds).toNumber()*1e3+Math.ceil(t.nanos/1e6))}fromDate(t){const e=this.create(),r=t.getTime();return e.seconds=Ee.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}internalJsonWrite(t,e){let r=Ee.from(t.seconds).toNumber()*1e3;if(r<Date.parse("0001-01-01T00:00:00Z")||r>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(t.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let i="Z";if(t.nanos>0){let n=(t.nanos+1e9).toString().substring(1);n.substring(3)==="000000"?i="."+n.substring(0,3)+"Z":n.substring(6)==="000"?i="."+n.substring(0,6)+"Z":i="."+n+"Z"}return new Date(r).toISOString().replace(".000Z",i)}internalJsonRead(t,e,r){if(typeof t!="string")throw new Error("Unable to parse Timestamp from JSON "+xh(t)+".");let i=t.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 n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(n<Date.parse("0001-01-01T00:00:00Z")||n>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 r||(r=this.create()),r.seconds=Ee.from(n/1e3).toBigInt(),r.nanos=0,i[7]&&(r.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),r}}new IO;class AO extends T{constructor(){super("common.BaseHubMessage",[{no:1,name:"event",kind:"scalar",T:5},{no:2,name:"id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9},{no:4,name:"room_id",kind:"scalar",T:9},{no:5,name:"user_id",kind:"scalar",T:9},{no:6,name:"payload",kind:"scalar",T:12},{no:7,name:"error",kind:"scalar",opt:!0,T:8},{no:8,name:"sid",kind:"scalar",opt:!0,T:9},{no:9,name:"room_object_id",kind:"scalar",opt:!0,T:9},{no:10,name:"preset",kind:"scalar",opt:!0,T:9},{no:11,name:"use_start_session",kind:"scalar",opt:!0,T:8}])}}const np=new AO;class MO extends T{constructor(){super("common.BulkedHubMessage",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>np}])}}new MO;class OO extends T{constructor(){super("common.CFWorkersResponse",[{no:1,name:"responses",kind:"message",repeat:1,T:()=>np},{no:2,name:"broadcast_responses",kind:"message",repeat:1,T:()=>np}])}}new OO;const DO=0,NO=1,LO=2,VO=3,xO=5,$O={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,updateConnectedRooms:45},UO={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,searchChannelMessages:7,pinMessage:10},BO={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},FO={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},kv={unknown:0,createWebRTCTransport:1,produce:2,consume:3,toggleProducer:4,toggleConsumer:5,closeProducer:6,closeConsumer:7,updateConsumersSimulcastConfig:8,joinRoom:16,leaveRoom:17,selectedPeer:18,globalPinPeer:19,selfJoinComplete:20,peerJoinedBroadcast:25,peerLeaveBroadcast:26,peerProducerCreateBroadcast:27,peerProducerToggleBroadcast:28,peerProducerCloseBroadcast:29,globalPeerPinBroadcast:30,recordingStartedBroadcast:31,recordingStoppedBroadcast:32,peerDisplayNameEditBroadcast:33,mediaRoomTerminationBroadcastResponse:36,selectedPeerDiff:40,renegotiateSessionDescription:50,errorResponse:60,kickPeer:90,kickAll:91,changeDisplayName:92,hostControlPeer:93,hostControlAllPeers:94,audioActivity:100},HO={getUserPresets:0,updateUserPreset:1};function bo(s,t){return Object.keys(t).reduce((e,r)=>(e[r]=(s<<16)+t[r],e),{})}function _v(s,t){return Object.keys(s).reduce((e,r)=>(e[r]=t|s[r],e),{})}const x=bo(DO,$O),Ke=bo(NO,UO),or=bo(LO,BO),cr=bo(VO,FO),qr=_v(kv,16777216),Es=_v(kv,50331648),gl=bo(xO,HO);var qO=Object.defineProperty,jO=Object.getOwnPropertyDescriptor,jr=(s,t,e,r)=>{for(var i=r>1?void 0:r?jO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&qO(t,e,i),i},rs=(s=>(s[s.TEXT=0]="TEXT",s[s.IMAGE=1]="IMAGE",s[s.FILE=2]="FILE",s[s.CUSTOM=3]="CUSTOM",s))(rs||{});class dr{constructor(t,e){m(this,Wt,void 0);m(this,ca,void 0);f(this,Wt,e),f(this,ca,t)}get telemetry(){return a(this,ca).getValue("telemetry")}get logger(){return a(this,ca).getValue("logger")}getChatMessages(){return a(this,Wt).sendMessagePromise(Ke.getMessages)}async getChatMessagesPaginated(t,e,r,i){const n={timeStamp:t,size:e,from:0,reversed:r,...i&&{filters:{filters:i}}},o=await a(this,Wt).sendMessagePromise(Ke.getPaginatedMessages,ZA.toBinary(n));return o.payload?tM.fromBinary(o.payload):{messages:[],next:!1}}sendMessageToRoom(t,e){const r={payloadType:e,payload:t};a(this,Wt).sendMessage(Ke.sendMessageToRoom,iM.toBinary(r))}sendMessageToPeers(t,e,r){const i={payloadType:e,peerIds:r,payload:t};a(this,Wt).sendMessage(Ke.sendMessageToPeers,oM.toBinary(i))}sendMessage(t,e,r){if(r&&r.length>0){this.sendMessageToPeers(t,e,r);return}this.sendMessageToRoom(t,e)}async editMessage(t,e,r,i){const n={chatId:t,payloadType:r,payload:e};i!==void 0&&(n.pinned=i);const o=await a(this,Wt).sendMessagePromise(Ke.editMessage,hM.toBinary(n));return pl.fromBinary(o.payload).message}async deleteMessage(t){const e={chatId:t},r=await a(this,Wt).sendMessagePromise(Ke.deleteMessage,SM.toBinary(e));return{id:ml.fromBinary(r.payload).chatId}}async searchMessages(t,e){var i,n,o,c;const r={searchTerm:t,timeStamp:(i=e.timestamp)!=null?i:Date.now(),size:(n=e.limit)!=null?n:75,from:(o=e.offset)!=null?o:0,reversed:(c=e.reversed)!=null?c:!0};try{const d=await a(this,Wt).sendMessagePromise(Ke.searchChannelMessages,EM.toBinary(r));return Sv.fromBinary(d.payload).messages}catch(d){return[]}}async setPinState(t,e){const r={chatId:t,pinned:e},i=await a(this,Wt).sendMessagePromise(Ke.pinMessage,mM.toBinary(r));return hl.fromBinary(i.payload)}on(t,e){let r,i;switch(t){case Ke.sendMessageToRoom:{r=ep.fromBinary.bind(ep),i=ep.create();break}case Ke.sendMessageToPeers:{r=tp.fromBinary.bind(tp),i=tp.create();break}case Ke.editMessage:{r=pl.fromBinary.bind(pl),i=pl.create();break}case Ke.pinMessage:{r=hl.fromBinary.bind(hl),i=hl.create();break}case Ke.deleteMessage:{r=ml.fromBinary.bind(ml),i=ml.create();break}}if(!r){this.logger.warn(`ChatSocketHandler::Event ${t} is not recognized`);return}a(this,Wt).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}Wt=new WeakMap,ca=new WeakMap,jr([E.trace("SocketService.getChatMessages")],dr.prototype,"getChatMessages",1),jr([E.trace("SocketService.getChatMessagesPaginated")],dr.prototype,"getChatMessagesPaginated",1),jr([E.trace("SocketService.sendMessageToRoom")],dr.prototype,"sendMessageToRoom",1),jr([E.trace("SocketService.sendMessageToPeers")],dr.prototype,"sendMessageToPeers",1),jr([E.trace("SocketService.sendMessage")],dr.prototype,"sendMessage",1),jr([E.trace("SocketService.editMessage")],dr.prototype,"editMessage",1),jr([E.trace("SocketService.deleteMessage")],dr.prototype,"deleteMessage",1),jr([E.trace("SocketService.searchMessages")],dr.prototype,"searchMessages",1);function GO(s){return s.replace(/([-_]\w)/g,t=>t[1].toUpperCase())}function Ls(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>Ls(e));const t={};return Object.keys(s).forEach(e=>{const r=nh(e)?e:GO(e);t[r]=Ls(s[e])}),t}function WO(s){return s.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Cv(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>Cv(e));const t={};return Object.keys(s).forEach(e=>{const r=nh(e)?e:WO(e);t[r]=s[e]}),t}class fl extends Error{constructor(e){const r=e instanceof Error?e.message:`Request failed with status ${e.status}`;super(r);p(this,"status");p(this,"response");p(this,"isTimeout");e instanceof Error?(this.stack=e.stack,this.isTimeout=e.name==="AbortError"):(this.status=e.status,this.response=e,this.isTimeout=!1),this.name="RequestError"}get isHttpError(){return this.status!==void 0}get isNetworkError(){return this.status===void 0&&!this.isTimeout}}class Rv{constructor(t){p(this,"defaults");this.defaults={baseURL:t.baseURL,headers:{common:{}},timeout:t.timeout,retry:t.retry,retryDelay:t.retryDelay}}buildURL(t,e){const{baseURL:r}=this.defaults,i=t.startsWith("http")?t:`${r}${t.startsWith("/")?t:`/${t}`}`;if(e){const n=new URLSearchParams;return Object.entries(e).forEach(([o,c])=>{n.append(o,c)}),`${i}${i.includes("?")?"&":"?"}${n.toString()}`}return i}async request(t){var h;const e=((h=t.method)==null?void 0:h.toUpperCase())||"GET",r=this.buildURL(t.url||"",t.params),i={...this.defaults.headers.common,...t.headers};e!=="GET"&&e!=="HEAD"&&t.data&&!i["Content-Type"]&&(i["Content-Type"]="application/json");const o=i["Content-Type"]==="application/json"?JSON.stringify(t.data):t.data,c={method:e,headers:i,body:e!=="GET"&&e!=="HEAD"&&t.data?o:void 0},d=t.timeout||this.defaults.timeout,l=t.retry!==void 0?t.retry:this.defaults.retry,u=t.retryDelay||this.defaults.retryDelay;try{const g=new AbortController,v=setTimeout(()=>g.abort(),d);c.signal=g.signal;const y=await fetch(r,c);clearTimeout(v);let k=null;const I=y.headers.get("content-type");I&&I.includes("application/json")?k=await y.json():k=await y.text();const D={};y.headers.forEach((B,U)=>{D[U]=B});const N={data:k,status:y.status,statusText:y.statusText,headers:D,config:t};if(!y.ok)throw N;return N}catch(g){if(g instanceof Error&&l>0)return await new Promise(v=>setTimeout(v,u)),this.defaults.baseURL===Di.apiBase.prod?this.defaults.baseURL=Di.apiBase.prodAlternate:this.defaults.baseURL===Di.apiBase.prodAlternate&&(this.defaults.baseURL=Di.apiBase.prod),this.request({...t,retry:l-1});throw g}}async get(t,e={}){return this.request({...e,method:"GET",url:t})}async post(t,e,r={}){return this.request({...r,method:"POST",url:t,data:e})}async put(t,e,r={}){return this.request({...r,method:"PUT",url:t,data:e})}}const JO=3,KO=30,zO=8e3;class YO{constructor(t,e){p(this,"fetchClient");p(this,"requests");p(this,"roomName");p(this,"roomUUID");p(this,"authToken");p(this,"organizationId");p(this,"iceServers");p(this,"userDetails");p(this,"roomDetails");p(this,"context");this.context=t;const{timeout:r=zO,retry:i=JO,retryDelay:n=KO,baseURL:o=Di.apiBase.prod,authToken:c,cachedUserDetails:d}=e||{};this.iceServers=d==null?void 0:d.iceServers,this.userDetails=d==null?void 0:d.userDetails,this.roomDetails=d==null?void 0:d.roomDetails,this.requests=new Rv({baseURL:o,timeout:r,retry:i,retryDelay:n,responseType:"json"}),this.fetchClient=new Rv({baseURL:"",timeout:r,retry:i,retryDelay:n,responseType:"json"}),this.setAuthToken(c,{bearer:!0});const l=this.requests.request.bind(this.requests);this.requests.request=async u=>{var g,v,y,k,I,D;const h=t.getValue("telemetry");try{h.injectContext(this.requests.defaults.headers.common);const N=await l(u);return u.url!==h.logsEndpoint&&this.logger.debug(`XHR - Fetched ${u.method}:${u.url} with status ${N.status}`,{networkCall:{status:N.status,statusText:N.statusText,baseURL:u.baseURL||this.requests.defaults.baseURL,url:u.url,method:u.method}}),N}catch(N){if(!N)throw new C("Unknown network error occurred","0011");if(N instanceof C||N instanceof fl)throw N;((g=N.config)==null?void 0:g.url)!==h.logsEndpoint&&this.logger.error(`XHR - Fetch failed on ${u.method}:${u.url} with status ${N.status}. Retry: ${(v=N.config)==null?void 0:v.retry}`,{error:N,networkCall:{status:N.status,statusText:N.statusText,baseURL:((y=N.config)==null?void 0:y.baseURL)||this.requests.defaults.baseURL,url:(k=N.config)==null?void 0:k.url,retries:(I=N.config)==null?void 0:I.retry,method:(D=N.config)==null?void 0:D.method,isOnline:navigator.onLine?"online":"offline"}});const B=N instanceof Error&&N.message||"Network request failed";throw new C(B,"0011"),new fl(N)}}}get peerId(){return this.context.getValue("peerId")}get logger(){return this.context.getValue("logger")}setAuthToken(t,e){const{bearer:r}=e||{};this.authToken=t,this.requests.defaults.headers.common.Authorization=r?`Bearer ${t}`:t}setHeader(t,e){this.requests.defaults.headers.common[t]=e}setRoomName(t){this.roomName=t}setRoomUUID(t){this.roomUUID=t}setOrganizationId(t){this.organizationId=t}}var QO=Object.defineProperty,XO=Object.getOwnPropertyDescriptor,lr=(s,t,e,r)=>{for(var i=r>1?void 0:r?XO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&QO(t,e,i),i};class Vs extends YO{constructor(e,r){super(e,r);p(this,"telemetry");this.telemetry=e.getValue("telemetry"),this.setHeader("x-realtimekit-version",e.getValue("sdkVersion"))}async getICEServers(){if(this.iceServers)return this.iceServers;const{success:e,iceServers:r}=(await this.requests.get("/iceservers")).data;if(e)return(r==null?void 0:r.length)>0&&(this.iceServers=r),r}async getPresignedUrls(e){const r=So(this.context,"chat_upload_expiry"),i={roomUUID:this.roomUUID,filename:e,expiry:typeof r=="number"?r:void 0},{get_location:n,put_location:o}=(await this.requests.post("/v2/meetings/chat-upload",i)).data.data;return{getLocation:n,putLocation:o}}async uploadFile(e,r){if(navigator.isReactNative&&"uri"in e)try{await fetch(r,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:{uri:e.uri,name:e.name}})}catch(i){this.logger.error(`sendFileMessage::${i}`)}else await this.fetchClient.put(r,e,{headers:{"Content-Type":e.type}})}async startLivestreaming({manualIngestion:e}){const r=Ls(await this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/livestreams`,{manual_ingest:!!e})).data.data;return{playbackUrl:r.playbackUrl,status:r.status,manualIngest:r.manualIngest,ingestionCredentials:r.streamKey?{ingestionServer:r.ingestServer,streamKey:r.streamKey}:null}}async stopLivestreaming(){return this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream/stop`)}async getActiveLivestream(){const e=Ls((await 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}}async getUserDetails(){if(this.userDetails)return this.userDetails;const e=(await this.requests.get("v2/internals/participant-details")).data.data;return Ls(e)}async startRecording(e,r){return(await this.requests.post("/v2/recordings",{...Cv(e),meeting_id:this.context.getValue("meetingId"),allow_multiple_recordings:!!r})).data.data.id}async updateRecording(e,r){return this.requests.put(`v2/recordings/${e}`,{action:r})}async getActiveRecording(){const{status:e,id:r}=(await this.requests.get(`v2/recordings/active-recording/${this.context.getValue("meetingId")}`)).data.data;return{status:e,id:r}}async getActiveTranscript(){const{transcript_download_url:e}=(await this.requests.get(`v2/meetings/${this.context.getValue("meetingId")}/active-transcript`)).data.data;try{return{transcript:(await this.fetchClient.get(e)).data}}catch(r){throw new C("Cant fetch transcript s3 url","1801")}}}lr([E.trace("APIClient.getICEServers")],Vs.prototype,"getICEServers",1),lr([E.trace("APIClient.startLivestreaming")],Vs.prototype,"startLivestreaming",1),lr([E.trace("APIClient.stopLivestreaming")],Vs.prototype,"stopLivestreaming",1),lr([E.trace("APIClient.getActiveLivestream")],Vs.prototype,"getActiveLivestream",1),lr([E.trace("APIClient.getUserDetails")],Vs.prototype,"getUserDetails",1),lr([E.trace("APIClient.startRecording")],Vs.prototype,"startRecording",1),lr([E.trace("APIClient.stopRecording")],Vs.prototype,"updateRecording",1),lr([E.trace("APIClient.getActiveRecording")],Vs.prototype,"getActiveRecording",1),lr([E.trace("APIClient.getActiveTranscript")],Vs.prototype,"getActiveTranscript",1);let ap;function ZO(s,t){return ap=new Vs(s,t),ap}function Ht(){return ap}const Wn={maxInvocations:5,period:1};function qt(s,t){return function(e,r,i){const n=i.value;let o=0,c=Date.now();return i.value=function(...d){const l=Date.now(),u=t?this[t]:s;if(l-c>u.period*1e3&&(c=l,o=0),o>=u.maxInvocations)throw new C(`Method rate limit ${u.maxInvocations} invocations/${u.period}sec exceeded`,"0013");return o+=1,n.apply(this,d)},i}}var eD=Object.defineProperty,tD=Object.getOwnPropertyDescriptor,xs=(s,t,e,r)=>{for(var i=r>1?void 0:r?tD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&eD(t,e,i),i};const sD=["text","image","file","custom","poll"],vl={maxInvocations:180,period:60};let is=(BS=class extends Bt{constructor(t,e,r,i){const n=t.getValue("logger");super(n);m(this,Ql);m(this,jo);p(this,"messages");m(this,ie,void 0);m(this,Ji,void 0);m(this,ot,void 0);m(this,da,void 0);p(this,"maxTextLimit",2e3);f(this,da,t),f(this,ot,e),f(this,ie,r),f(this,Ji,i),this.messages=[]}get telemetry(){return a(this,da).getValue("telemetry")}setMaxTextLimit(t){this.maxTextLimit=t}async sendMessageInternal(t,e){switch(t.type){case"text":{await this.sendTextMessageInternal(t.message,e);break}case"image":await this.sendImageMessageInternal(t.image,e);break;case"file":await this.sendFileMessageInternal(t.file,e);break;default:this.logger.error("sendMessage::message_type_not_supported",{chat:{messageType:t.type}});break}}async sendTextMessageInternal(t,e){var i,n,o,c,d,l;if(t.length>this.maxTextLimit)throw new C("Max character limit breached","0503");if(e&&e.length>0){if(!((i=a(this,ie).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,ie).permissions)!=null&&n.chatPrivate.text))throw this.logger.error("sendTextMessage::private_chat_permission_denied"),new C("Could not send message to private chat.","0501")}else if(!((c=(o=a(this,ie).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,ie).permissions)==null?void 0:d.chatPublic)!=null&&l.text))throw this.logger.error("sendTextMessage::public_chat_permission_denied"),new C("Could not send message to public chat.","0501");if(!t)throw this.logger.error("sendTextMessage::message_can_not_be_empty"),new C("Message can not be empty.","0502");let r=[];e&&e.length>0&&(e.push(a(this,ie).id),r=a(this,Ji).joined.toArray().filter(u=>e.includes(u.id)).map(u=>u.userId),r.push(a(this,ie).userId)),a(this,ot).sendMessage(t,rs.TEXT,e)}async sendImageMessageInternal(t,e){var i,n,o,c,d,l;if(e&&e.length>0){if(!((i=a(this,ie).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,ie).permissions)!=null&&n.chatPrivate.files)){this.logger.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((c=(o=a(this,ie).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,ie).permissions)==null?void 0:d.chatPublic)!=null&&l.files)){this.logger.error("sendImageMessage::permission_denied");return}if(!t){this.logger.error("sendImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(t.type)){this.logger.error("sendImageMessage::image_type_not_supported",{chat:{imageType:t.type}});return}try{const u=Ht(),{getLocation:h,putLocation:g}=await u.getPresignedUrls(t.name);await u.uploadFile(t,g);let v=[];e&&e.length>0&&(e.push(a(this,ie).id),v=a(this,Ji).joined.toArray().filter(y=>e.includes(y.id)).map(y=>y.userId),v.push(a(this,ie).userId)),a(this,ot).sendMessage(h,rs.IMAGE,e)}catch(u){throw new C("Error sending image message.","0500",this.logger)}}async sendFileMessageInternal(t,e){var r,i,n,o,c,d;if(e&&e.length>0){if(!((r=a(this,ie).permissions)!=null&&r.chatPrivate.canSend)||!((i=a(this,ie).permissions)!=null&&i.chatPrivate.files)){this.logger.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((o=(n=a(this,ie).permissions)==null?void 0:n.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,ie).permissions)==null?void 0:c.chatPublic)!=null&&d.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!t){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const l=Ht(),{getLocation:u,putLocation:h}=await l.getPresignedUrls(t.name);await l.uploadFile(t,h);let g=[];e&&e.length>0&&(e.push(a(this,ie).id),g=a(this,Ji).joined.toArray().filter(y=>e.includes(y.id)).map(y=>y.userId),g.push(a(this,ie).userId));const v=JSON.stringify({link:u,name:t.name,size:"size"in t?t.size:0});a(this,ot).sendMessage(v,rs.FILE,e)}catch(l){throw new C("Error sending file message.","0500",this.logger)}}get rateLimits(){return vl}updateRateLimits(t,e){vl.maxInvocations=t,vl.period=e}async sendTextMessage(t,e){return this.sendTextMessageInternal(t,e)}async sendCustomMessage(t,e){var n,o,c,d,l,u,h,g,v,y,k,I,D,N,B;if(e&&e.length>0){if(!((n=a(this,ie).permissions)!=null&&n.chatPrivate.canSend)||!((o=a(this,ie).permissions)!=null&&o.chatPrivate.files)||!((c=a(this,ie).permissions)!=null&&c.chatPrivate.text)){this.logger.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((l=(d=a(this,ie).permissions)==null?void 0:d.chatPublic)!=null&&l.canSend)||!((h=(u=a(this,ie).permissions)==null?void 0:u.chatPublic)!=null&&h.files)||!((v=(g=a(this,ie).permissions)==null?void 0:g.chatPublic)!=null&&v.text)){this.logger.error("sendCustomMessage::permission_denied");return}const r=async U=>{try{if(typeof U=="string")return{link:U};const j=Ht(),{getLocation:Z,putLocation:re}=await j.getPresignedUrls(U.name);return await j.uploadFile(U,re),{link:Z,type:U.type,name:U.name,size:U.size}}catch(j){throw new C("Error sending image message.","0500",this.logger)}},i={...t,files:await Promise.all((k=(y=t.files)!=null?y:[])==null?void 0:k.map(async U=>r(U))),images:await Promise.all((D=(I=t.images)!=null?I:[])==null?void 0:D.map(async U=>r(U))),videos:await Promise.all((B=(N=t.videos)!=null?N:[])==null?void 0:B.map(async U=>r(U)))};a(this,ot).sendMessage(JSON.stringify(i),rs.CUSTOM,e)}async sendImageMessage(t,e){return this.sendImageMessageInternal(t,e)}async sendFileMessage(t,e){return this.sendFileMessageInternal(t,e)}async sendMessage(t,e){return this.sendMessageInternal(t,e)}async editTextMessage(t,e){var r,i,n,o;if(!((i=(r=a(this,ie).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(n=a(this,ie).permissions)==null?void 0:n.chatPublic)!=null&&o.text)){this.logger.error("editTextMessage::permission_denied");return}if(!e){this.logger.error("editTextMessage::message_can_not_be_empty");return}a(this,ot).editMessage(t,e,rs.TEXT)}async editImageMessage(t,e){var i,n,o,c;if(!((n=(i=a(this,ie).permissions)==null?void 0:i.chatPublic)!=null&&n.canSend)||!((c=(o=a(this,ie).permissions)==null?void 0:o.chatPublic)!=null&&c.files)){this.logger.error("editImageMessage::permission_denied");return}if(!e){this.logger.error("editImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(e.type)){this.logger.error("sendImageMessage::image_type_not_supported",{chat:{imageType:e.type}});return}try{const d=Ht(),{getLocation:l,putLocation:u}=await d.getPresignedUrls(e.name);await d.uploadFile(e,u),a(this,ot).editMessage(t,l,rs.IMAGE)}catch(d){throw new C("Error editing image message.","0500",this.logger)}}async editFileMessage(t,e){var r,i,n,o;if(!((i=(r=a(this,ie).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(n=a(this,ie).permissions)==null?void 0:n.chatPublic)!=null&&o.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!e){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const c=Ht(),{getLocation:d,putLocation:l}=await c.getPresignedUrls(e.name);await c.uploadFile(e,l),a(this,ot).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),rs.FILE)}catch(c){throw new C("Error editing file message.","0500",this.logger)}}async editMessage(t,e){switch(e.type){case"text":{this.editTextMessage(t,e.message);break}case"image":{this.editImageMessage(t,e.image);break}case"file":{this.editFileMessage(t,e.file);break}default:{this.logger.error("editMessage::message_type_not_supported",{chat:{messageType:e.type}});break}}}async deleteMessage(t){a(this,ot).deleteMessage(t)}async pin(t){if(!a(this,jo,Kp))throw new C("Can`t pin message without joining room","0505");try{await a(this,ot).setPinState(t,!0)}catch(e){throw new C(`No message found with id: ${t}`,"0504")}}async unpin(t){if(!a(this,jo,Kp))throw new C("Can`t unpin message without joining room","0505");try{await a(this,ot).setPinState(t,!1)}catch(e){throw new C(`No message found with id: ${t}`,"0504")}}async fetchPublicMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await a(this,ot).getChatMessagesPaginated(t,e,r==="before")).messages.map(o=>wo.formatSocketPeerMessage(o))}async fetchPrivateMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after",userId:i}){return(await a(this,ot).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"userId",userId:i})).messages.map(c=>wo.formatSocketPeerMessage(c))}async fetchPinnedMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await a(this,ot).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"pinned",pinned:!0})).messages.map(o=>wo.formatSocketPeerMessage(o))}},ie=new WeakMap,Ji=new WeakMap,ot=new WeakMap,da=new WeakMap,Ql=new WeakSet,iT=function(){return a(this,da).getValue("connectionHandler")},jo=new WeakSet,Kp=function(){return a(this,Ql,iT).socketJoined===!0},BS);xs([E.trace("Chat.sendTextMessage"),qt(vl)],is.prototype,"sendTextMessage",1),xs([E.trace("Chat.sendImageMessage"),qt({maxInvocations:20,period:60})],is.prototype,"sendImageMessage",1),xs([E.trace("Chat.sendFileMessage"),qt({maxInvocations:20,period:60})],is.prototype,"sendFileMessage",1),xs([E.trace("Chat.sendMessage"),qt({maxInvocations:180,period:60})],is.prototype,"sendMessage",1),xs([E.trace("Chat.editTextMessage")],is.prototype,"editTextMessage",1),xs([E.trace("Chat.editImageMessage")],is.prototype,"editImageMessage",1),xs([E.trace("Chat.editFileMessage")],is.prototype,"editFileMessage",1),xs([E.trace("Chat.editMessage")],is.prototype,"editMessage",1),xs([E.trace("Chat.deleteMessage")],is.prototype,"deleteMessage",1),is=xs([pt("0500")],is);var rD=Object.defineProperty,iD=Object.getOwnPropertyDescriptor,nD=(s,t,e,r)=>{for(var i=r>1?void 0:r?iD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&rD(t,e,i),i};const Gr=(FS=class{constructor(s,t,e,r){p(this,"chat");p(this,"chatSocketHandler");p(this,"self");m(this,Ki,void 0);f(this,Ki,s),this.chatSocketHandler=t,this.chat=new is(s,t,e,r),this.self=e,this.setupEvents()}get telemetry(){return a(this,Ki).getValue("telemetry")}get logger(){return a(this,Ki).getValue("logger")}static async init(s,t,e,r){return new Gr(s,t,e,r)}static formatMessage(s){return{...s,time:new Date(s.time),type:sD[s.type]}}static formatSocketPeerMessage(s){const t=s.createdAt*1e3,e={displayName:s.displayName,id:s.chatId,time:t,timeMs:s.createdAtMs,type:s.payloadType,isEdited:s.isEdited,userId:s.userId,targetUserIds:s.targetUserIds,message:"",link:"",name:"",html:"",images:[],videos:[],files:[],size:0,pinned:s.pinned};switch(e.type){case rs.TEXT:{e.message=s.payload;break}case rs.IMAGE:{e.link=s.payload;break}case rs.FILE:{const{link:r,name:i,size:n}=JSON.parse(s.payload);e.link=r,e.name=i,e.size=n;break}case rs.CUSTOM:{const{html:r,images:i,message:n,videos:o,files:c}=JSON.parse(s.payload);e.message=n,e.html=r,e.images=i,e.videos=o,e.files=c;break}}return Gr.formatMessage(e)}async getChatMessages(){if(this.self.config.viewType==="LIVESTREAM")return;const s=await this.chatSocketHandler.getChatMessages();if(!(s!=null&&s.payload))return;const t=Sv.fromBinary(s.payload).messages;this.chat.messages=t.map(e=>Gr.formatSocketPeerMessage(e))}setupEvents(){a(this,Ki).getValue("peerSessionStore").on(P.SOCKET_SERVICE_ROOM_JOINED,async()=>{this.getChatMessages()}),this.chatSocketHandler.on(Ke.sendMessageToRoom,s=>{if(!s.message)return;const t=Gr.formatSocketPeerMessage(s.message);this.chat.messages=[...this.chat.messages,t],this.chat.emit("chatUpdate",{action:"add",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(Ke.sendMessageToPeers,s=>{const t=Gr.formatSocketPeerMessage(s.message);this.chat.messages=[...this.chat.messages,t],this.chat.emit("chatUpdate",{action:"add",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(Ke.editMessage,s=>{if(!s.message)return;const t=Gr.formatSocketPeerMessage(s.message),e=this.chat.messages.findIndex(r=>r.id===t.id);e!==-1&&(this.chat.messages[e]=t),this.chat.emit("chatUpdate",{action:"edit",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(Ke.deleteMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId);let e={id:s.chatId};t!==-1&&([e]=this.chat.messages.splice(t,1)),this.chat.emit("chatUpdate",{action:"delete",message:e,messages:this.chat.messages})}),this.chatSocketHandler.on(Ke.pinMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId),e=Gr.formatSocketPeerMessage(s.message);t!==-1&&(this.chat.messages[t]=e),this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages}),s.pinned?this.chat.emit("pinMessage",{message:e,messages:this.chat.messages}):this.chat.emit("unpinMessage",{message:e,messages:this.chat.messages})})}},Ki=new WeakMap,FS);let wo=Gr;nD([E.trace("ChatController.setupEvents")],wo.prototype,"setupEvents",1);var aD=Object.defineProperty,oD=Object.getOwnPropertyDescriptor,cD=(s,t,e,r)=>{for(var i=r>1?void 0:r?oD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&aD(t,e,i),i};let op=(HS=class extends Bt{constructor(t,e,r){const i=t.getValue("logger");super(i);m(this,Xl);m(this,Zl);p(this,"items");m(this,la,void 0);m(this,ua,void 0);m(this,Go,void 0);f(this,Go,t),f(this,la,e),f(this,ua,r),this.items=[]}async create(t,e,r=!1,i=!1){if(!a(this,Zl,aT))throw new C("Can't create polls without joining room","0705");if(!a(this,la).permissions.polls.canCreate){this.logger.error("Polls::create::permission_denied");return}if(!t||!e){this.logger.error("Polls::question_and_options_can_not_be_empty",{polls:{hasQuestion:!!t,optionsLength:e==null?void 0:e.length}});return}if(e.length<2){this.logger.error("Polls::there_must_be_at_least_two_options",{polls:{hasQuestion:!!t,optionsLength:e.length}});return}await a(this,ua).createPoll(t,e,r,i)}async vote(t,e){if(!a(this,la).permissions.polls.canVote){this.logger.error("Polls::vote::permission_denied");return}await a(this,ua).votePoll(t,e)}},Xl=new WeakSet,nT=function(){return a(this,Go).getValue("connectionHandler")},Zl=new WeakSet,aT=function(){var t;return((t=a(this,Xl,nT))==null?void 0:t.socketJoined)===!0},la=new WeakMap,ua=new WeakMap,Go=new WeakMap,HS);op=cD([pt("0700")],op);var dD=Object.defineProperty,lD=Object.getOwnPropertyDescriptor,uD=(s,t,e,r)=>{for(var i=r>1?void 0:r?lD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&dD(t,e,i),i};const Jn=(qS=class{constructor(s,t,e){p(this,"polls");m(this,ti,void 0);m(this,ha,void 0);m(this,zi,void 0);this.polls=new op(s,t,e),f(this,ha,t),f(this,ti,s),f(this,zi,e),this.setupEvents()}get telemetry(){return a(this,ti).getValue("telemetry")}get logger(){return a(this,ti).getValue("logger")}static async init(s,t,e){return new Jn(s,t,e)}canViewPolls(){return a(this,ha).permissions.polls.canView}setupEvents(){const s={[cr.createPoll]:r=>{r.poll&&this.updatePoll(Jn.formatSocketServicePoll(r.poll))},[cr.updatePoll]:r=>{r.poll&&this.updatePoll(Jn.formatSocketServicePoll(r.poll))},[cr.votePoll]:r=>{r.poll&&this.updatePoll(Jn.formatSocketServicePoll(r.poll))}},t=()=>{a(this,ti).getValue("peerSessionStore").on(P.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,zi).on(r,s[r])})},e=()=>{a(this,ti).getValue("peerSessionStore").on(P.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,zi).removeListeners(r)})};a(this,ha).permissions.on("permissionsUpdate",async r=>{var i;r!=null&&r.polls&&((i=r==null?void 0:r.polls)!=null&&i.canView?(await this.getPolls(),t()):(this.polls.items=[],e()))}),this.canViewPolls()&&t()}updatePoll(s){if(!this.canViewPolls())return;const t=this.polls.items.findIndex(e=>e.id===s.id);if(t>-1){const e=JSON.stringify(this.polls.items[t]);this.polls.items[t]=s,e!==JSON.stringify(s)&&this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!1});return}this.polls.items=[...this.polls.items,s],this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!0})}async getPolls(){const s=await a(this,zi).getPolls();if(!(s!=null&&s.payload))return;const{polls:t}=CO.fromBinary(s.payload);this.polls.items=t.map(e=>Jn.formatSocketServicePoll(e))}static formatSocketServicePoll(s){const t=s.options.map(e=>({count:e.count,text:e.text,votes:e.votes.map(r=>({id:r.userId,name:r.name}))}));return{anonymous:s.anonymous,createdBy:s.createdBy,createdByUserId:s.createdByUserId,hideVotes:s.hideVotes,id:s.pollId,options:t,question:s.question,voted:s.votes}}},ti=new WeakMap,ha=new WeakMap,zi=new WeakMap,qS);let Iv=Jn;uD([E.trace("PollController.setupEvents")],Iv.prototype,"setupEvents",1);var hD=Object.defineProperty,pD=Object.getOwnPropertyDescriptor,mD=(s,t,e,r)=>{for(var i=r>1?void 0:r?pD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&hD(t,e,i),i};const Sl=Symbol("ApplyRemoteTitleSync");var Av=(s=>(s[s.User=0]="User",s[s.Meeting=1]="Meeting",s))(Av||{});let cp=(jS=class extends Bt{constructor(t,e,r,i,n){const o=t.getValue("logger");super(o);m(this,Wo);p(this,"selfActiveTab");p(this,"broadcastTabChanges");m(this,Yi,void 0);m(this,yr,void 0);m(this,pa,void 0);p(this,"viewType");p(this,"meetingStartedTimestamp");p(this,"meetingTitle");p(this,"sessionId");f(this,Yi,t),f(this,yr,e),this.viewType=r,f(this,pa,i),this.meetingTitle=n,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return a(this,Wo,zp).socketState}get mediaState(){return a(this,Wo,zp).mediaState}[Sl](t){this.meetingTitle=t,this.emit("meetingTitleUpdate",{meetingTitle:t})}get meetingId(){return a(this,Yi).getValue("meetingId")}async setMeetingTitle(t){var i,n,o;const e=(i=a(this,Yi).getValue("meeting"))==null?void 0:i.connectedMeetings;if(((n=e==null?void 0:e.parentMeeting)==null?void 0:n.id)&&(e!=null&&e.isActive)){if(!((o=a(this,yr).permissions.connectedMeetings)!=null&&o.canAlterConnectedMeetings))throw this.logger.error("Meta::setMeetingTitle::permission_denied"),new C("User does not have permission to edit the meeting title","0801");await e.updateMeetings([{id:this.meetingId,title:t}]);return}if(!a(this,yr).permissions.canEditMeetingTitle)throw this.logger.error("Meta::setMeetingTitle::permission_denied"),new C("User does not have permission to edit the meeting title","0801");await a(this,pa).updateRoomTitle(t)}setBroadcastTabChanges(t){if(!a(this,yr).permissions.canSpotlight)throw this.logger.error("Spotlight::setSpotlighted::permission_denied"),new C("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;this.logger.info("Spotlight::setActiveTab",{spotlight:{currentTab:{id:t.id,type:t.type}}}),this.selfActiveTab=t,e===0&&this.emit("selfTabUpdate",t),(r=a(this,yr).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){a(this,pa).broadcastMessage("spotlight",{userId:a(this,yr).userId,currentTab:this.selfActiveTab})}},Yi=new WeakMap,Wo=new WeakSet,zp=function(){return a(this,Yi).getValue("connectionHandler")},yr=new WeakMap,pa=new WeakMap,jS);cp=mD([pt("0800")],cp);function gD(s){let t="",e=[""];const r=[e];let i=0,n=0,o=!0,c;for(c of s)c==='"'?(o&&c===t&&(e[i]+=c),o=!o):c===","&&o?c=e[++i]="":c===`
|
|
13
|
+
`&&o?(t==="\r"&&(e[i]=e[i].slice(0,-1)),e=r[++n]=[c=""],i=0):e[i]+=c,t=c;return r}var fD=Object.defineProperty,vD=Object.getOwnPropertyDescriptor,Mv=(s,t,e,r)=>{for(var i=r>1?void 0:r?vD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&fD(t,e,i),i};let Li=(GS=class extends Bt{constructor(t){const e=t.getValue("logger");super(e);p(this,"transcripts");m(this,Jo,void 0);f(this,Jo,t),this.transcripts=[]}get telemetry(){return a(this,Jo).getValue("telemetry")}static async init(t,e){const r=new Li(t),i=t.getValue("logger");try{e&&r.getActiveTranscript()}catch(n){i.error("Error fetching active transcriptions ",n)}return r}static parseTranscript(t,e=!1){if(!t)return;const[[r,i,n,o,c,d]]=gD(t);return{id:Ci(),name:c,peerId:i,userId:n,customParticipantId:o,transcript:d,isPartialTranscript:e,date:new Date(parseInt(r,10)*1e3)}}static parseTranscripts(t){return t?t.split(`
|
|
14
|
+
`).map(e=>Li.parseTranscript(e,!1)).filter(Boolean):[]}async getActiveTranscript(){try{const t=Ht(),{transcript:e}=await t.getActiveTranscript();this.transcripts=Li.parseTranscripts(e)}catch(t){}}async onTranscript(t){var r;const e=this.transcripts.filter(({peerId:i})=>i===t.peerId);if((r=e==null?void 0:e.at(-1))!=null&&r.isPartialTranscript){const i=e.at(-1);i.transcript=t.transcript,i.isPartialTranscript=t.isPartialTranscript,this.emit("transcript",i);return}this.transcripts=[...this.transcripts,t],this.emit("transcript",t)}},Jo=new WeakMap,GS);Mv([E.trace("Ai.getActiveTranscript")],Li.prototype,"getActiveTranscript",1),Li=Mv([pt("0000")],Li);var SD=Object.defineProperty,TD=Object.getOwnPropertyDescriptor,yD=(s,t,e,r)=>{for(var i=r>1?void 0:r?TD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&SD(t,e,i),i};const dp=(WS=class{constructor(s,t,e,r,i,n){p(this,"meta");p(this,"ai");m(this,si,void 0);m(this,Qi,void 0);p(this,"aiSocketHandler");m(this,Jt,void 0);f(this,Jt,s),this.meta=new cp(s,t,t.config.viewType,e,n),this.ai=r,f(this,si,t),f(this,Qi,e),this.aiSocketHandler=i,this.setupEvents()}get telemetry(){return a(this,Jt).getValue("telemetry")}get logger(){return a(this,Jt).getValue("logger")}static async init(s,t,e,r,i){const n=await Li.init(s,t.permissions.transcriptionEnabled);return new dp(s,t,e,n,r,i)}conditionallySetActiveTab(s){var t;s!=null&&s.currentTab&&((t=this.meta.selfActiveTab)==null?void 0:t.id)!==s.currentTab.id&&(this.meta.setSelfActiveTab(s.currentTab,Av.Meeting),this.meta.emit("activeTabUpdate",s.currentTab))}setupEvents(){a(this,Jt).getValue("peerSessionStore").on(P.TRANSPORT_STATE_UPDATE,s=>{this.meta.emit("mediaConnectionUpdate",s)}),a(this,Jt).getValue("peerSessionStore").on(P.SOCKET_STATE_UPDATE,s=>{this.meta.emit("socketConnectionUpdate",s)}),a(this,Jt).getValue("peerSessionStore").on(P.ROOM_STATE,({createdAt:s,roomUuid:t,title:e})=>{e&&e!==this.meta.meetingTitle&&this.meta[Sl](e);const r=this.meta.meetingStartedTimestamp;if(t&&(this.meta.sessionId=t),s&&!r){const i=new Date(s*1e3);this.meta.meetingStartedTimestamp=i,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),a(this,Jt).getValue("peerSessionStore").on(P.PRODUCER_SCORE_UPDATE,({score:s})=>{s<5&&this.meta.emit("poorConnection",{score:s})}),a(this,si).permissions.canSpotlight&&this.meta.selfActiveTab&&(this.logger.info("Asserting Spotlight status to other peers."),a(this,Qi).broadcastMessage("spotlight",{userId:a(this,si).userId,currentTab:this.meta.selfActiveTab})),a(this,Jt).getValue("peerSessionStore").on(P.PEER_JOINED_INTERNAL,async s=>{a(this,si).permissions.canSpotlight&&this.meta.selfActiveTab&&a(this,Qi).broadcastToPeers("spotlight",[s.id],{userId:a(this,si).userId,currentTab:this.meta.selfActiveTab})}),a(this,Jt).getValue("peerSessionStore").on(P.ROOM_MESSAGE,s=>{var e,r;let t;if("type"in s){if(s.type!=="spotlight")return;t={...s,...s.payload}}else if("roomMessageType"in s){if(s.roomMessageType!=="spotlight")return;t=s}else return;this.logger.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:t.userId},currentTab:{id:(e=t.currentTab)==null?void 0:e.id,type:(r=t.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(t)}),a(this,Jt).getValue("peerSessionStore").on(P.MESSAGE,s=>{var e,r;let t;if("type"in s){if(s.type!=="spotlight")return;t={...s,...s.payload}}else if("roomMessageType"in s){if(s.roomMessageType!=="spotlight")return;t=s}else return;this.logger.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:t.userId},currentTab:{id:(e=t.currentTab)==null?void 0:e.id,type:(r=t.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(t)}),a(this,Qi).on(x.updateRoomInfo,s=>{var e;const t=(e=s==null?void 0:s.room)==null?void 0:e.title;!t||t===this.meta.meetingTitle||this.meta[Sl](t)}),this.aiSocketHandler.on(x.transcript,s=>{let t;try{t=dp.extractSocketTranscript(s)}catch(e){this.logger.error("Failed to parse transcript socket message.",{error:e});return}if(!t){this.logger.warn("Received empty transcript data");return}this.ai.onTranscript(t)})}static extractSocketTranscript(s){return s?{id:Ci(),name:s.speaker.displayName,peerId:s.speaker.peerId,userId:s.speaker.participantId,customParticipantId:s.speaker.customParticipantId,transcript:s.sentence,isPartialTranscript:s.isPartial||!1,date:new Date(s.startedAt*1e3)}:void 0}},si=new WeakMap,Qi=new WeakMap,Jt=new WeakMap,WS);let Ov=dp;yD([E.trace("MetaController.setupEvents")],Ov.prototype,"setupEvents",1);const Po={},ur={executeWithLock({methodName:s,lockName:t,timeout:e}){return(r,i,n)=>{const o=n.value;return n.value=function(...d){var y,k;const l=(k=(this==null?void 0:this.peerId)||((y=d[0])==null?void 0:y.authToken))!=null?k:"",u=`${t}-${l}`,h=this==null?void 0:this.logger;if(Po[u]){const I=new Error(`Unsupported concurrent calls on method: ${s}.`);throw I.name="UnsupportedConcurrentMethodExecution",h==null||h.error("Locker::UnsupportedConcurrentMethodExecution",{error:{stack:I.stack},locker:{methodName:s,lockName:u}}),I}Po[u]=!0;const g=setTimeout(()=>delete Po[u],e),v=o.apply(this,d);return Promise.resolve(v).then(()=>{delete Po[u],clearTimeout(g)}).catch(()=>{delete Po[u],clearTimeout(g)}),v},n}}};var ED=Object.defineProperty,bD=Object.getOwnPropertyDescriptor,Vi=(s,t,e,r)=>{for(var i=r>1?void 0:r?bD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ED(t,e,i),i};class Wr extends Bt{constructor(e,r,i,n,o){const c=e.getValue("logger");super(c);m(this,zo);m(this,ma);m(this,ds,void 0);m(this,eu,void 0);m(this,le,void 0);m(this,Ko,void 0);m(this,Us,void 0);m(this,Qe,void 0);f(this,Qe,e),f(this,ds,n),f(this,eu,o),f(this,le,r),f(this,Ko,i),f(this,Us,[]),this.setupEvents()}get telemetry(){return a(this,Qe).getValue("telemetry")}get status(){return a(this,Qe).getValue("stageStatus")}setupEvents(){const e={[P.GET_STAGE_REQUESTS]:async n=>{f(this,Us,n)},[P.UPDATE_STAGE_REQUESTS]:async({add:n})=>{const o=a(this,Us).length,{stageRequests:c}=this.getAccessRequests();(n||c.length>o)&&this.emit("newStageRequest",{count:c.length}),this.emit("stageAccessRequestUpdate",c)}},r=()=>{Object.entries(e).forEach(([n,o])=>{a(this,Qe).getValue("peerSessionStore").onAsync(n,o)})},i=()=>{Object.entries(e).forEach(([n,o])=>{a(this,Qe).getValue("peerSessionStore").removeListener(n,o)})};a(this,le).permissions.on("permissionsUpdate",n=>{const{canAcceptProductionRequests:o}=n;o!==void 0&&(a(this,le).permissions.acceptStageRequests?(r(),a(this,ds).getStageRequests()):(i(),f(this,Us,[]),this.emit("stageAccessRequestUpdate",a(this,Us))))}),a(this,le).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!a(this,le).permissions.acceptStageRequests)throw this.logger.error("Stage::get_access_request::permission_denied"),new C("You do not have permission to perform this action","2001");const e=a(this,Ko).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return f(this,Us,e),{stageRequests:a(this,Us)}}async requestAccess(){if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(this.status!=="OFF_STAGE")throw new C(`Unable to request access you are currently ${this.status}`,"2006");if(a(this,le).permissions.stageAccess===G.Allowed){R(this,ma,th).call(this,"ACCEPTED_TO_JOIN_STAGE");return}a(this,ds).requestAccess(),R(this,ma,th).call(this,"REQUESTED_TO_JOIN_STAGE")}async cancelRequestAccess(){if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");a(this,ds).cancelRequestAccess(),R(this,ma,th).call(this,"OFF_STAGE")}grantAccess(e){if(!a(this,le).roomJoined)throw new C("Can`t grant for participant without joining room");if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!a(this,le).permissions.acceptStageRequests)throw this.logger.error("Stage::grant_access::permission_denied"),new C("You do not have permission to perform this action","2001");return a(this,ds).grantAccess(e)}denyAccess(e){if(!a(this,le).roomJoined)throw new C("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!a(this,le).permissions.acceptStageRequests)throw this.logger.error("Stage::deny_access::permission_denied"),new C("You do not have permission to perform this action","2001");return a(this,ds).denyAccess(e)}get peerId(){return a(this,Qe).getValue("peerId")}async join(){const e=a(this,Qe).getValue("viewType");if(this.status==="ON_STAGE")throw new C("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||a(this,le).permissions.stageAccess===G.NotAllowed)throw new C(`Unable to join stage you are currently ${this.status}`,"2006");if(a(this,Qe).setValue("stageStatus","ON_STAGE",!1),await a(this,ds).joinStage(),e===Ss.Livestream){await a(this,Qe).getValue("selfController").joinRoom();return}a(this,Qe).notify("stageStatus"),a(this,le).audioEnabled&&a(this,zo,Yp).shareMic(a(this,le).audioTrack),a(this,le).videoEnabled&&a(this,zo,Yp).shareWebcam(a(this,le).videoTrack)}async leave(){if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new C(`Unable to leave stage you are currently ${this.status}`,"2006");a(this,le).setIsPinned(!1),a(this,Qe).setValue("stageStatus","OFF_STAGE",!1),await a(this,ds).leaveStage(a(this,le).userId);try{await a(this,Qe).getValue("peerSessionStore").emitAsync(P.LEAVE_MEDIA_ROOM,"stageLeft")}catch(e){this.logger.error("Stage::leave::emitAsync::failed",{error:e})}a(this,Qe).notify("stageStatus")}async kick(e){if(!a(this,le).roomJoined)throw new C("Can`t kick participant without joining room","2005");if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!a(this,le).permissions.acceptStageRequests)throw this.logger.error("Stage::kick::permission_denied"),new C("You do not have permissions for kick","2001");return a(this,ds).kick(e)}}ds=new WeakMap,eu=new WeakMap,le=new WeakMap,Ko=new WeakMap,Us=new WeakMap,Qe=new WeakMap,zo=new WeakSet,Yp=function(){return a(this,Qe).getValue("roomNodeClient")},ma=new WeakSet,th=async function(e){this.status!==e&&a(this,Qe).setValue("stageStatus",e)},Vi([E.trace("Stage.getStageRequests")],Wr.prototype,"getAccessRequests",1),Vi([E.trace("Stage.requestAccess")],Wr.prototype,"requestAccess",1),Vi([E.trace("Stage.cancelRequestAccess")],Wr.prototype,"cancelRequestAccess",1),Vi([E.trace("Stage.grantAccess")],Wr.prototype,"grantAccess",1),Vi([E.trace("Stage.denyAccess")],Wr.prototype,"denyAccess",1),Vi([ur.executeWithLock({methodName:"joinStage",lockName:"Stage.join",timeout:5e3}),E.trace("Stage.joinStage")],Wr.prototype,"join",1),Vi([E.trace("Stage.leaveStage")],Wr.prototype,"leave",1);function wD(s){return!(s.viewType==="LIVESTREAM"||s.viewType==="CHAT")}function lp(s){switch(s){case ar.UNSPECIFIED:return"OFF_STAGE";case ar.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case ar.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case ar.OFF_STAGE:return"OFF_STAGE";case ar.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var PD=Object.defineProperty,kD=Object.getOwnPropertyDescriptor,_D=(s,t,e,r)=>{for(var i=r>1?void 0:r?kD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&PD(t,e,i),i};class Dv{constructor(t,e,r,i,n){p(this,"stage");m(this,ri,void 0);m(this,Ps,void 0);m(this,ii,void 0);m(this,Yo,0);m(this,Et,void 0);f(this,Et,t),this.stage=new Wr(t,i,n,e,r),f(this,ii,e),f(this,ri,i),f(this,Ps,n),this.setupEvents()}get telemetry(){return a(this,Et).getValue("telemetry")}get logger(){return a(this,Et).getValue("logger")}setupEvents(){a(this,Et).subscribe("stageStatus",t=>{this.stage.emit("stageStatusUpdate",t)}),a(this,ii).on(x.grantStageAccess,()=>{a(this,ri).permissions.stageAccess!==G.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),a(this,ii).on(x.peerStageStatusUpdate,t=>{t!==void 0&&(t.peerId===a(this,ri).id?this.selfStageStatusHandler(t):this.peerStageStatusHandler(t))}),a(this,ii).on(x.denyStageAccess,()=>{a(this,ri).permissions.stageAccess!==G.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),a(this,ii).on(x.getStageRequests,async t=>{var r;if(a(this,ri).permissions.stageAccess!==G.Allowed)return;const e=(r=t==null?void 0:t.stageRequests)!=null?r:[];await a(this,Et).getValue("peerSessionStore").emitAsync(P.GET_STAGE_REQUESTS,e),a(this,Yo)<e.length&&e.length>0&&this.stage.emit("newStageRequest",{count:e.length}),f(this,Yo,e.length),this.stage.emit("stageAccessRequestUpdate",e)})}getCurrentStageRequests(){return a(this,Ps).joined.toArray().filter(e=>e.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(e=>({displayName:e.name,userId:e.userId,peerId:e.id}))}async setStageStatus(t){this.stage.status!==t&&a(this,Et).setValue("stageStatus",t)}selfStageStatusHandler(t){const e=lp(t.stageType),r=a(this,Et).getValue("stageStatus");if(r!==e)switch(t.stageType){case 1:a(this,Et).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(r);break;case 0:case 4:default:a(this,Et).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}async peerStageStatusHandler(t){const e=a(this,Ps).joined.get(t.peerId),r=a(this,Ps).viewMode==="ACTIVE_GRID";if(!e){this.logger.warn("err::peerStageStatusUpdate: participant not found");return}switch(t.stageType){case 1:e.setStageStatus("ON_STAGE"),r&&a(this,Et).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:a(this,Ps).viewMode,page:a(this,Ps).currentPage});break;case 2:e.setStageStatus("ACCEPTED_TO_JOIN_STAGE");break;case 3:e.setStageStatus("REQUESTED_TO_JOIN_STAGE");break;case 0:case 4:default:e.setStageStatus("OFF_STAGE"),r&&a(this,Et).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:a(this,Ps).viewMode,page:a(this,Ps).currentPage});break}a(this,Et).getValue("peerSessionStore").emit(P.UPDATE_PEER_STAGE_STATUS,{id:e.id,status:e.stageStatus})}}ri=new WeakMap,Ps=new WeakMap,ii=new WeakMap,Yo=new WeakMap,Et=new WeakMap,_D([E.trace("Stage.setupEvents")],Dv.prototype,"setupEvents",1);var CD=Object.defineProperty,RD=Object.getOwnPropertyDescriptor,up=(s,t,e,r)=>{for(var i=r>1?void 0:r?RD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&CD(t,e,i),i};let ko=(JS=class extends Bn{constructor(t,e,r,i){const n=t.getValue("logger");super(n);p(this,"name");p(this,"icon");p(this,"id");p(this,"permissions");m(this,Xi,void 0);m(this,Er,void 0);m(this,Qo,void 0);m(this,Xo,void 0);m(this,Zi,void 0);p(this,"active");p(this,"enabledBy");f(this,Qo,t);const o=t.getValue("meetingId");this.id=`${o}:${e.id}`,this.name=e.name,this.icon=e.icon,f(this,Xo,e.component),this.permissions=e.permissions,f(this,Xi,i),f(this,Er,r),this.active=!1,this.enabledBy=""}get component(){return a(this,Xo)}get telemetry(){return a(this,Qo).getValue("telemetry")}set activePluginsStore(t){f(this,Er,t)}activateForSelf(){f(this,Zi,new Date),this.active=!0,this.emit("stateUpdate",{active:this.active,pluginId:this.id}),this.emit("enabled")}deactivateForSelf(){f(this,Zi,void 0),this.active=!1,this.emit("stateUpdate",{active:this.active,pluginId:this.id}),this.emit("closed")}async activate(){var t;if(!this.active&&(t=this.permissions)!=null&&t.canActivate){if(!a(this,Er))throw new C("Cannot activate plugin: active plugins store is not available yet.","0604");await a(this,Er).set(this.id,{name:this.name,icon:this.icon,id:this.id,enabledBy:a(this,Xi).id}),this.enabledBy=a(this,Xi).id,this.activateForSelf(),this.logger.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}})}}async deactivate(){var e;if(!this.active||!((e=this.permissions)!=null&&e.canDeactivate)&&this.enabledBy!==a(this,Xi).id)return;if(!a(this,Er))throw new C("Cannot deactivate plugin: active plugins store is not available yet.","0604");const t=a(this,Zi)?new Date().getTime()-a(this,Zi).getTime():0;await a(this,Er).set(this.id,null),this.deactivateForSelf(),this.logger.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:t}})}},Xi=new WeakMap,Er=new WeakMap,Qo=new WeakMap,Xo=new WeakMap,Zi=new WeakMap,JS);up([E.trace("Plugin.activatePlugin")],ko.prototype,"activate",1),up([E.trace("Plugin.deactivatePlugin")],ko.prototype,"deactivate",1),ko=up([pt("0600")],ko);class Nv extends Map{constructor(e,r=void 0){const{onAddEvent:i,onDeleteEvent:n,onClearEvent:o}=e;super();m(this,Be,void 0);m(this,en,void 0);p(this,"onAddEvent");p(this,"onDeleteEvent");p(this,"onClearEvent");f(this,Be,new Bn(r)),this.onAddEvent=i,this.onDeleteEvent=n,this.onClearEvent=o,f(this,en,new Map)}emit(e,...r){return a(this,Be).emit(e,...r)}on(e,r){return a(this,Be).on(e,r)}addListener(e,r){return a(this,Be).addListener(e,r)}off(e,r){return a(this,Be).off(e,r)}once(e,r){return a(this,Be).once(e,r)}prependListener(e,r){return a(this,Be).prependListener(e,r)}prependOnceListener(e,r){return a(this,Be).prependOnceListener(e,r)}removeListener(e,r){return a(this,Be).removeListener(e,r)}removeAllListeners(e){return a(this,Be).removeAllListeners(e)}listeners(e){return a(this,Be).listeners(e)}listenerCount(e){return a(this,Be).listenerCount(e)}getMaxListeners(){return a(this,Be).getMaxListeners()}setMaxListeners(e){return a(this,Be).setMaxListeners(e)}eventNames(){return a(this,Be).eventNames()}add(e,r=!0){return this.set(e.id,e,r)}set(e,r,i=!0){const n=super.set(e,r),o=(c,...d)=>{this.emit(c,r,...d)};return a(this,en).set(e,o),r.on("*",o),i&&a(this,Be).emit(this.onAddEvent,r),n}delete(e,r=!0,i=!1){const n=this.get(e);if(!n)return!1;n.removeListener("*",a(this,en).get(e));const o=super.delete(e);return i&&n.removeAllListeners(),r&&a(this,Be).emit(this.onDeleteEvent,n),o}clear(e=!0,r=!1){this.forEach(n=>{n.removeListener("*",a(this,en).get(n.id)),r&&n.removeAllListeners()});const i=super.clear();return e&&a(this,Be).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}Be=new WeakMap,en=new WeakMap;class Lv extends Nv{constructor(t){super({onAddEvent:"pluginAdded",onDeleteEvent:"pluginDeleted"},t)}add(t,e=!0){return super.add(t,e)}delete(t,e=!0,r=!1){return super.delete(t,e,r)}}var ID=Object.defineProperty,AD=Object.getOwnPropertyDescriptor,MD=(s,t,e,r)=>{for(var i=r>1?void 0:r?AD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ID(t,e,i),i};let hp=class{constructor(s){p(this,"all");p(this,"active");this.all=new Lv(s),this.active=new Lv(s)}};hp=MD([pt("0600")],hp);var OD=Object.defineProperty,DD=Object.getOwnPropertyDescriptor,ND=(s,t,e,r)=>{for(var i=r>1?void 0:r?DD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&OD(t,e,i),i};const Vv=(KS=class{constructor(s,t,e,r){m(this,tu);m(this,Zo);m(this,ec);m(this,tc);p(this,"plugins");m(this,ks,void 0);m(this,ga,void 0);m(this,ni,void 0);m(this,tn,null);f(this,ni,s),this.plugins=t,f(this,ga,e),f(this,ks,r),this.setupEvents()}get telemetry(){return a(this,ni).getValue("telemetry")}get logger(){return a(this,ni).getValue("logger")}static async init(s,t,e,r){var l,u;const i=s.getValue("logger"),n=s.getValue("connectionHandler"),o=new hp(i);let c;n.socketState.state==="connected"?(i.info("Creating active plugins store immediately. Socket is already connected."),c=await r.create(Nh,!0)):i.info("Deferring active plugins store creation until socket connects."),t.forEach(h=>{const g=new ko(s,h,c,e);o.all.add(g)});const d=new Vv(s,o,r,c);return c?R(l=d,tc,Zp).call(l):R(u=d,tu,oT).call(u),d}cleanup(){R(this,Zo,Qp).call(this)}setupEvents(){this.plugins.all.on("stateUpdate",({active:s,id:t})=>{if(s){this.plugins.active.add(this.plugins.all.get(t));return}this.plugins.active.delete(t)}),a(this,ni).getValue("peerSessionStore").onAsync(P.SOCKET_SERVICE_ROOM_JOINED,async()=>{var t,e;if(((e=(t=this.plugins.active)==null?void 0:t.toArray())!=null?e:[]).forEach(r=>{r.deactivateForSelf()}),!a(this,ks)){this.logger.warn("Active plugins store not available yet on ROOM_JOINED. Sync will be performed when store is created.");return}await R(this,ec,Xp).call(this),this.logger.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to sync active plugins.")})}},ks=new WeakMap,ga=new WeakMap,ni=new WeakMap,tn=new WeakMap,tu=new WeakSet,oT=function(){const s=a(this,ni).getValue("peerSessionStore"),t=async e=>{if(e.state==="connected"&&!a(this,ks))try{f(this,ks,await a(this,ga).create(Nh,!0)),R(this,Zo,Qp).call(this),this.plugins.all.toArray().forEach(r=>{r.activePluginsStore=a(this,ks)}),R(this,tc,Zp).call(this),this.logger.info("Active plugins store created after socket connected"),await R(this,ec,Xp).call(this)}catch(r){this.logger.error("Failed to create active plugins store after socket connected, will retry on next reconnect",{error:r})}};s.on(P.SOCKET_STATE_UPDATE,t),f(this,tn,()=>{s.off(P.SOCKET_STATE_UPDATE,t)})},Zo=new WeakSet,Qp=function(){a(this,tn)&&(a(this,tn).call(this),f(this,tn,null))},ec=new WeakSet,Xp=async function(){try{await a(this,ga).refresh(a(this,ks).name)}catch(t){this.logger.error("Failed to refresh active plugins store, syncing from stale data.",{error:t})}const s=a(this,ks).getAll();Object.entries(s).forEach(([t,e])=>{if(!e)return;const r=this.plugins.all.get(t);if(!r){this.logger.warn(`Plugin '${t}' not found in plugins.all, ignoring store entry.`);return}r.active||(r.enabledBy=e.enabledBy,r.activateForSelf())})},tc=new WeakSet,Zp=function(){a(this,ks).subscribe("*",s=>{Object.entries(s).forEach(([t,e])=>{const r=this.plugins.all.get(t);if(!r){this.logger.warn(`Plugin '${t}' not found in plugins.all, ignoring store update.`);return}!e&&r.active&&r.deactivateForSelf(),e&&!r.active&&(r.enabledBy=e.enabledBy,r.activateForSelf())})})},KS);let xv=Vv;ND([E.trace("PluginController.setupEvents")],xv.prototype,"setupEvents",1);class LD{constructor(t){p(this,"mediaJoined");p(this,"socketJoined");p(this,"socketJoinAttempted");p(this,"mediaJoinAttempted");p(this,"socketState");p(this,"mediaState");m(this,sc,void 0);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},f(this,sc,t)}get joinAttempted(){return this.mediaJoinAttempted||this.socketJoinAttempted}get roomJoined(){return this.mediaJoined&&this.socketJoined}updateSocketConnectionState(t,e){let r;const{reconnected:i}=this.socketState;switch(t){case"connected":r={state:"connected",reconnected:i,reconnectionAttempt:void 0};break;case"disconnected":r={state:"disconnected",reconnected:!1,reconnectionAttempt:0},this.socketJoined=!1;break;case"reconnected":r={state:"connected",reconnected:!0,reconnectionAttempt:void 0};break;case"reconnecting":r={state:"reconnecting",reconnected:i,reconnectionAttempt:0};break;case"reconnectAttempt":r={state:"reconnecting",reconnected:i,reconnectionAttempt:e};break;case"failed":r={state:"failed",reconnected:i,reconnectionAttempt:void 0},this.socketJoined=!1;break}r&&(this.socketState=r,a(this,sc).getValue("peerSessionStore").emit(P.SOCKET_STATE_UPDATE,r))}}sc=new WeakMap;var VD=Object.defineProperty,xD=Object.getOwnPropertyDescriptor,_o=(s,t,e,r)=>{for(var i=r>1?void 0:r?xD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&VD(t,e,i),i};const $v="Cannot start recording: another recording is already in progress.";let xi=(zS=class extends Bt{constructor(t,e){const r=t.getValue("logger");super(r);m(this,Sa);m(this,fa,void 0);m(this,va,void 0);p(this,"recordingPeerIds",[]);p(this,"recordings",[]);f(this,va,t),f(this,fa,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"}get telemetry(){return a(this,va).getValue("telemetry")}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}async start(t){if(!a(this,fa).permissions.canRecord)throw this.logger.error("Recording::start::permission_denied"),new C("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 this.logger.error("Recording::start::recording_in_progress",{recording:{state:this.recordingState}}),new C($v,"1005");try{const e=Ht(),{recording:r={}}=a(this,va).getValue("defaults"),i=await e.startRecording(r,t==null?void 0:t.allowMultiple);this.updateRecordings([...this.recordings,{id:i,state:"STARTING",type:"BROWSER"}])}catch(e){throw this.logger.error("Recording::start::recording_failed_to_start",{error:e}),e instanceof fl&&e.status===409?new C($v,"1005"):new C("Error while starting recording","1000",this.logger)}}async stop(t){await R(this,Sa,sh).call(this,"stop",["RECORDING","PAUSED"],t)}async pause(t){await R(this,Sa,sh).call(this,"pause",["RECORDING"],t)}async resume(t){await R(this,Sa,sh).call(this,"resume",["PAUSED"],t)}},fa=new WeakMap,va=new WeakMap,Sa=new WeakSet,sh=async function(t,e,r){if(!a(this,fa).permissions.canRecord)throw this.logger.error("Recording::stop::permission_denied"),new C("User does not have permission to stop recording","1001");let i=[];if(r!==void 0){const n=this.recordings.find(o=>o.id===r);if(n===void 0)throw new C("Could not find the specified recording","1004");if(e.includes(n.state)){this.logger.error("Recording::stop::recording_not_in_expected_state",{recording:{state:n.state}});return}i.push(n)}else i=this.recordings.filter(n=>e.includes(n.state));i.forEach(async n=>{const o=n.state;t==="stop"&&(n.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{await Ht().updateRecording(n.id,t)}catch(c){throw this.logger.error("Recording::stop::recording_failed_to_stop",{error:c}),n.state!==o&&(n.state=o,this.emit("recordingUpdate",o)),new C("Error while stopping recording","1000",this.logger)}})},zS);_o([E.trace("Recording.start")],xi.prototype,"start",1),_o([E.trace("Recording.stop")],xi.prototype,"stop",1),_o([E.trace("Recording.stop")],xi.prototype,"pause",1),_o([E.trace("Recording.stop")],xi.prototype,"resume",1),xi=_o([pt("1000")],xi);var $D=Object.defineProperty,UD=Object.getOwnPropertyDescriptor,BD=(s,t,e,r)=>{for(var i=r>1?void 0:r?UD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&$D(t,e,i),i};class Uv{constructor(t,e,r){p(this,"recording");p(this,"room");m(this,sn,void 0);f(this,sn,t),this.recording=new xi(t,e),this.room=r,this.setupEvents()}get telemetry(){return a(this,sn).getValue("telemetry")}get logger(){return a(this,sn).getValue("logger")}getRecordingTypeFromProtoType(t){let e;switch(t){case Ni.BROWSER:e="BROWSER";break;case Ni.COMPOSITE:e="COMPOSITE";break;case Ni.TRACK:e="TRACK";break;default:e="BROWSER"}return e}setupEvents(){a(this,sn).getValue("peerSessionStore").on(P.ROOM_STATE,t=>{t.activeRecordings.length!==0?this.recording.updateRecordings(t.activeRecordings.map(e=>{const r=this.getRecordingTypeFromProtoType(e.recordingType);return{id:e.recordingId,state:e.recordingStatus,type:r}})):this.recording.recordings.length&&this.recording.updateRecordings([])}),this.room.on(x.recordingStarted,t=>{let e=!1;const r=[...this.recording.recordings];if(r.forEach(i=>{i.id===t.recordingId&&(e=!0,i.state="RECORDING")}),e===!1){const i=this.getRecordingTypeFromProtoType(t.recordingType);r.push({id:t.recordingId,state:"RECORDING",type:i})}this.recording.updateRecordings(r)}),this.room.on(x.recordingPaused,t=>{const e=[...this.recording.recordings];e.forEach(r=>{r.id===t.recordingId&&(r.state="PAUSED")}),this.recording.updateRecordings(e)}),this.room.on(x.recordingStopped,t=>{const e=[...this.recording.recordings.filter(r=>r.id!==t.recordingId)];this.recording.updateRecordings(e)})}}sn=new WeakMap,BD([E.trace("RecordingController.setupEvents")],Uv.prototype,"setupEvents",1);class FD{constructor(t){m(this,rn,void 0);f(this,rn,t)}hasFeature(t){return a(this,rn).getValue("logger").warn("Unimplemented method: meeting.__internals__.hasFeature called"),!1}getFeatureValue(t){return a(this,rn).getValue("logger").warn("Unimplemented method: meeting.__internals__.getFeatureValue called"),null}getAllFeatures(){return a(this,rn).getValue("logger").warn("Unimplemented method: meeting.__internals__.getAllFeatures called"),{}}}rn=new WeakMap;const jp=class{constructor(t){m(this,rc,void 0);p(this,"authToken");p(this,"logger");p(this,"features");p(this,"browserSpecs");p(this,"callStats");f(this,rc,t),this.authToken=t.getValue("authToken"),this.logger=t.getValue("logger"),this.features=new FD(t),this.browserSpecs=Pe,this.callStats=t.getValue("callstats")}setUiKitMetadata(t){a(this,rc).getValue("telemetry").setUiKitMetadata(t)}static init(t){return new jp(t)}};let pp=jp;rc=new WeakMap;class mp{constructor(t){p(this,"internals");this.internals=t}static async init(t){const e=pp.init(t);return new mp(e)}}var HD=Object.defineProperty,qD=Object.getOwnPropertyDescriptor,jt=(s,t,e,r)=>{for(var i=r>1?void 0:r?qD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&HD(t,e,i),i};class Dt extends Bn{constructor(e,r,i=yl,n=!0){const o=e.getValue("logger");super(o);m(this,Ge,void 0);m(this,Ce,void 0);m(this,be,void 0);m(this,br,void 0);m(this,ls,void 0);m(this,ic,void 0);m(this,Ve,void 0);p(this,"audioUpdateInProgress");p(this,"videoUpdateInProgress");f(this,Ve,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,f(this,Ge,new Wv(e,r)),f(this,Ce,new S1(e,a(this,Ge),void 0,i)),f(this,be,new k1(e,a(this,Ge),void 0,i)),f(this,ls,new b1(a(this,Ve),a(this,Ge))),f(this,br,new y1(e,a(this,Ge))),f(this,ic,n),a(this,Ce).on("trackMuted",this.onAudioTrackMuted.bind(this)),a(this,Ce).on("trackChanged",this.onAudioTrackChanged.bind(this)),a(this,be).on("trackChanged",this.onVideoTrackChanged.bind(this)),a(this,be).on("trackEnded",this.onVideoTrackEnded.bind(this)),a(this,ls).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}get telemetry(){return a(this,Ve).getValue("telemetry")}set context(e){f(this,Ve,e)}async onVisibilityChange(){a(this,Ve).getValue("callstats").tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?a(this,Ve).getValue("callstats").browserBackgrounded():(a(this,Ve).getValue("callstats").browserForegrounded(),await this.setupSpeaker())}async repopulateAvailableDevices(){return!0}async setupStreams({audio:e,video:r}){var o;e?a(this,Ve).getValue("callstats").audioOn():a(this,Ve).getValue("callstats").audioOff(),r?a(this,Ve).getValue("callstats").videoOn():a(this,Ve).getValue("callstats").videoOff();let i,n;if(e&&r)try{const c=await a(this,Ge).getAudioAndVideoTrack(a(this,Ce).userSelectedDevice,a(this,be).userSelectedDevice);i=c.audioTrack,n=c.videoTrack}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:c})}if(!i&&e)try{i=await a(this,Ge).getAudioTrack(!1,a(this,Ce).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!n&&r)try{n=await a(this,Ge).getVideoTrack(a(this,be).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get video track",{error:c})}e&&!i&&a(this,Ve).getValue("callstats").audioOff(),r&&!n&&a(this,Ve).getValue("callstats").videoOff(),await a(this,Ce).setMediaTrack(i),await a(this,be).setMediaTrack(n);try{await this.setupSpeaker()}catch(c){}if(n){const c=await this.getDeviceById(n.getSettings().deviceId);a(this,Ve).getValue("callstats").selectedDevice("VIDEO",c)}if(i){const c=await this.getDeviceById(i.getSettings().deviceId);a(this,Ve).getValue("callstats").selectedDevice("AUDIO",c)}(o=a(this,br).currentDevice)!=null&&o.deviceId&&a(this,Ve).getValue("callstats").selectedDevice("SPEAKER",a(this,br).currentDevice),a(this,Ge).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})}getCurrentDevices(){return{audio:a(this,Ce).currentDevice,video:a(this,be).currentDevice,speaker:a(this,br).currentDevice}}get permissions(){return a(this,Ge).permissions}getAllDevices(){return a(this,Ge).getAvailableDevices()}getDeviceById(e,r){return a(this,Ge).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return a(this,Ce).mediaTrack}get audioTrack(){return a(this,Ce).transformedMediaTrack}get audioEnabled(){return a(this,Ce).trackEnabled}async enableAudio(e){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{e?await a(this,Ce).enableTrack(!1,e):await a(this,Ce).unmuteTrack()}catch(r){}finally{this.audioUpdateInProgress=!1}}}disableAudio(){a(this,Ce).mediaTrack&&!a(this,Ce).isCustomTrack?a(this,Ce).muteTrack():a(this,Ce).disableTrack()}getAudioDevices(e){return a(this,Ge).getAudioInputDevices(e)}async setAudioDevice(e,{saveDevicePreference:r}){await a(this,Ce).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Ve).getValue("callstats").selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async setupSpeaker(){const{speaker:e}=this.getCurrentDevices();await a(this,br).setPreferredSpeaker();const{speaker:r}=this.getCurrentDevices();(e==null?void 0:e.deviceId)!==(r==null?void 0:r.deviceId)&&r&&this.emit("DEVICE_CHANGE",{device:r})}async setSpeakerDevice(e,{saveDevicePreference:r}){await a(this,br).setupSpeaker(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Ve).getValue("callstats").selectedDevice("SPEAKER",e),this.emit("DEVICE_CHANGE",{device:e})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return a(this,be).mediaTrack}get videoTrack(){return a(this,be).transformedMediaTrack}get videoEnabled(){return a(this,be).trackEnabled}async enableVideo(e){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{e?await a(this,be).enableTrack(!1,e):await a(this,be).unmuteTrack()}catch(r){}finally{this.videoUpdateInProgress=!1}}}disableVideo(){a(this,be).disableTrack()}getVideoDevices(e){return a(this,Ge).getVideoInputDevices(e)}async setVideoDevice(e,{saveDevicePreference:r}){await a(this,be).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Ve).getValue("callstats").selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async updateVideoConstraints(e){await a(this,be).updateConstraints(e)}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:a(this,ls).audioMediaTrack,video:a(this,ls).videoMediaTrack}}get screenShareEnabled(){return a(this,ls).trackEnabled}async enableScreenShare(){await a(this,ls).enableScreenShare()}async disableScreenShare(){a(this,ls).disableScreenShare()}async updateScreenshareConstraints(e){await a(this,ls).updateConstraints(e)}getSpeakerDevices(e){return a(this,Ge).getAudioOutputDevices(e)}addAudioMiddleware(e){return a(this,Ce).addMiddleware(e)}removeAudioMiddleware(e){return a(this,Ce).removeMiddleware(e)}removeAllAudioMiddlewares(){return a(this,Ce).removeAllMiddlewares()}addVideoMiddleware(e){return a(this,be).addMiddleware(e)}removeVideoMiddleware(e){return a(this,be).removeMiddleware(e)}removeAllVideoMiddlewares(){return a(this,be).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return a(this,be).setVideoMiddlewareGlobalConfig(e)}destruct(){a(this,Ce).disableTrack(),a(this,be).disableTrack(),a(this,be).terminateMiddlewareWebWorker(),a(this,ls).disableScreenShare(),a(this,Ge).destruct()}async onDeviceChange(e,r){var n,o;if(this.emit("DEVICE_LIST_UPDATED",e),r||!a(this,ic))return;let i=!1;(n=e==null?void 0:e.added)==null||n.reverse().forEach(async c=>{var d;c&&!yl(c)&&(c.kind==="audioinput"&&((d=this.audioTrack)==null?void 0:d.enabled)===!0?await this.setAudioDevice(c,{saveDevicePreference:!1}):c.kind==="audiooutput"&&(i=!0,await this.setSpeakerDevice(c,{saveDevicePreference:!1})))}),i||(o=e==null?void 0:e.removed)==null||o.forEach(async c=>{var d;if(c.kind==="audiooutput"&&((d=this.getCurrentDevices().speaker)==null?void 0:d.deviceId)===c.deviceId){const l=await this.getSpeakerDevices();(l==null?void 0:l.length)>0&&await this.setSpeakerDevice(l[0],{saveDevicePreference:!1})}})}removeAllTracks(){this.destruct()}removeAudioTrack(){a(this,Ce).disableTrack()}removeVideoTrack(){a(this,be).disableTrack(),a(this,be).terminateMiddlewareWebWorker()}async removeDocumentEventListeners(){document.removeEventListener("visibilitychange",this.onVisibilityChange)}}Ge=new WeakMap,Ce=new WeakMap,be=new WeakMap,br=new WeakMap,ls=new WeakMap,ic=new WeakMap,Ve=new WeakMap,jt([E.trace("MediaHandler.setupStreams")],Dt.prototype,"setupStreams",1),jt([E.trace("MediaHandler.enableAudio")],Dt.prototype,"enableAudio",1),jt([E.trace("MediaHandler.disableAudio")],Dt.prototype,"disableAudio",1),jt([E.trace("MediaHandler.setAudioDevice")],Dt.prototype,"setAudioDevice",1),jt([E.trace("MediaHandler.enableVideo")],Dt.prototype,"enableVideo",1),jt([E.trace("MediaHandler.disableVideo")],Dt.prototype,"disableVideo",1),jt([E.trace("MediaHandler.setVideoDevice")],Dt.prototype,"setVideoDevice",1),jt([E.trace("MediaHandler.updateVideoConstraints")],Dt.prototype,"updateVideoConstraints",1),jt([E.trace("MediaHandler.enableScreenShare")],Dt.prototype,"enableScreenShare",1),jt([E.trace("MediaHandler.disableScreenShare")],Dt.prototype,"disableScreenShare",1),jt([E.trace("MediaHandler.updateScreenshareConstraints")],Dt.prototype,"updateScreenshareConstraints",1),jt([E.trace("MediaHandler.destruct")],Dt.prototype,"destruct",1),jt([E.trace("MediaHandler.onDeviceChange")],Dt.prototype,"onDeviceChange",1);function Tl(s,t,e){switch(!0){case Pe.isChromiumBased():switch(t){case"NotAllowedError":return e.includes("by system")?"SYSTEM_DENIED":s==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case Pe.isSafari():switch(t){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case Pe.isFirefox():switch(t){case"NotFoundError":case"NotReadableError":return"SYSTEM_DENIED";case"NotAllowedError":return"DENIED";case"AbortError":default:return"COULD_NOT_START"}default:return"COULD_NOT_START"}}const jD=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function yl(s){var e,r;const t=(e=s.label)==null?void 0:e.toLowerCase();return((r=Pe._bowser)==null?void 0:r.getOSName())==="macOS"&&t.includes("iphone")?!0:jD.some(i=>t==null?void 0:t.includes(i))}async function GD(s,t,e){if(!(t!=null&&t.length))return e;const r=s.getValue("logger"),i=new AudioContext,n=await Promise.all(t==null?void 0:t.map(d=>d(i))),o=i.createMediaStreamSource(new MediaStream([e])),c=i.createMediaStreamDestination();try{let d=o;for(let l=0;l<n.length;l+=1)d.connect(n[l]),d=n[l];d.connect(c)}catch(d){return r.error("getTransformedAudioTrack::middleware_execution_failed",{error:d}),e}return c.stream.getAudioTracks()[0]}const WD=s=>(t,e)=>(s.set(t,e),e),Bv=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,Fv=536870912,Hv=Fv*2,JD=(s,t)=>e=>{const r=t.get(e);let i=r===void 0?e.size:r<Hv?r+1:0;if(!e.has(i))return s(e,i);if(e.size<Fv){for(;e.has(i);)i=Math.floor(Math.random()*Hv);return s(e,i)}if(e.size>Bv)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;e.has(i);)i=Math.floor(Math.random()*Bv);return s(e,i)},qv=new WeakMap,KD=WD(qv),El=JD(KD,qv),zD=s=>s.method!==void 0&&s.method==="call",YD=s=>s.error===null&&typeof s.id=="number",bl=((s,t)=>{let e=null;return()=>{if(e!==null)return e;const r=new Blob([t],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(r);return e=s(i),setTimeout(()=>URL.revokeObjectURL(i)),e}})(s=>{const t=new Map([[0,()=>{}]]),e=new Map([[0,()=>{}]]),r=new Map,i=new Worker(s);return i.addEventListener("message",({data:l})=>{if(zD(l)){const{params:{timerId:u,timerType:h}}=l;if(h==="interval"){const g=t.get(u);if(typeof g=="number"){const v=r.get(g);if(v===void 0||v.timerId!==u||v.timerType!==h)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(h==="timeout"){const g=e.get(u);if(typeof g=="number"){const v=r.get(g);if(v===void 0||v.timerId!==u||v.timerType!==h)throw new Error("The timer is in an undefined state.")}else if(typeof g!="undefined")g(),e.delete(u);else throw new Error("The timer is in an undefined state.")}}else if(YD(l)){const{id:u}=l,h=r.get(u);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:g,timerType:v}=h;r.delete(u),v==="interval"?t.delete(g):e.delete(g)}else{const{error:{message:u}}=l;throw new Error(u)}}),{clearInterval:l=>{const u=El(r);r.set(u,{timerId:l,timerType:"interval"}),t.set(l,u),i.postMessage({id:u,method:"clear",params:{timerId:l,timerType:"interval"}})},clearTimeout:l=>{const u=El(r);r.set(u,{timerId:l,timerType:"timeout"}),e.set(l,u),i.postMessage({id:u,method:"clear",params:{timerId:l,timerType:"timeout"}})},setInterval:(l,u=0)=>{const h=El(t);return t.set(h,()=>{l(),typeof t.get(h)=="function"&&i.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:h,timerType:"interval"}})}),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:h,timerType:"interval"}}),h},setTimeout:(l,u=0)=>{const h=El(e);return e.set(h,l),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:h,timerType:"timeout"}}),h}}},`(()=>{"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})}}))})();`),jv=s=>bl().clearInterval(s),QD=s=>bl().clearTimeout(s),Gv=(s,t)=>bl().setInterval(s,t),gp=Object.freeze(Object.defineProperty({__proto__:null,clearInterval:jv,clearTimeout:QD,setInterval:Gv,setTimeout:(s,t)=>bl().setTimeout(s,t)},Symbol.toStringTag,{value:"Module"}));class XD{constructor(t){m(this,nn,void 0);m(this,nc,void 0);f(this,nc,t)}get logger(){return a(this,nc).getValue("logger")}terminateMiddlewareWebWorker(){if(a(this,nn))try{jv(a(this,nn)),f(this,nn,void 0)}catch(t){this.logger.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}async getTransformedVideoTrack(t,e,r){if(!(t!=null&&t.length))return e;const i=document.createElement("canvas"),n=await Promise.all(t==null?void 0:t.map(g=>g({canvas:i,WorkerTimers:gp})));if(r.disablePerFrameCanvasRendering){const v=i.captureStream().getVideoTracks()[0];return Object.defineProperty(v,"originalSettings",{value:e.getSettings()}),v}const o=document.createElement("video"),c=new MediaStream;c.addTrack(e);const d=i.getContext("2d");o.srcObject=c,o.autoplay=!0,this.terminateMiddlewareWebWorker();const l=async()=>{if(e.enabled===!1||e.readyState==="ended"){this.terminateMiddlewareWebWorker(),o.remove(),i.remove();return}try{d.drawImage(o,0,0);for(let g=0;g<n.length;g+=1)typeof n[g]=="function"&&await n[g](i,d)}catch(g){this.logger.error("getTransformedVideoTrack::middleware_execution_failed",{error:g})}};try{o.play()}catch(g){}o.addEventListener("play",()=>{i.width=o.width||e.getSettings().width,i.height=o.width||e.getSettings().height,f(this,nn,Gv(l,50))},!1);const h=i.captureStream().getVideoTracks()[0];return Object.defineProperty(h,"originalSettings",{value:e.getSettings()}),h}}nn=new WeakMap,nc=new WeakMap;const ZD={qvga:{width:{ideal:320},height:{ideal:240},frameRate:{ideal:30}},vga:{width:{ideal:640},height:{ideal:480},frameRate:{ideal:30}},hd:{width:{ideal:1280},height:{ideal:720},frameRate:{ideal:30}},fhd:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},uhd:{width:{ideal:3840},height:{ideal:2160},frameRate:{ideal:30}}},e1=[[320,[{rid:"f",scaleResolutionDownBy:1,scalabilityMode:"L1T3"},{rid:"h",scaleResolutionDownBy:2,scalabilityMode:"L1T3"}]],[640,[{rid:"f",scaleResolutionDownBy:1,scalabilityMode:"L1T3"},{rid:"h",scaleResolutionDownBy:2,scalabilityMode:"L1T3"}]],[1280,[{rid:"f",scaleResolutionDownBy:1,scalabilityMode:"L1T3"},{rid:"h",scaleResolutionDownBy:2,scalabilityMode:"L1T3"},{rid:"q",scaleResolutionDownBy:4,scalabilityMode:"L1T3"}]],[1920,[{rid:"f",scaleResolutionDownBy:1,scalabilityMode:"L1T3"},{rid:"h",scaleResolutionDownBy:2,scalabilityMode:"L1T3"},{rid:"q",scaleResolutionDownBy:4,scalabilityMode:"L1T3"}]],[3840,[{rid:"f",scaleResolutionDownBy:1,scalabilityMode:"L1T3"},{rid:"h",scaleResolutionDownBy:2,scalabilityMode:"L1T3"},{rid:"q",scaleResolutionDownBy:4,scalabilityMode:"L1T3"}]]],t1=(s,t)=>{var d,l,u;const e=(d=s==null?void 0:s.getValue("overrides"))==null?void 0:d.simulcastConfig;if((l=e==null?void 0:e.encodings)!=null&&l.length)return e.encodings;const r="getSettings"in t&&t.getSettings().width||"getConstraints"in t&&t.getConstraints().width||"originalSettings"in t&&((u=t.originalSettings)==null?void 0:u.width),i=e1,n=i.map(([h])=>h).sort((h,g)=>h-g);let o=Number.MAX_VALUE,c=0;return n.forEach((h,g)=>{Math.abs(h-r)<o&&(o=Math.abs(h-r),c=g)}),i[c][1]};var _e=(s=>(s.WEBCAM="webcam",s.WEBCAM_BACKUP="webcam_backup",s.MIC="mic",s.SCREENSHARE_VIDEO="screenshare_video",s.SCREENSHARE_AUDIO="screenshare_audio",s))(_e||{});const s1=oC(),Kn=Ls(s1.config.media);function r1(s){var e,r;const t={};return s.audio&&(t.audio={enableStereo:(e=s.audio.enableStereo)!=null?e:!1,enableHighBitrate:(r=s.audio.enableHighBitrate)!=null?r:!1}),t.video=s.video.quality,t}class i1{constructor(t,e){m(this,an,void 0);m(this,su,void 0);p(this,"getScreenShareConstraints",()=>{var l,u,h,g,v,y,k,I,D;const t=(l=a(this,an))==null?void 0:l.screenshare,e=(h=(u=t==null?void 0:t.width)==null?void 0:u.max)!=null?h:1920,r=(v=(g=t==null?void 0:t.height)==null?void 0:g.max)!=null?v:1080,i=(k=(y=t==null?void 0:t.frameRate)==null?void 0:y.max)!=null?k:5,n=(D=(I=t==null?void 0:t.frameRate)==null?void 0:I.ideal)!=null?D:5,o=t==null?void 0:t.displaySurface,c=t==null?void 0:t.selfBrowserSurface;let d={width:{max:e},height:{max:r},frameRate:{ideal:n,max:i}};return o!==void 0&&["monitor","browser","window"].includes(o)&&(d={...d,displaySurface:o}),c!==void 0&&(d={...d,selfBrowserSurface:c}),{audio:!0,video:d}});p(this,"getAudioConstraints",t=>{var n,o,c,d,l,u,h;const e={},r=(n=a(this,an))==null?void 0:n.audio,i=r!=null&&r.enableStereo?2:1;return Pe.isFirefox()||Pe.isWebKitBased()?(e.audio={deviceId:t,autoGainControl:(o=r==null?void 0:r.autoGainControl)!=null?o:!0,echoCancellation:(c=r==null?void 0:r.echoCancellation)!=null?c:!0,noiseSuppression:(d=r==null?void 0:r.noiseSupression)!=null?d:!0,channelCount:i},e):(e.audio={autoGainControl:(l=r==null?void 0:r.autoGainControl)!=null?l:!0,echoCancellation:(u=r==null?void 0:r.echoCancellation)!=null?u:!0,noiseSuppression:(h=r==null?void 0:r.noiseSupression)!=null?h:!0,channelCount:i},t&&(e.audio.deviceId={exact:t}),e)});p(this,"getVideoConstraints",t=>{var o,c,d;const e={},r=(o=a(this,an))==null?void 0:o.video,i=wk(ZD);let n=i.vga;if(typeof r=="string"){const l=i[r];l&&(n=l)}else r!==void 0&&(n.height.ideal=r.height.ideal,n.width.ideal=r.width.ideal,n.frameRate.ideal=(d=(c=r.frameRate)==null?void 0:c.ideal)!=null?d:30);return e.video=n,typeof e.video=="boolean"||(t?e.video.deviceId={exact:t}:e.video.facingMode="user"),e});f(this,su,t),f(this,an,e)}getUpdatedVideoConstraints(t){return t}}an=new WeakMap,su=new WeakMap;class fp extends Error{constructor(e,r,i){super(r);p(this,"constraints");p(this,"name");this.name=e,this.constraints=i}}class n1{constructor(){p(this,"permissions");this.permissions={audio:"NOT_REQUESTED",video:"NOT_REQUESTED",screenshare:"NOT_REQUESTED"}}async getAudioInputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="audioinput")}async getVideoInputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="videoinput")}async getAudioOutputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="audiooutput")}}var a1=Object.defineProperty,o1=Object.getOwnPropertyDescriptor,bs=(s,t,e,r)=>{for(var i=r>1?void 0:r?o1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&a1(t,e,i),i};let Gt=(YS=class extends n1{constructor(t,e){super();m(this,Ta,void 0);m(this,us,void 0);m(this,Xe,void 0);f(this,Xe,t),f(this,us,new i1(t,e)),f(this,Ta,new AbortController)}get telemetry(){return a(this,Xe).getValue("telemetry")}get logger(){return a(this,Xe).getValue("logger")}get constraintsBuilder(){return a(this,us)}async destruct(){var t;(t=a(this,Ta))==null||t.abort()}handlePermissionErrors(t,e){const r=Tl(t,e.name,e.message);return this.permissions[t]=r,a(this,Xe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_ERROR,{message:r,constraints:e.constraints,kind:t}),r}async getAudioAndVideoTrack(t,e){var r,i,n,o;try{const c=await this.getAudioInputDevices(),d=await this.getVideoInputDevices(),l=!!(c!=null&&c.find(D=>D.deviceId===t));let u;t&&l?u=t:c&&((r=c[0])!=null&&r.deviceId)&&(u=(i=c[0])==null?void 0:i.deviceId);const h=!!(d!=null&&d.find(D=>D.deviceId===e));let g;e&&h?g=e:d&&((n=d[0])!=null&&n.deviceId)&&(g=(o=d[0])==null?void 0:o.deviceId);const v={audio:a(this,us).getAudioConstraints(u).audio,video:a(this,us).getVideoConstraints(g).video};this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(v)});const y=await navigator.mediaDevices.getUserMedia(v);this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(v)});const k=y.getAudioTracks()[0];let I=y.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",I.label.includes("OBS Virtual")){const N=(await this.getVideoInputDevices()).find(B=>B.label.includes("OBS Virtual"));I=await this.getVideoTrack(N.deviceId)}return a(this,Xe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),a(this,Xe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:k,videoTrack:I}}catch(c){throw this.logger.error("WebMediaInterface.getAudioAndVideoTrack",{error:c}),new C("Couldnt fetch audio and video track","1605")}}async getAudioTrack(t,e){var c,d;let r=await this.getAudioInputDevices();if(!(r!=null&&r.length))throw this.permissions.audio="NO_DEVICES_AVAILABLE",a(this,Xe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new C("No audio devices available","1606");const i=!!(r!=null&&r.find(l=>l.deviceId===e));let n;e&&i?n=e:(c=r[0])!=null&&c.deviceId&&(n=(d=r[0])==null?void 0:d.deviceId);const o=async l=>{let u;try{r=r.filter(g=>g.deviceId!==l),u=a(this,us).getAudioConstraints(l),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(u)});const[h]=(await navigator.mediaDevices.getUserMedia(u)).getAudioTracks();return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(u)}),h}catch(h){const g=Tl("audio",h.name,h.message),v=new fp(h.name,h.message,u);if(g==="COULD_NOT_START"){const y=r.shift();if(!y)throw v;this.logger.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(u),error:h});const k=a(this,us).getAudioConstraints(y.deviceId);return this.logger.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(k)}),o(y.deviceId)}throw v}};try{const l=await o(n);return l.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",a(this,Xe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),l}catch(l){throw l.constraints&&this.handlePermissionErrors("audio",l),new C(l.message,"1601")}}async getVideoTrack(t){var c,d,l;const e=(c=await this.getCurrentDeviceLabel(t))==null?void 0:c.includes("OBS Virtual"),r=await this.getVideoInputDevices();if(!(r!=null&&r.length))throw this.permissions.video="NO_DEVICES_AVAILABLE",a(this,Xe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new C("No video devices available","1607");const i=!!(r!=null&&r.find(u=>u.deviceId===t));let n;t&&i?n=t:(d=r[0])!=null&&d.deviceId&&(n=(l=r[0])==null?void 0:l.deviceId);const o=async u=>{try{let h=u;const{video:g}=h;e&&typeof g!="boolean"&&(h={video:{deviceId:g.deviceId}}),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(h)});const[v]=(await navigator.mediaDevices.getUserMedia(h)).getVideoTracks();if(e&&typeof g!="boolean"&&typeof g.width=="object"){const{width:y,height:k}=v.getSettings(),{ideal:I}=g.width;v.applyConstraints({width:{ideal:I},height:{ideal:Math.floor(k*I/y)},frameRate:g.frameRate})}return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(h)}),v}catch(h){const g=Tl("video",h.name,h.message),v=new fp(h.name,h.message,u);if(g==="COULD_NOT_START"){const y=r.shift();if(!y)throw v;this.logger.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(u),error:h});const k=a(this,us).getVideoConstraints(y.deviceId);return this.logger.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(k)}),o({video:k.video})}throw v}};try{const u=a(this,us).getVideoConstraints(n),h=await o(u);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",a(this,Xe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),h}catch(u){throw u.constraints&&this.handlePermissionErrors("video",u),new C(u.message,"1602")}}async getScreenShareTracks(){const t=async e=>{try{this.logger.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),a(this,Xe).getValue("callstats").screenShareRequested();const r=await navigator.mediaDevices.getDisplayMedia(e);return this.logger.info("getDisplayMediaWithoutTimeout::received_display_media",{constraints:JSON.stringify(e)}),r}catch(r){const i=Tl("video",r.name,r.message),n=new fp(r.name,r.message,e),o={video:!0};if(M_(e,o))throw n;if(i==="COULD_NOT_START")return t(o);throw n}};try{const e=a(this,us).getScreenShareConstraints(),r=await t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",a(this,Xe).getValue("peerSessionStore").emit(P.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 C(e.message,"1612")}}async getCurrentDeviceLabel(t){const e=await this.getDevice(t||"default");return e==null?void 0:e.label}async enumerateDevicesWithExternalFirst(){const t=await navigator.mediaDevices.enumerateDevices(),e=i=>{var o;const n=((o=i.label)==null?void 0:o.toLowerCase())||"";return yl(i)?4:n.includes("airpods")||n.includes("airdopes")||n.includes("bluetooth")||n.includes("wireless")||n.includes("headphones")||n.includes("headset")&&!n.includes("earpiece")||n.includes("earbuds")||n.includes("usb")||n.includes("external")?0:i.deviceId==="default"||n.includes("default")?1:n.includes("built-in")||n.includes("internal")?2:3},r=i=>{var o;if(i.kind!=="videoinput")return!1;const n=((o=i.label)==null?void 0:o.toLowerCase())||"";return n.includes("front")||n.includes("user")||n.includes("selfie")?!0:!(n.includes("back")||n.includes("rear")||n.includes("environment"))};return t.sort((i,n)=>{var u,h;const o=e(i),c=e(n);if(o!==c)return o-c;const d=i.deviceId==="default"||((u=i.label)==null?void 0:u.toLowerCase().includes("default")),l=n.deviceId==="default"||((h=n.label)==null?void 0:h.toLowerCase().includes("default"));if(d&&!l)return-1;if(!d&&l)return 1;if(i.kind==="videoinput"&&n.kind==="videoinput"){const g=r(i),v=r(n);if(g&&!v)return-1;if(!g&&v)return 1}return 0})}async getAvailableDevices(){try{return await this.enumerateDevicesWithExternalFirst()||[]}catch(t){return this.logger.error("enumerate_devices_failed",{error:t}),[]}}async getAvailableDevicesByKind(t){try{return(await this.enumerateDevicesWithExternalFirst()).filter(({kind:e})=>t===e)}catch(e){throw this.logger.error("enumerate_devices_failed",{error:e}),new C("Failed to get available devices by kind","1609")}}async getDevice(t){try{return(await this.enumerateDevicesWithExternalFirst()).filter(r=>r.deviceId===t)[0]}catch(e){throw this.logger.error("enumerate_devices_failed",{error:e}),new C("Failed to get device","1609")}}async onDeviceChange(t){if(Pe.supportsDeviceChangeEvent()){let e=await this.getAvailableDevices();navigator.mediaDevices.addEventListener("devicechange",async r=>{var l,u;const i=h=>`${h.kind}-${h.label}-${h.deviceId}-${h.groupId}`,n=new Set(e.map(h=>i(h))),o=await this.getAvailableDevices(),c=new Set(o.map(h=>i(h))),d={added:o.filter(h=>!n.has(i(h))),removed:e.filter(h=>!c.has(i(h))),devices:o};if(e=o,(l=d.added)!=null&&l.length||(u=d.removed)!=null&&u.length){this.logger.info("repopulated_full_device_list",{devices:JSON.stringify(o)});const h=[...d.added,...d.removed];h.some(g=>g.kind==="audioinput")&&a(this,Xe).getValue("callstats").devices("AUDIO",o==null?void 0:o.filter(g=>g.kind==="audioinput")),h.some(g=>g.kind==="videoinput")&&a(this,Xe).getValue("callstats").devices("VIDEO",o==null?void 0:o.filter(g=>g.kind==="videoinput")),h.some(g=>g.kind==="audiooutput")&&a(this,Xe).getValue("callstats").devices("SPEAKER",o==null?void 0:o.filter(g=>g.kind==="audiooutput")),t(r,d,!1)}},{signal:a(this,Ta).signal})}}},Ta=new WeakMap,us=new WeakMap,Xe=new WeakMap,YS);bs([E.trace("WebMediaInterface.destruct")],Gt.prototype,"destruct",1),bs([E.trace("WebMediaInterface.handlePermissionErrors")],Gt.prototype,"handlePermissionErrors",1),bs([E.trace("WebMediaInterface.getAudioAndVideoTrack")],Gt.prototype,"getAudioAndVideoTrack",1),bs([E.trace("WebMediaInterface.getAudioTrack")],Gt.prototype,"getAudioTrack",1),bs([E.trace("WebMediaInterface.getVideoTrack")],Gt.prototype,"getVideoTrack",1),bs([E.trace("WebMediaInterface.getScreenShareTracks")],Gt.prototype,"getScreenShareTracks",1),bs([E.trace("WebMediaInterface.getAvailableDevices")],Gt.prototype,"getAvailableDevices",1),bs([E.trace("WebMediaInterface.getAvailableDevicesByKind")],Gt.prototype,"getAvailableDevicesByKind",1),bs([E.trace("WebMediaInterface.getDevice")],Gt.prototype,"getDevice",1),bs([E.trace("WebMediaInterface.onDeviceChange")],Gt.prototype,"onDeviceChange",1),Gt=bs([pt("1600")],Gt);const Wv=Gt,$i={setItem:(s,t,e)=>{try{localStorage.setItem(s,t)}catch(r){e==null||e.error("LocalStorage::setItem::crashed",{error:r,localStorage:{key:s,value:t}})}},getItem:(s,t)=>{try{return localStorage.getItem(s)}catch(e){t==null||t.error("LocalStorage::getItem::crashed",{error:e,localStorage:{key:s}})}return null}},c1=(s=0)=>new Promise(t=>setTimeout(t,s)),d1=(s,t,e)=>{const r=typeof e=="number"?e:250,i=s.createMediaStreamSource(t),n=s.createAnalyser();n.fftSize=2048,i.connect(n);const o=new Uint8Array(n.fftSize);let c=!1;setTimeout(()=>{c=!0},r);function d(){return c?Promise.resolve(!0):(n.getByteTimeDomainData(o),o.some(l=>l!==128&&l!==0)?Promise.resolve(!1):c1().then(d))}return d().then(l=>(i.disconnect(),l),l=>{throw i.disconnect(),l})},l1=typeof AudioContext!="undefined"?AudioContext:null;class vp{constructor(t){p(this,"_AudioContext");p(this,"audioContext");p(this,"_audioContextRefContainers");const e={AudioContext:l1,...t};Object.defineProperties(this,{_AudioContext:{value:e.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:vp}})}getOrCreate(t){if(!this._audioContextRefContainers.has(t)&&(this._audioContextRefContainers.add(t),this._AudioContext&&!this.audioContext))try{this.audioContext=new this._AudioContext}catch(e){}return this.audioContext}release(t){this._audioContextRefContainers.has(t)&&(this._audioContextRefContainers.delete(t),!this._audioContextRefContainers.size&&this.audioContext&&(this.audioContext.close(),this.audioContext=null))}}const Jv=new vp,u1=3,h1=250;function p1(s){const t={},e=Jv.getOrCreate(t);let r=u1;function i(){return r-=1,d1(e,s.srcObject,h1).then(n=>n?r>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{Jv.release(t)})}async function Kv(s,t){const e=new Audio,r=new MediaStream;r.addTrack(t),e.srcObject=r;let i=!1;try{const n=e.play();n&&await n,i=await p1(e),i&&s.info("checkIfAudioTrackIsSilent::silence_detected")}catch(n){s.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:n})}finally{e.pause(),e.remove()}return i}var m1=Object.defineProperty,g1=Object.getOwnPropertyDescriptor,zv=(s,t,e,r)=>{for(var i=r>1?void 0:r?g1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&m1(t,e,i),i};let wl=class extends Bn{constructor(t,e,r,i){var o;const n=t.getValue("logger");super(n);p(this,"constructorName",this.constructor.name);p(this,"userSelectedDevice");p(this,"mediaInterface");p(this,"isNonPreferredDevice");p(this,"_mediaTrack");p(this,"transformedMediaTrack");p(this,"middlewares",[]);p(this,"currentDevice");p(this,"userPreferredDeviceKey",`Realtimekit::${this.constructorName}::UserDeviceID`);p(this,"setUserPreferredDevice",t=>$i.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>$i.getItem(this.userPreferredDeviceKey,this.logger));p(this,"isCustomTrack",!1);p(this,"context");this.context=t,this.mediaInterface=e,r&&this.setMediaTrack(r),this.userSelectedDevice=(o=this.getUserPreferredDevice())!=null?o:void 0,this.isNonPreferredDevice=i,this.onTrackEnded=this.onTrackEnded.bind(this),this.onTrackMuted=this.onTrackMuted.bind(this)}get telemetry(){return this.context.getValue("telemetry")}disableTrack(){var t,e;this.removeMediaTrackListeners(),this.isCustomTrack||(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}async setMediaTrack(t,e=!1){const r=i=>{this.logger.error(`${this.constructorName}.setMediaTrack.error`,{error:i})};try{this.disableTrack()}catch(i){r(i)}this._mediaTrack=await this.conditionallyChangeTrack(t,e),await this.setTransformedTrack();try{this.addMediaTrackListeners(),await this.setCurrentDevice()}catch(i){r(i)}}get trackEnabled(){return!!this.mediaTrack&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}muteTrack(){if(!this.mediaTrack){this.logger.warn("BaseMediaHandler.muteTrack Tried muting with no track present");return}this.transformedMediaTrack&&(this.transformedMediaTrack.enabled=!1),this.mediaTrack.enabled=!1}async unmuteTrack(){try{this.mediaTrack?this.mediaTrack.enabled=!0:await this.enableTrack(!1)}catch(t){throw this.logger.error(`${this.constructorName}.unmuteTrack.error`,{error:t}),this.disableTrack(),new C("Failed to unmute track","1611")}}getCurrentDeviceId(){var e;const{kind:t}=this.mediaTrack;switch(t){case"audio":{const{deviceId:r}=this.mediaTrack.getSettings();if(r)return r;const i=this.mediaTrack.getConstraints();return this.userSelectedDevice?(i&&typeof i.deviceId=="object"&&"exact"in i.deviceId?i.deviceId.exact:i.deviceId)||((e=i==null?void 0:i.advanced)==null?void 0:e[0].deviceId)||"default":this.mediaTrack.getSettings().deviceId}default:return this.mediaTrack.getSettings().deviceId}}async setCurrentDevice(){var e;if(!this.mediaTrack){this.currentDevice=void 0;return}const t=this.getCurrentDeviceId();((e=this.currentDevice)==null?void 0:e.deviceId)!==t&&(this.currentDevice=await this.mediaInterface.getDevice(t))}async setDevice(t,{saveDevicePreference:e}){if(!t)throw this.logger.warn(`${this.constructorName}.setDevice No device received`),new C("No device received!","1603");this.userSelectedDevice=t.deviceId,e&&this.setUserPreferredDevice(t.deviceId),await this.onSetDevice(t)}async addMiddleware(t){if(Pe.isWebKitBased()&&!(Pe.isSafari()&&G_.test(Pe.getVersion())))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&&await this.setTransformedTrack(),{success:!0,message:"Successfully added the middleware."}}catch(e){return this.logger.error("While adding middleware",{error:e}),this.removeMiddleware(t),{success:!1,message:e==null?void 0:e.message}}}async removeMiddleware(t){const e=this.middlewares.indexOf(t,0);if(e>-1)try{return this.middlewares.splice(e,1),await this.setTransformedTrack(!0),{success:!0,message:"Successfully removed the middleware."}}catch(r){return this.logger.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."}}async removeAllMiddlewares(){var t;if((t=this.middlewares)!=null&&t.length)try{return this.middlewares=[],await this.setTransformedTrack(!0),{success:!0,message:"Successfully removed all the middlewares."}}catch(e){return this.logger.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&&(this.logger.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&&(this.logger.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}`),this.logger.info(`${this.constructorName}.removeMediaTrackListeners`),this.mediaTrack.removeEventListener("ended",this.onTrackEnded),this.mediaTrack.removeEventListener("mute",this.onTrackMuted))}};zv([E.trace("BaseMediaHandler.unmuteTrack")],wl.prototype,"unmuteTrack",1),wl=zv([pt("1600")],wl);const Yv=wl;var f1=Object.defineProperty,v1=Object.getOwnPropertyDescriptor,Sp=(s,t,e,r)=>{for(var i=r>1?void 0:r?v1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&f1(t,e,i),i};const Tp="[Realtimekit]nonSilentDeviceLabels";class Pl extends Yv{async onSetDevice(t){if(!t)throw this.logger.warn("AudioMediaHandler.setDevice No device received"),new C("No device received!","1603");if(t.kind!=="audioinput")throw this.logger.warn("AudioMediaHandler.setDevice Received non audio device"),new C("Non audio device received while setting device!","1603");try{const e=this.trackEnabled;this.disableTrack(),await this.setMediaTrack(await this.mediaInterface.getAudioTrack(!e,this.userSelectedDevice))}catch(e){throw this.logger.error("AudioMediaHandler.setDevice.error",{error:e}),this.disableTrack(),new C(e.message,"1604")}}async enableTrack(t,e){if(this.trackEnabled){this.logger.warn("AudioMediaHandler.enableTrack Track already enabled!");return}if(e){this.isCustomTrack=!0,await this.setMediaTrack(e,!0);return}this.isCustomTrack=!1;const r=await this.mediaInterface.getAudioTrack(t,this.userSelectedDevice);await this.setMediaTrack(r)}async setTransformedTrack(t){var e;if(!t&&!((e=this.middlewares)!=null&&e.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=await GD(this.context,this.middlewares,this.mediaTrack),this.emit("trackChanged")}catch(r){this.logger.error("AudioMediaHandler.setTransformedTrack",{error:r}),this.transformedMediaTrack=this.mediaTrack}}async onTrackEnded(){this.logger.info("AudioMediaHandler.TrackEnded"),this.emit("trackEnded");const t=this.mediaTrack.enabled;this.disableTrack(),await this.enableTrack(!t),await this.setTransformedTrack(),this.emit("trackChanged")}onTrackMuted(){this.logger.info("AudioMediaHandler.TrackMuted"),this.emit("trackMuted")}async conditionallyChangeTrack(t,e=!1){var d;if(!t||this.userSelectedDevice||e)return t;let r=t;const i=await this.mediaInterface.getAudioInputDevices(),n=this.isNonPreferredDevice?i.filter(l=>l&&!this.isNonPreferredDevice(l)):i;if(!(n!=null&&n.length))return r;n.find(l=>l.deviceId===t.getSettings().deviceId)||(r.stop(),this.logger.info("localmediahandler::setupstreams::found_audio_non_preferred"),r=await this.mediaInterface.getAudioTrack(!1,n[0].deviceId));const o=JSON.parse($i.getItem(Tp,this.logger));if(o!=null&&o.devices.some(l=>l.label===r.label))return r;if(!await Kv(this.logger,r)){const l=(d=o==null?void 0:o.devices.concat({label:r.label}))!=null?d:[{label:r.label}];return $i.setItem(Tp,JSON.stringify({devices:l}),this.logger),r}this.logger.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const c=r.getSettings().deviceId;return n.filter(l=>l.deviceId!==c).some(async l=>{var u;if(r=await this.mediaInterface.getAudioTrack(!1,l.deviceId),!await Kv(this.logger,r)){const h=(u=o==null?void 0:o.devices.concat({label:r.label}))!=null?u:[{label:r.label}];return $i.setItem(Tp,JSON.stringify({devices:h}),this.logger),this.logger.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return this.logger.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1}),r}}Sp([E.trace("AudioMediaHandler.setTransformedTrack")],Pl.prototype,"setTransformedTrack",1),Sp([E.trace("AudioMediaHandler.onTrackEnded")],Pl.prototype,"onTrackEnded",1),Sp([E.trace("AudioMediaHandler.conditionallyChangeTrack")],Pl.prototype,"conditionallyChangeTrack",1);const S1=Pl;class T1{constructor(t,e){m(this,on,void 0);p(this,"currentDevice");p(this,"userPreferredDeviceKey","Realtimekit::speaker::UserDeviceID");p(this,"logger");p(this,"setUserPreferredDevice",t=>$i.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>$i.getItem(this.userPreferredDeviceKey,this.logger));f(this,on,e),this.logger=t.getValue("logger")}async setPreferredSpeaker(){const t=this.getUserPreferredDevice(),e=await a(this,on).getAudioOutputDevices(),r=e==null?void 0:e.find(i=>i.deviceId===t);await this.setupSpeaker(r,{saveDevicePreference:!1})}async setupSpeaker(t,{saveDevicePreference:e}){var n,o;if(!(a(this,on)instanceof Wv))return;let r=t;if(t||([r]=(await a(this,on).getAvailableDevicesByKind("audiooutput")).filter(d=>!yl(d))),!r)throw new C("No speaker found","1608");if(((n=this.currentDevice)==null?void 0:n.deviceId)===r.deviceId)return;e&&this.setUserPreferredDevice(r.deviceId),this.currentDevice=r;const i=document.querySelectorAll("audio");(o=i[0])!=null&&o.setSinkId&&i.forEach(async c=>{if(typeof c.sinkId!="undefined"&&this.currentDevice.deviceId&&c.sinkId!==this.currentDevice.deviceId)try{await c.setSinkId(this.currentDevice.deviceId)}catch(d){}})}}on=new WeakMap;const y1=T1;class E1 extends Bn{constructor(e,r){const i=e.getValue("logger");super(i);p(this,"mediaInterface");p(this,"audioMediaTrack");p(this,"videoMediaTrack");p(this,"previousAudioMediaTrack");p(this,"previousVideoMediaTrack");m(this,ac,void 0);f(this,ac,e),this.mediaInterface=r,this.onTrackEnded=this.onTrackEnded.bind(this)}get trackEnabled(){return!!this.videoMediaTrack}async enableScreenShare(){var e,r,i,n,o,c;try{const{audioTrack:d,videoTrack:l}=await this.mediaInterface.getScreenShareTracks();this.audioMediaTrack=d,this.videoMediaTrack=l,this.addMediaTrackListeners(),this.mediaInterface.permissions&&this.mediaInterface.permissions.screenshare!=="ACCEPTED"&&(this.mediaInterface.permissions.screenshare="ACCEPTED",a(this,ac).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"})),(this.previousAudioMediaTrack||this.previousVideoMediaTrack)&&((e=this.previousAudioMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded),(r=this.previousVideoMediaTrack)==null||r.removeEventListener("ended",this.onTrackEnded),(i=this.previousAudioMediaTrack)==null||i.removeEventListener("mute",this.onTrackEnded),(n=this.previousVideoMediaTrack)==null||n.removeEventListener("mute",this.onTrackEnded),(o=this.previousAudioMediaTrack)==null||o.stop(),(c=this.previousVideoMediaTrack)==null||c.stop()),this.previousAudioMediaTrack=this.audioMediaTrack,this.previousVideoMediaTrack=this.videoMediaTrack}catch(d){}}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,this.previousAudioMediaTrack=void 0,this.previousVideoMediaTrack=void 0}async updateConstraints(e){if(!this.videoMediaTrack)throw new C("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new C("update constraints not supported for non web clients","1100",this.logger);try{this.videoMediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),this.addMediaTrackListeners()}catch(i){this.logger.error("ScreenShareHandler.updateConstraints.error",{error:i})}}addMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.addEventListener("ended",this.onTrackEnded),Pe.isWebKitBased()&&((r=this.videoMediaTrack)==null||r.addEventListener("mute",this.onTrackEnded))}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")}}ac=new WeakMap;const b1=E1;var w1=Object.defineProperty,P1=Object.getOwnPropertyDescriptor,kl=(s,t,e,r)=>{for(var i=r>1?void 0:r?P1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&w1(t,e,i),i};class Co extends Yv{constructor(e,r,i,n){super(e,r,i,n);m(this,ya,void 0);m(this,oc,{disablePerFrameCanvasRendering:!1});f(this,ya,new XD(e))}async onSetDevice(e){if(!e)throw this.logger.warn("VideoMediaHandler.setDevice No device received"),new C("No device received!","1603");if(e.kind!=="videoinput")throw this.logger.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new C("Non video device received while setting video device!","1603");if(!(this.mediaTrack&&this.mediaTrack.enabled)){this.logger.warn("VideoMediaHandler.setDevice Tried switching device with video disabled",{devices:[e]}),this.currentDevice=e;return}try{this.disableTrack(),await this.setMediaTrack(await this.mediaInterface.getVideoTrack(this.userSelectedDevice))}catch(r){throw this.logger.error("VideoMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new C("Failed to change device","1600",this.logger)}}async enableTrack(e,r){if(this.trackEnabled){this.logger.warn("VideoMediaHandler.enableTrack Track already enabled!");return}if(r){this.isCustomTrack=!0,await this.setMediaTrack(r,!0);return}this.isCustomTrack=!1;const i=await this.mediaInterface.getVideoTrack(this.userSelectedDevice);await this.setMediaTrack(i)}async setTransformedTrack(e){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=await a(this,ya).getTransformedVideoTrack(this.middlewares,this.mediaTrack,a(this,oc)),this.emit("trackChanged")}catch(i){this.logger.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}}async setVideoMiddlewareGlobalConfig(e){f(this,oc,e)}async updateConstraints(e){if(!this._mediaTrack)throw new C("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new C("update constraints not supported for non web clients","1100",this.logger);try{this._mediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),await this.setTransformedTrack(),this.addMediaTrackListeners(),await this.setCurrentDevice()}catch(i){this.logger.error("VideoMediaHandler.updateConstraints.error",{error:i})}}terminateMiddlewareWebWorker(){a(this,ya).terminateMiddlewareWebWorker()}async onTrackEnded(){this.logger.info("VideoMediaHandler.TrackEnded"),this.disableTrack(),this.emit("trackEnded")}onTrackMuted(){this.logger.info("VideoMediaHandler.TrackMuted"),this.emit("trackMuted")}async conditionallyChangeTrack(e,r=!1){if(!e||this.userSelectedDevice||r)return e;let i=e;const n=await this.mediaInterface.getVideoInputDevices(),o=this.isNonPreferredDevice?n.filter(c=>!this.isNonPreferredDevice(c)):n;return!(o!=null&&o.length)||window.FAST_RTK||o.find(c=>c.deviceId===e.getSettings().deviceId)||(i.stop(),this.logger.info("localmediahandler::setupstreams::found_video_non_preferred"),i=await this.mediaInterface.getVideoTrack(o[0].deviceId)),i}}ya=new WeakMap,oc=new WeakMap,kl([E.trace("VideoMediaHandler.setTransformedTrack")],Co.prototype,"setTransformedTrack",1),kl([E.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],Co.prototype,"setVideoMiddlewareGlobalConfig",1),kl([E.trace("VideoMediaHandler.onTrackEnded")],Co.prototype,"onTrackEnded",1),kl([E.trace("VideoMediaHandler.conditionallyChangeTrack")],Co.prototype,"conditionallyChangeTrack",1);const k1=Co,Qv=Ls(Lh()),ba=class{constructor(t){m(this,bt,void 0);m(this,cn,void 0);m(this,cc,void 0);m(this,Ea,void 0);if(!t)throw new C("Could not load preset.","0904");f(this,bt,t.config),f(this,cc,t.name),f(this,cn,t.ui||Ls(Lh().ui)),f(this,Ea,t.permissions.plugins.config)}static fromResponse(t){return new ba(t)}static default(){return new ba(Qv)}static init(t,e=!0){return!t||e?new ba(Qv):new ba(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:a(this,cn).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return a(this,bt).viewType}get livestreamViewerQualities(){return a(this,bt).livestreamViewerQualities||[]}get maxVideoStreams(){return a(this,bt).maxVideoStreams}get maxScreenShareCount(){return a(this,bt).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(a(this,Ea)).filter(t=>a(this,Ea)[t].disabled)}get designTokens(){return a(this,cn).designTokens}get configDiff(){return a(this,cn).configDiff}get isSimulcastEnabled(){var t,e,r,i;return(i=(r=(e=(t=a(this,bt))==null?void 0:t.media)==null?void 0:e.video)==null?void 0:r.simulcast)!=null?i:!1}get mediaConstraints(){var t,e,r,i,n,o,c,d,l,u,h,g,v,y,k,I,D,N,B,U,j,Z,re,F;return{audio:{enableStereo:(i=(r=(e=(t=a(this,bt))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?i:Kn.audio.enableStereo,enableHighBitrate:(d=(c=(o=(n=a(this,bt))==null?void 0:n.media)==null?void 0:o.audio)==null?void 0:c.enableHighBitrate)!=null?d:Kn.audio.enableHighBitrate},video:{quality:(g=(h=(u=(l=a(this,bt))==null?void 0:l.media)==null?void 0:u.video)==null?void 0:h.quality)!=null?g:Kn.video.quality,frameRate:(I=(k=(y=(v=a(this,bt))==null?void 0:v.media)==null?void 0:y.video)==null?void 0:k.frameRate)!=null?I:Kn.video.frameRate},screenshare:{quality:(U=(B=(N=(D=a(this,bt))==null?void 0:D.media)==null?void 0:N.screenshare)==null?void 0:B.quality)!=null?U:Kn.screenshare.quality,frameRate:(F=(re=(Z=(j=a(this,bt))==null?void 0:j.media)==null?void 0:Z.screenshare)==null?void 0:re.frameRate)!=null?F:Kn.screenshare.frameRate}}}get name(){return a(this,cc)}};let yp=ba;bt=new WeakMap,cn=new WeakMap,cc=new WeakMap,Ea=new WeakMap;var _1=Object.defineProperty,C1=Object.getOwnPropertyDescriptor,Xv=(s,t,e,r)=>{for(var i=r>1?void 0:r?C1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&_1(t,e,i),i};class Ep extends Bt{constructor(e,r){const i=e.getValue("logger");super(i);m(this,wa,void 0);p(this,"state","IDLE");p(this,"playbackUrl");p(this,"ingestionCredentials");p(this,"viewerCount");m(this,dc,void 0);f(this,wa,r),f(this,dc,e),this.viewerCount=0}get telemetry(){return a(this,dc).getValue("telemetry")}setLivestreamState(e){const r=this.state;this.state=e,r!==e&&this.emitCurrentLivestreamState()}emitCurrentLivestreamState(){this.emit("livestreamUpdate",this.state)}async start(e={manualIngestion:!1}){if(!a(this,wa).permissions.canLivestream)throw this.logger.error("Livestream::start::permission_denied"),new C("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const r=Ht(),{playbackUrl:i,ingestionCredentials:n}=await r.startLivestreaming(e);this.playbackUrl=i,this.ingestionCredentials=n,e!=null&&e.manualIngestion&&this.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}catch(r){throw this.logger.error("Recording::stop::livestream_failed_to_start",{error:r}),this.setLivestreamState("IDLE"),new C("Error while starting livestream","1900",this.logger)}}async stop(){if(!a(this,wa).permissions.canLivestream)throw this.logger.error("Livestream::stop::permission_denied"),new C("User does not have permission to stop livestreaming","1901");if(this.state!=="LIVESTREAMING"&&this.state!=="WAITING_ON_MANUAL_INGESTION")throw this.logger.error("Livestream::stop::inconsistent_state"),new C("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),await Ht().stopLivestreaming()}catch(e){throw this.logger.error("Livestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new C("Error while stopping livestream","1900",this.logger)}}}wa=new WeakMap,dc=new WeakMap,Xv([E.trace("livestream.start")],Ep.prototype,"start",1),Xv([E.trace("livestream.stop")],Ep.prototype,"stop",1);var R1=Object.defineProperty,I1=Object.getOwnPropertyDescriptor,A1=(s,t,e,r)=>{for(var i=r>1?void 0:r?I1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&R1(t,e,i),i};class Zv{constructor(t,e,r){p(this,"livestream");m(this,Pa,void 0);m(this,ka,void 0);m(this,wr,void 0);m(this,Bs,void 0);f(this,Bs,t),f(this,ka,e),this.livestream=new Ep(t,e),f(this,wr,r),this.setupEvents()}get logger(){return a(this,Bs).getValue("logger")}get telemetry(){return a(this,Bs).getValue("telemetry")}async fetchInitialLivestreamingState(){const t=Ht(),{status:e,playbackUrl:r,manualIngest:i,ingestionCredentials:n}=await t.getActiveLivestream();this.livestream.playbackUrl=r,this.livestream.ingestionCredentials=n,e==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),e==="INVOKED"&&i&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}setupEvents(){a(this,wr).on(x.startedLivestream,async t=>{this.livestream.playbackUrl=t.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{a(this,ka).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}}),a(this,wr).on(x.livestreamingInvoked,async t=>{if(t.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{a(this,ka).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}}),a(this,wr).on(x.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),a(this,wr).on(x.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),a(this,wr).on(x.roomPeerCount,t=>{this.livestream.viewerCount=t.count,this.livestream.emit("viewerCountUpdate",t.count)}),a(this,Bs).getValue("peerSessionStore").on(P.PEER_JOINED_INTERNAL,async t=>{var e;((e=t.flags)==null?void 0:e.hiddenParticipant)===!0&&t.recorderType==="LIVESTREAMER"&&(f(this,Pa,t.id),this.livestream.setLivestreamState("LIVESTREAMING"))}),a(this,Bs).getValue("peerSessionStore").on(P.PEER_CLOSED,t=>{t.id===a(this,Pa)&&(f(this,Pa,void 0),this.livestream.setLivestreamState("IDLE"))}),a(this,Bs).getValue("peerSessionStore").onAsync(P.LEAVE_MEDIA_ROOM,async()=>{if(!this.livestream.playbackUrl){this.logger.info("Fetching livestreaming state on leave stage");try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Failed to fetch livestreaming state on leave stage",{error:t})}}}),a(this,Bs).getValue("peerSessionStore").on(P.SOCKET_SERVICE_ROOM_JOINED,async()=>{try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Error: LivestreamController.fetchLivestream")}})}}Pa=new WeakMap,ka=new WeakMap,wr=new WeakMap,Bs=new WeakMap,A1([E.trace("LivestreamController.setupEvents")],Zv.prototype,"setupEvents",1);var M1=Object.defineProperty,O1=Object.getOwnPropertyDescriptor,Ro=(s,t,e,r)=>{for(var i=r>1?void 0:r?O1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&M1(t,e,i),i};class zn{constructor({name:t,socketHandler:e,meetingId:r}){m(this,ru);p(this,"name","");m(this,ct,{});m(this,ai,"");m(this,oi,void 0);p(this,"rateLimitConfig",{maxInvocations:5,period:1});p(this,"bulkRateLimitConfig",{maxInvocations:5,period:1});p(this,"listeners",{});this.name=t,f(this,oi,e),f(this,ai,r)}async set(t,e,r=!0,i=!1){a(this,ct)[t]=e,r&&this.remoteSet(t,e),i&&(this.listeners[t]&&this.listeners[t].forEach(n=>n({[t]:a(this,ct)[t]})),this.listeners["*"]&&this.listeners["*"].forEach(n=>n({[t]:a(this,ct)[t]})))}remoteSet(t,e){a(this,oi).storeInsertKeys(a(this,ai),this.name,[{key:t,payload:e}])}async bulkSet(t){t.forEach(({key:e,payload:r})=>{a(this,ct)[e]=r}),a(this,oi).storeInsertKeys(a(this,ai),this.name,t)}async update(t,e,r=!0){R(this,ru,cT).call(this,t,e,r)}async delete(t,e=!0,r=!1){if(a(this,ct)[t]&&delete a(this,ct)[t],e)return a(this,oi).storeDeleteKeys(a(this,ai),this.name,[{key:t}]);r&&(this.listeners[t]&&(this.listeners[t].forEach(i=>i({[t]:void 0})),delete this.listeners[t]),this.listeners["*"]&&this.listeners["*"].forEach(i=>i({[t]:void 0})))}async bulkDelete(t){return t.forEach(({key:e})=>{a(this,ct)[e]&&delete a(this,ct)[e]}),a(this,oi).storeDeleteKeys(a(this,ai),this.name,t)}get(t){if(a(this,ct)[t])return a(this,ct)[t]}getAll(){return a(this,ct)}clear(){f(this,ct,{})}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get bulkRateLimits(){return this.bulkRateLimitConfig}updateBulkRateLimits(t,e){this.bulkRateLimitConfig.maxInvocations=t,this.bulkRateLimitConfig.period=e}subscribe(t,e){if(this.listeners[t]){this.listeners[t].push(e);return}this.listeners[t]=[e]}unsubscribe(t,e){var r;if(e){this.listeners[t]=((r=this.listeners[t])==null?void 0:r.filter(i=>i!==e))||[];return}this.listeners[t]&&delete this.listeners[t]}populate(t){f(this,ct,t)}}ct=new WeakMap,ai=new WeakMap,oi=new WeakMap,ru=new WeakSet,cT=function(t,e,r=!0){let i;const n=a(this,ct)[t],o=Object.prototype.toString.call(e),c=Object.prototype.toString.call(n);if(o!==c){this.set(t,e);return}switch(c){case"[object Array]":i=[...n,...e];break;case"[object Object]":i={...n,...e};break;case"[object Map]":i=new Map([...n,...e]);break;case"[object Set]":i=new Set([...n,...e]);break;default:i=e;break}this.set(t,i,r)},Ro([qt(Wn,"rateLimitConfig")],zn.prototype,"remoteSet",1),Ro([qt(Wn,"bulkRateLimitConfig")],zn.prototype,"bulkSet",1),Ro([qt(Wn,"rateLimitConfig")],zn.prototype,"update",1),Ro([qt(Wn,"rateLimitConfig")],zn.prototype,"delete",1),Ro([qt(Wn,"bulkRateLimitConfig")],zn.prototype,"bulkDelete",1);class D1{constructor(t,e){m(this,lc);m(this,iu);p(this,"stores",new Map);m(this,ci,void 0);m(this,di,"");m(this,uc,void 0);m(this,_s,new Map);f(this,ci,e),f(this,di,t.getValue("meetingId")),f(this,uc,t),R(this,iu,dT).call(this)}create(t,e=!1){if(W_.includes(t)&&!e)throw new C(`'${t}' is a reserved store name.`,"0601");const r=new zn({name:t,socketHandler:a(this,ci),meetingId:a(this,di)});return a(this,ci).storeGetKeys(a(this,di),t,[]),new Promise((n,o)=>{const c=setTimeout(()=>{a(this,_s).delete(t),o(Error("Failed"))},3e3);a(this,_s).set(t,{rejectTimeout:c,resolve:n,store:r})})}refresh(t){const e=this.stores.get(t);return e?(e.clear(),a(this,ci).storeGetKeys(a(this,di),t,[]),new Promise((i,n)=>{const o=setTimeout(()=>{a(this,_s).delete(t),n(Error("Store refresh timed out"))},3e3);a(this,_s).set(t,{rejectTimeout:o,resolve:i,store:e})})):Promise.reject(Error(`Store '${t}' does not exist`))}}ci=new WeakMap,di=new WeakMap,lc=new WeakSet,em=function(){return a(this,uc).getValue("peerId")},uc=new WeakMap,_s=new WeakMap,iu=new WeakSet,dT=function(){[or.storeInsertKeys,or.storeGetKeys,or.storeDeleteKeys].forEach(t=>{a(this,ci).on(t,async e=>{var n,o;if(e.pluginId!==a(this,di))return;const r=(n=e.storeItems)==null?void 0:n.map(c=>{var d;return{timestamp:c.timestamp,peerId:c.peerId,payload:JSON.parse((d=c.payload)!=null&&d.length?new TextDecoder().decode(c.payload):"{}"),key:c.storeKey}});if(t===or.storeGetKeys){const c=a(this,_s).get(e.storeName),d=this.stores.get(e.storeName)||(c==null?void 0:c.store);if(a(this,_s).get(e.storeName)&&(this.stores.set(e.storeName,c.store),c.resolve(d),clearTimeout(c.rejectTimeout),a(this,_s).delete(e.storeName)),!d)return;r.forEach(l=>{d.set(l.key,l.payload,!1,!1)});return}const i=this.stores.get(e.storeName)||((o=a(this,_s).get(e.storeName))==null?void 0:o.store);i!==void 0&&(t===or.storeInsertKeys&&r.forEach(({key:c,peerId:d,payload:l})=>{d!==a(this,lc,em)&&i.set(c,l,!1,!0)}),t===or.storeDeleteKeys&&r.forEach(({key:c,peerId:d})=>{d!==a(this,lc,em)&&i.delete(c,!1,!0)}))})})};function Ui(s){var t,e,r,i,n,o,c,d,l,u,h,g,v;return s?{media:{audio:{enabled:s.audioEnabled,trackId:(t=s.audioTrack)==null?void 0:t.id,permission:"mediaPermissions"in s?(e=s.mediaPermissions)==null?void 0:e.audio:null},video:{enabled:s.videoEnabled,trackId:(r=s.videoTrack)==null?void 0:r.id,permission:"mediaPermissions"in s?(i=s.mediaPermissions)==null?void 0:i.video:null},screenshare:{enabled:s.screenShareEnabled,permission:"mediaPermissions"in s?(n=s.mediaPermissions)==null?void 0:n.screenshare:null,audio:{enabled:(c=(o=s.screenShareTracks)==null?void 0:o.audio)==null?void 0:c.enabled,trackId:(l=(d=s.screenShareTracks)==null?void 0:d.audio)==null?void 0:l.id},video:{enabled:(h=(u=s.screenShareTracks)==null?void 0:u.video)==null?void 0:h.enabled,trackId:(v=(g=s.screenShareTracks)==null?void 0:g.video)==null?void 0:v.id}}}}:{}}var N1=Object.defineProperty,L1=Object.getOwnPropertyDescriptor,Yn=(s,t,e,r)=>{for(var i=r>1?void 0:r?L1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&N1(t,e,i),i};const V1=.8,x1=1.2;let hr=(QS=class extends Bt{constructor(t,e,r,i){const n=t.getValue("logger");super(n);m(this,dn);m(this,li);m(this,ln);m(this,nu);m(this,un);m(this,pc);m(this,ou);m(this,cu);p(this,"id");p(this,"userId");p(this,"name");p(this,"picture");p(this,"isHost");p(this,"customParticipantId");p(this,"flags");p(this,"device");p(this,"videoTrack");p(this,"audioTrack");p(this,"screenShareTracks");p(this,"videoEnabled");p(this,"audioEnabled");p(this,"screenShareEnabled");p(this,"producers");p(this,"manualProducerConfig");m(this,_a,void 0);p(this,"supportsRemoteControl",!1);m(this,Ca,void 0);p(this,"presetName");m(this,Kt,void 0);m(this,wt,void 0);m(this,hc,void 0);m(this,ui,new Map);m(this,Pr,1);m(this,au,Ah(t=>{if(!this.videoTrack)return;const{clientWidth:e,clientHeight:r}=t,{width:i,height:n}=this.videoTrack.getSettings();if(!i||!n)return;const o=n/r,c=i/e,d=Math.max(o,c);d>x1&&a(this,Pr)===1?(f(this,Pr,0),a(this,Kt).getValue("peerSessionStore").emit(P.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,Pr)})):d<V1&&a(this,Pr)===0&&(f(this,Pr,1),a(this,Kt).getValue("peerSessionStore").emit(P.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,Pr)}))},2e3));f(this,Kt,t);const{id:o,userId:c,displayName:d,device:l,picture:u,isHost:h,flags:g,stageStatus:v,customParticipantId:y,audioMuted:k,audioTrack:I,videoEnabled:D=!1,videoTrack:N,producers:B,metadata:U}=e;this.id=o,this.userId=c,this.name=d,this.device=l,this.picture=u,this.isHost=h,this.flags=g,this.manualProducerConfig=U_,f(this,Ca,v!=null?v:"ON_STAGE"),this.customParticipantId=y,this.audioEnabled=!k,this.audioTrack=I,this.videoEnabled=D,this.videoTrack=N,this.screenShareTracks={audio:void 0,video:void 0},this.producers=B!=null?B:[],this.presetName=U==null?void 0:U.preset_name,f(this,_a,!1),f(this,wt,r),f(this,hc,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),R(this,pc,tm).call(this)}get stageStatus(){return a(this,Ca)}get telemetry(){return a(this,Kt).getValue("telemetry")}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(this.logger.info("Participant::setVideoEnabled::videoUpdate",{...Ui(this)}),this.logger.info(`Emitting videoUpdate to the UI Kit for remote peerId: ${this.id}. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(this.logger.info("Participant::setAudioEnabled::audioUpdate",{...Ui(this)}),this.logger.info(`Emitting audioUpdate to the UI Kit for remote peerId: ${this.id}. Audio enabled: ${this.audioEnabled}. Audio track available: ${!!this.audioTrack}.`),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}))}setScreenShareEnabled(t,e=!0){var r;this.screenShareEnabled=t,e&&(this.logger.info(`Emitting screenShareUpdate to the UI Kit for remote peerId: ${this.id}. Screen sharing enabled: ${this.screenShareEnabled}. Video track available: ${!!((r=this.screenShareTracks)!=null&&r.video)}.`),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}setupEvents(){this.on("videoUpdate",R(this,pc,tm)),a(this,li,so)&&(this.on("audioUpdate",R(this,ou,uT)),this.on("screenShareUpdate",R(this,cu,hT)))}async pin(){if(!a(this,ln,wd))throw new C("Can`t pin participant without joining room","1205");if(!a(this,wt).permissions.pinParticipant)throw new C("You do not have permission to pin participants.","1201");return a(this,dn,bd).pinPeer(this.id)}async unpin(){if(!a(this,ln,wd))throw new C("Can`t unpin participant without joining room","1205");if(!a(this,wt).permissions.pinParticipant)throw new C("You do not have permission to unpin participants.","1201");return a(this,dn,bd).pinPeer(null)}setIsPinned(t,e=!0){var i;f(this,_a,t);const r=t?"pinned":"unpinned";(i=a(this,un,Pd))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}async disableAudio(){const t=this.id;if(this.logger.info(`Local peer ${a(this,wt).id} is disabling mic of a remote peer ${t}`),!a(this,ln,wd))throw new C("Can`t disable participant audio without joining room","1205");if(a(this,wt).permissions.canDisableParticipantAudio)return a(this,dn,bd).disableAudio(t);throw this.logger.error(`Local peer ${a(this,wt).id} is not authorized to disable mic of a remote peer ${t}`),new C("Unauthorized: User does not have permission to disable participant audio.","1201")}async kick(){const t=this.id;if(this.logger.info(`Local peer ${a(this,wt).id} is kicking a remote peer ${t} out of the meeting.`),!a(this,nu,lT))throw new C("Can`t kick participant without joining room","1205");if(a(this,wt).permissions.kickParticipant){await a(this,Kt).getValue("peerSessionStore").emitAsync(P.KICK_PEER,{peerId:t});return}throw this.logger.error(`Local peer ${a(this,wt).id} is not authorized to kick a remote peer ${t} out of the meeting.`),new C("Unauthorized: User does not have permission to kick participants.","1201")}async disableVideo(){const t=this.id;if(this.logger.info(`Local peer ${a(this,wt).id} is disabling webcam of a remote peer ${t}.`),!a(this,ln,wd))throw new C("Can`t disable participant video without joining room","1205");if(a(this,wt).permissions.canDisableParticipantVideo)return a(this,dn,bd).disableVideo(t);throw this.logger.error(`Local peer ${a(this,wt).id} is not authorized to disable webcam of a remote peer ${t}.`),new C("Unauthorized: User does not have permission to disable participant video.","1201")}async getPermissions(){return a(this,hc).getUserPermissions(this.userId)}setStageStatus(t){f(this,Ca,t),this.emit("stageStatusUpdate",this)}get isPinned(){return a(this,_a)}registerVideoElement(t){var r,i,n,o;if(!t)return;let e;(i=(r=a(this,ui).get(t))==null?void 0:r.observer)==null||i.disconnect(),"ResizeObserver"in window&&(e=new ResizeObserver(()=>a(this,au).call(this,t)),e.observe(t)),a(this,ui).set(t,{observer:e}),this.updateVideo(t),(o=a(this,un,Pd))==null||o.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(n=this.raised)!=null?n:!1)}deregisterVideoElement(t){var e,r,i,n;if(!t){(e=a(this,un,Pd))==null||e.removeSource(this.id);return}t.srcObject=void 0,(i=(r=a(this,ui).get(t))==null?void 0:r.observer)==null||i.disconnect(),a(this,ui).delete(t),(n=a(this,un,Pd))==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 i=new MediaStream;i.addTrack(this.videoTrack),t.srcObject=i}else t.srcObject=void 0;t.style.display=this.videoEnabled?"block":"none"}},_a=new WeakMap,Ca=new WeakMap,Kt=new WeakMap,dn=new WeakSet,bd=function(){return a(this,Kt).getValue("roomNodeClient")},li=new WeakSet,so=function(){return a(this,Kt).getValue("audioPlayback")},ln=new WeakSet,wd=function(){return a(this,Kt).getValue("connectionHandler").mediaJoined},nu=new WeakSet,lT=function(){return a(this,Kt).getValue("connectionHandler").socketJoined},wt=new WeakMap,hc=new WeakMap,ui=new WeakMap,un=new WeakSet,Pd=function(){return a(this,Kt).getValue("pip")},Pr=new WeakMap,au=new WeakMap,pc=new WeakSet,tm=function(){Array.from(a(this,ui).keys()).forEach(this.updateVideo)},ou=new WeakSet,uT=function(){var t,e;this.audioEnabled&&this.audioTrack?(t=a(this,li,so))==null||t.addParticipantTrack(this.id,this.audioTrack):(e=a(this,li,so))==null||e.removeParticipantTrack(this.id)},cu=new WeakSet,hT=function(){var t,e;this.screenShareEnabled&&this.screenShareTracks.audio?(t=a(this,li,so))==null||t.addParticipantTrack(`screenshare-${this.id}`,this.screenShareTracks.audio):(e=a(this,li,so))==null||e.removeParticipantTrack(`screenshare-${this.id}`)},QS);Yn([E.trace("Participant.disableAudio")],hr.prototype,"disableAudio",1),Yn([E.trace("Participant.kick")],hr.prototype,"kick",1),Yn([E.trace("Participant.disableVideo")],hr.prototype,"disableVideo",1),Yn([E.trace("Participant.getPermissions")],hr.prototype,"getPermissions",1),Yn([E.trace("Participant.setStageStatus")],hr.prototype,"setStageStatus",1),hr=Yn([pt("1200")],hr);class Io extends Nv{constructor(t,e){const{onAddEvent:r="participantJoined",onDeleteEvent:i="participantLeft",onClearEvent:n="participantsCleared"}=e!=null?e:{};super({onAddEvent:r,onDeleteEvent:i,onClearEvent:n},t)}add(t,e=!0){return this.has(t.id)&&Object.is(this.get(t.id),t)===!1&&this.delete(t.id),super.add(t,e)}clear(t=!0,e=!1){return super.clear(t,e)}delete(t,e=!0,r=!1){return super.delete(t,e,r)}}class $1 extends Bn{constructor(e){super(e);m(this,hi,void 0);f(this,hi,new Map)}__set(e,r){return a(this,hi).set(e,r)}__clear(){return a(this,hi).clear()}get(e){return a(this,hi).get(e)}toArray(){return Array.from(a(this,hi).values())}}hi=new WeakMap;class U1{constructor(){p(this,"_orderedArray");p(this,"_map");this._map=new Map,this._orderedArray=[]}add(t,e){if(!this._map.has(t))return this._map.set(t,{peerId:t,priority:e}),this._orderedArray.splice(Math.max(e-1,0),0,t),this.index(t);const r=this.index(t);this.delete(t);const i=this.add(t,e);return r!==i?i:-1}delete(t){if(this._map.has(t)){const e=this.index(t);this._map.delete(t),this._orderedArray.splice(e,1)}}index(t){return this._map.has(t)?this._orderedArray.indexOf(t):-1}[Symbol.iterator](){return this._orderedArray[Symbol.iterator]()}}class B1{constructor(){p(this,"_activeSpeakerPeers");p(this,"_compulsoryPeers");this._activeSpeakerPeers=new U1,this._compulsoryPeers=new Set}add(t,e,r){if(!t)return-1;if(e<0)return this._compulsoryPeers.add(t),0;const i=r.getValue("logger");if(this.compulsoryPeers.includes(t)&&(e>0||e===246267631)){if(i.info("SelectedPeer::removing_compulsory_peer",{selectedPeer:{peerId:t}}),this._removeFromCompulsoryPeer(t),e===246267631)return-1}else if(e===229490415)return this.delete(t,r),-1;return this._activeSpeakerPeers.add(t,e)}delete(t,e){const r=e==null?void 0:e.getValue("logger");r==null||r.info("SelectedPeer::deleting_peer_from_selectedPeer",{selectedPeer:{peerId:t}}),this._removeFromCompulsoryPeer(t),this._activeSpeakerPeers.delete(t)}reassignPeer(t,e,r){const i=this._activeSpeakerPeers.index(t),n=this._compulsoryPeers.has(t);this.delete(t,r),n&&this.add(e,-1,r),i>=0&&this.add(e,i+1,r)}index(t){return this._activeSpeakerPeers.index(t)}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(t){this._compulsoryPeers.delete(t)}}const eS=new B1;var F1=Object.defineProperty,H1=Object.getOwnPropertyDescriptor,$s=(s,t,e,r)=>{for(var i=r>1?void 0:r?H1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&F1(t,e,i),i};const tS=["ACTIVE_GRID","PAGINATED","MANUAL"];let ns=(XS=class extends Bt{constructor(t,e,r){var o,c;const i=t.getValue("logger");super(i);m(this,mc);m(this,hn);m(this,Ra);p(this,"waitlisted");p(this,"joined");p(this,"active");p(this,"videoSubscribed");p(this,"audioSubscribed");p(this,"pinned");p(this,"all");m(this,xe,void 0);m(this,pn,void 0);m(this,Vt,void 0);p(this,"rateLimitConfig",{maxInvocations:5,period:1});p(this,"viewMode");p(this,"currentPage");p(this,"lastActiveSpeaker");p(this,"selectedPeers",eS);const n=(c=(o=t.getValue("defaults"))==null?void 0:o.viewMode)!=null?c:"ACTIVE_GRID";if(!tS.includes(n))throw new C(`Invalid view mode: ${n}. Try ACTIVE_GRID, PAGINATED or MANUAL.`,"1207");f(this,xe,t),f(this,pn,e),f(this,Vt,r),this.waitlisted=new Io(i),this.joined=new Io(i),this.videoSubscribed=new Io(i),this.audioSubscribed=new Io(i),this.active=this.videoSubscribed,this.pinned=new Io(i),this.all=new $1(i),this.viewMode=n,this.currentPage=this.viewMode==="PAGINATED"?1:0,this.setupEvents()}get pip(){return a(this,xe).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get telemetry(){return a(this,xe).getValue("telemetry")}setupEvents(){a(this,xe).getValue("peerSessionStore").on(P.E2EE_ACTIVE_CONSUMER,({peerId:e})=>{var r;((r=a(this,xe).getValue("modules").e2ee)==null?void 0:r.enabled)!==!0&&this.emit("media_decode_error",{reason:`Got encrypted media for participantId ${e}, but encryption wasn't enabled in init.defaults`,code:"1702"})});const t=a(this,xe).getValue("audioPlayback");t&&this.audioSubscribed.on("participantLeft",e=>{t.removeParticipantTrack(e.id)})}get count(){return this.joined.size}get maxActiveParticipantsCount(){var t;return(t=a(this,xe))==null?void 0:t.getValue("maxPreferredStreams")}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new C("0 <= Max active participants count limit <= 24","1203");a(this,xe).setValue("maxPreferredStreams",t),a(this,Ra,rh)&&a(this,xe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}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)/Math.max(this.maxActiveParticipantsCount-t,1))}return 0}acceptWaitingRoomRequest(t){var r,i;if(!a(this,hn,kd))throw new C("Can`t accept waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;return a(this,Vt).acceptWaitingRoomRequest([e])}async acceptAllWaitingRoomRequest(t){const e=t.map(r=>{var i,n;return(n=(i=this.waitlisted.get(r))==null?void 0:i.userId)!=null?n:r});return a(this,Vt).acceptWaitingRoomRequest(e)}async rejectWaitingRoomRequest(t){var r,i;if(!a(this,hn,kd))throw new C("Can`t reject waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;a(this,Vt).rejectWaitingRoomRequest([e])}async setViewMode(t){if(this.logger.info("Participants::set_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),!(r=>tS.includes(r))(t))throw this.logger.error("Participants::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.`,"1207");if(this.viewMode===t){this.logger.info("Participants::setViewMode::view_mode_same_as_previous");return}this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,a(this,xe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="ACTIVE_GRID"?(this.currentPage=0,a(this,xe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="MANUAL"&&(this.currentPage=0,a(this,xe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})}async subscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new C("MANUAL subscription mode was not activated.","1206");t.forEach(r=>{const i=this.joined.get(r);i&&(e.includes("audio")&&(i.manualProducerConfig={...i.manualProducerConfig,audio:!0},this.audioSubscribed.has(i.id)||this.audioSubscribed.add(i)),e.includes("video")&&(i.manualProducerConfig={...i.manualProducerConfig,video:!0},this.videoSubscribed.has(i.id)||this.videoSubscribed.add(i)),e.includes("screenshareAudio")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!0},this.audioSubscribed.has(i.id)||this.audioSubscribed.add(i)),e.includes("screenshareVideo")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!0},this.videoSubscribed.has(i.id)||this.videoSubscribed.add(i)))}),a(this,xe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}async unsubscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new C("MANUAL subscription mode was not activated.","1206");t.forEach(r=>{const i=this.joined.get(r);i&&(e.includes("audio")&&(i.manualProducerConfig={...i.manualProducerConfig,audio:!1},i.manualProducerConfig.screenshareAudio||this.audioSubscribed.delete(i.id)),e.includes("video")&&(i.manualProducerConfig={...i.manualProducerConfig,video:!1},i.manualProducerConfig.screenshareVideo||this.videoSubscribed.delete(i.id)),e.includes("screenshareAudio")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!1},i.manualProducerConfig.audio||this.audioSubscribed.delete(i.id)),e.includes("screenshareVideo")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!1},i.manualProducerConfig.video||this.videoSubscribed.delete(i.id)))}),a(this,xe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}getPeerIdsForCurrentPage(){this.logger.info("Participants::getPeerIdsForCurrentPage()",{pageNavigation:{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}});const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(c=>this.joined.has(c)),r=Array.from(this.pinned.keys()).filter(c=>!e.includes(c)),i=Array.from(this.joined.toArray().filter(c=>c.stageStatus==="ON_STAGE").map(c=>c.id)),n=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-r.length)),o=this.currentPage*(this.maxActiveParticipantsCount-e.length-r.length);return e.concat(r,i.slice(n,o))}async setPage(t){if(this.logger.info("Participants::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 this.logger.error("Participants::invalid_page_number"),new C(`Invalid page: ${t}. Page must be an integer and greater than 0 and less than or equal to .pageCount`,"1202");this.currentPage=t,a(this,xe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.viewMode,page:t}),this.emit("pageChanged",{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount})}}async disableAllAudio(t){if(this.logger.info("Participants::disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),!a(this,Ra,rh))throw new C("Can`t disable all audio without joining room","1205");if(a(this,pn).permissions.canAllowParticipantAudio)return a(this,mc,sm).muteAll(t);throw this.logger.error("Participants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new C("Unauthorized: User does not have permission to disable peer audio.","1201")}async disableAllVideo(){if(this.logger.info("Participants::disable_all_video"),!a(this,Ra,rh))throw new C("Can`t disable all video without joining room","1205");if(a(this,pn).permissions.canAllowParticipantVideo)return a(this,mc,sm).muteAllVideo();throw this.logger.error("Participants::unauthorized_disable_all_video"),new C("Unauthorized: User does not have permission to disable peer video.","1201")}async kickAll(){if(this.logger.info("Participants::kick_all"),a(this,xe).getValue("viewType")!=="LIVESTREAM"&&!a(this,hn,kd))throw new C("Can`t kick all without joining room","1205");if(!a(this,pn).permissions.kickParticipant)throw this.logger.error("Participants::unauthorized_kick_all"),new C("Unauthorized: User does not have permission to kick peers.","1201");const e=!0;a(this,Vt).kickAll(e)}async broadcastMessage(t,e,r){if(this.logger.info("Participants::broadcastMessage"),!a(this,hn,kd))throw new C("Can`t broadcast message without joining room","1205");if(!(t!=null&&t.trim()))throw new C("`type` must be a non-empty string.","1209");if(r)if("meetingIds"in r)await a(this,Vt).broadcastToMeetings(t,r.meetingIds,e);else{let i=[];"participantIds"in r?i=r.participantIds:i=this.joined.toArray().filter(n=>{var o;return(o=r.presetNames)==null?void 0:o.includes(n.presetName)}).map(n=>n.id),await a(this,Vt).broadcastToPeers(t,i,e)}else await a(this,Vt).broadcastMessage(t,e)}async getAllJoinedPeers(t,e,r){return(await a(this,Vt).getRoomPeers(t,e,r)).peers.map(pr.formatSocketPeerMessage)}async updatePermissions(t,e){const r=this.joined.toArray().filter(n=>t.includes(n.id)).map(n=>n.userId),i=[...new Set(r)];if(!i.length)throw new C("Cannot update permissions, no valid userIDs found","1204");a(this,Vt).updatePermissions(i,e)}async getParticipantsInMeetingPreJoin(){return a(this,Vt).getRoomPeersNonPaginated()}},xe=new WeakMap,mc=new WeakSet,sm=function(){return a(this,xe).getValue("roomNodeClient")},hn=new WeakSet,kd=function(){var t;return((t=a(this,xe).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},Ra=new WeakSet,rh=function(){var t;return((t=a(this,xe).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},pn=new WeakMap,Vt=new WeakMap,XS);$s([E.trace("Participants.setViewMode")],ns.prototype,"setViewMode",1),$s([E.trace("Participants.setPage")],ns.prototype,"setPage",1),$s([E.trace("Participants.disableAllAudio")],ns.prototype,"disableAllAudio",1),$s([E.trace("Participants.disableAllVideo")],ns.prototype,"disableAllVideo",1),$s([E.trace("Participants.kickAll")],ns.prototype,"kickAll",1),$s([E.trace("Participants.broadcastMessage"),qt(Wn,"rateLimitConfig")],ns.prototype,"broadcastMessage",1),$s([E.trace("Participants.getAllJoinedPeers"),qt({maxInvocations:10,period:60})],ns.prototype,"getAllJoinedPeers",1),$s([E.trace("Participant.updatePermissions"),qt({maxInvocations:1e3,period:60})],ns.prototype,"updatePermissions",1),$s([E.trace("Participants.getParticipantsInMeetingPreJoin")],ns.prototype,"getParticipantsInMeetingPreJoin",1),ns=$s([pt("1200")],ns);var q1=Object.defineProperty,j1=Object.getOwnPropertyDescriptor,Bi=(s,t,e,r)=>{for(var i=r>1?void 0:r?j1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&q1(t,e,i),i};const G1=5e3,W1=1e4,Qn=(ZS=class{constructor(s,t,e){m(this,gn);m(this,du);m(this,lu);m(this,gc);m(this,uu);m(this,hu);p(this,"participants");p(this,"self");p(this,"selectedPeers",eS);p(this,"maxSpatialLayerUpdates",new Map);p(this,"consumerPeerMap");p(this,"events");p(this,"roomSocketHandler");p(this,"context");p(this,"videoPeerConsumerMap",new Map);m(this,hs,{mode:"ACTIVE_GRID",page:0});m(this,Fs,!1);m(this,pi,!1);p(this,"isRebuildingReconnectSnapshot",!1);m(this,Ze,new Map);m(this,kr,void 0);m(this,mn,void 0);m(this,pu,({state:s})=>{s==="disconnected"||s==="stageLeft"||(this.isRebuildingReconnectSnapshot=!1,R(this,hu,fT).call(this),a(this,Ze).clear(),f(this,kr,void 0))});p(this,"updateConsumerSpatialLayers",Ah(()=>{const s={},t=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(t.entries()).forEach(([e,r])=>{s[r]===void 0&&(s[r]={layer:r,consumerIds:[]}),s[r].consumerIds.push(e)}),Object.keys(s).forEach(e=>{const r=s[e];this.logger.log(`Switching max spatial layer to ${r.layer}`,{consumerIds:r.consumerIds}),this.roomNodeClient.switchConsumersToLayer(r.consumerIds,r.layer)})},2e3));p(this,"updateConsumers",async(s,t)=>{this.logger.info(`updateConsumers: Starting serialized consumer updates: createProducerIds=[${s.map(({producerId:e})=>e).join(",")}], deleteConsumerIds=[${t.join(",")}], consumersSyncing=${a(this,Fs)}.`);try{s.length!==0&&(this.logger.info(`updateConsumers: Creating consumers for producerIds=[${s.map(({producerId:e})=>e).join(",")}].`),await this.roomNodeClient.createConsumers(s),this.logger.info("updateConsumers: Successfully created consumers."))}catch(e){this.logger.error("updateConsumers: Error creating consumers",{error:e})}try{t.length!==0&&(this.logger.info(`updateConsumers: Closing consumers after grace period: consumerIds=[${t.join(",")}].`),await this.roomNodeClient.closeConsumersById(t),this.logger.info("updateConsumers: Successfully closed consumers."))}catch(e){this.logger.error("updateConsumers: Error closing consumers",{error:e})}this.logger.info("updateConsumers: Completed consumer updates.")});this.context=s,this.roomSocketHandler=e,this.participants=new ns(s,t,this.roomSocketHandler),this.self=t,this.consumerPeerMap=new Map,this.events=Es,t.config.viewType!=="CHAT"&&(this.setupEventsGlobal(),R(this,uu,gT).call(this)),this.setupEvents(),this.self.on("roomLeft",a(this,pu))}get roomNodeClient(){return this.context.getValue("roomNodeClient")}get mediaJoined(){var s;return((s=this.roomNodeClient)==null?void 0:s.mediaJoined)===!0}get pip(){return this.context.getValue("pip")}static async init(s,t,e){return new Qn(s,t,e)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}handleSocketPeers(s){var d;const t=new Set(this.roomSocketHandler.socket.supersededLocalPeerIds),e=(d=s==null?void 0:s.filter(l=>!l.waitlisted&&!t.has(l.peerId)))!=null?d:[],r=new Set(e.map(({peerId:l})=>l)),i=t.size>0||this.participants.joined.size>0,n=this.context.getValue("viewType"),o=this.context.getValue("stageStatus"),c=this.mediaJoined&&(n!==Ss.Livestream||o==="ON_STAGE");this.isRebuildingReconnectSnapshot=i&&c,this.isRebuildingReconnectSnapshot||(this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear(),this.participants.pinned.clear()),this.participants.joined.forEach(({id:l})=>{var u;r.has(l)||(u=this.pip)==null||u.removeSource(l)}),this.participants.joined.clear(),e.forEach(l=>{var h;const u=this.createParticipantObjFromSocketPeer(l);if(this.isRebuildingReconnectSnapshot){const g=(h=this.participants.videoSubscribed.get(l.peerId))!=null?h:this.participants.audioSubscribed.get(l.peerId);g&&(u.manualProducerConfig={...g.manualProducerConfig})}this.logger.debug(`Processing socket join for ${this.self.id===u.id?"local peer":"remote peer"} ${u.id} listed in socket peers.`),this.onParticipantSocketJoined(u),this.logger.debug(`Processed socket join for ${this.self.id===u.id?"local peer":"remote peer"} ${u.id} listed in socket peers.`)})}handlePeerMediaJoinedBroadcast({participant:s,producerHandoverFromPeerId:t}){var i;if(!s)return;const e=s.peerId===this.self.id,r=(i=s.producerStates)!=null?i:[];this.logger.info(`${e?"Local peer":"Remote peer"} ${s.peerId} has joined media room with producerStates: ${JSON.stringify(r)}`),t&&t!==s.peerId&&r.length>0&&(this.logger.info(`Producer handover detected from ${t} to ${s.peerId} for producer ids ${r.map(({producerId:n})=>n).join(",")}`),this.context.getValue("peerSessionStore").emit(P.PRODUCER_HANDOVER,{oldPeerId:t,newPeerId:s.peerId,producerIds:r.map(({producerId:n})=>n)})),this.logger.debug(`Processing media join for newly joined ${e?"local peer":"remote peer"} ${s.peerId}.`),this.onParticipantMediaJoined(s.peerId,r),this.logger.debug(`Processed media join for newly joined ${e?"local peer":"remote peer"} ${s.peerId}.`)}clearParticipantMediaState(s,t,e){const r=s;e?t==="audio"?(r.screenShareTracks.audio=void 0,r.setScreenShareEnabled(r.screenShareEnabled&&r.screenShareTracks.video!==void 0)):(r.setScreenShareEnabled(!1),r.screenShareTracks={audio:void 0,video:void 0}):t==="audio"?(r.setAudioEnabled(!1),r.audioTrack=void 0):(r.setVideoEnabled(!1),this.updatePipSource(r.id,!1),r.videoTrack=void 0)}setupEvents(){this.roomSocketHandler.on(x.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),this.context.getValue("peerSessionStore").on(P.SOCKET_PEERS,this.handleSocketPeers.bind(this)),this.roomSocketHandler.on(this.events.peerJoinedBroadcast,this.handlePeerMediaJoinedBroadcast.bind(this)),this.roomSocketHandler.on(this.events.selfJoinComplete,async({participants:s,selectedPeers:t,roomState:e})=>{this.logger.info(`Local peer has joined media room. Processing media joins for existing ${s==null?void 0:s.length} peers.`),s.forEach(({peerId:n,producerStates:o})=>{this.logger.debug(`Processing media join for ${this.self.peerId===n?"local peer":"existing remote peer"} ${n}.`),this.onParticipantMediaJoined(n,o),this.logger.debug(`Processed media join for ${this.self.peerId===n?"local peer":"existing remote peer"} ${n}.`)}),this.isRebuildingReconnectSnapshot&&this.rewireConsumersOnLocalUserReconnect();const{audioPeers:r,compulsoryPeers:i}=t!=null?t:{};if(this.applyPinnedSnapshot(e.pinnedPeerIds),this.computeActivateParticipants(r!=null?r:[],i),this.participants.viewMode==="PAGINATED"){const n=Math.max(1,Math.min(this.participants.currentPage,this.participants.pageCount));n!==this.participants.currentPage&&await this.participants.setPage(n)}this.isRebuildingReconnectSnapshot=!1,this.logger.info("Participants reconciliation on local peer's media join is complete. Reconciling consumers."),this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}),this.context.getValue("peerSessionStore").on(P.MAX_SPATIAL_LAYER_CHANGE,({peerId:s,maxSpatialLayer:t})=>{const e=this.videoPeerConsumerMap.get(s);e&&(this.maxSpatialLayerUpdates.set(e,t),this.updateConsumerSpatialLayers())}),this.context.getValue("peerSessionStore").on(P.PRODUCER_HANDOVER,s=>this.handleProducerHandover(s)),this.context.getValue("peerSessionStore").on(P.NEW_PRODUCER,({peerId:s,producer:t})=>{if(!t){this.logger.error(`Received new remote producer for peer ${s}. producer is invalid/empty.`);return}const e=this.participants.joined.get(s);if(!e){this.logger.warn(`Received new ${t.screenShare?"screenshare":"participant"} ${t.kind} remote producer ${t.producerId} for a non-existent peer ${s}`);return}const r=e.producers.find(({producerId:n})=>n===t.producerId);let i="REPLACED";r?(Object.assign(r,t),i="REPLACED"):(e.producers.push(t),i="INSERTED"),this.logger.info(`Scheduling syncConsumer post upserting (${i}) new producer ${t.producerId} to peer ${s} for ${t.screenShare?"screenshare":"participant"} ${t.kind}`),this.scheduleSyncConsumers({source:"NEW_REMOTE_PRODUCER"})}),this.context.getValue("peerSessionStore").on(P.PRODUCER_CLOSED,({peerId:s,producerId:t})=>{const e=this.participants.joined.get(s);if(!e){this.logger.warn(`Received producer closed event for producer ${t} of a peer ${s} that might have already left the meeting.`);return}const r=e.producers.find(i=>i.producerId===t);r?(this.logger.info(`${r.screenShare?"Screenshare":"Participant"} ${r.kind} producer ${t} of peer ${s} has closed. Updating media state and scheduling syncConsumers for reconciliation.`),this.clearParticipantMediaState(e,r.kind,r.screenShare),r.kind==="video"&&!r.screenShare&&this.videoPeerConsumerMap.get(s)===t&&this.videoPeerConsumerMap.delete(s),e.producers=e.producers.filter(i=>i.producerId!==t),this.scheduleSyncConsumers({source:"PRODUCER_CLOSED"})):this.logger.warn(`Received producer closed event for producer ${t} of a peer ${s}. Peer doesn't have the producer associated with it. Ignoring the event.`)}),this.context.getValue("peerSessionStore").on(P.PRODUCER_TOGGLE,({peerId:s,producerId:t,paused:e,kind:r})=>{const i=this.participants.joined.get(s);if(i){const n=i.producers.find(o=>o.producerId===t);if(!n){this.logger.warn(`Processing participant ${r} producer ${e?"paused":"resumed"} broadcast for remote producer ${t} of peer ${s} however producer is not associated with the peer. Ignoring the event.`);return}if(this.logger.info(`Processing participant ${r} producer ${e?"paused":"resumed"} broadcast for remote producer ${t} of peer ${s}. Reconciling media states and consumers.`),n.pause=e,r==="audio"&&i.setAudioEnabled(!e),r==="video"){const o=this.roomNodeClient.getConsumers().get(t);e?(i.setVideoEnabled(!1),this.updatePipSource(i.id,!1)):o&&!o.closed&&(i.videoTrack=o.track,i.setVideoEnabled(!0),this.updatePipSource(i.id,!0)),this.context.getValue("callstats").consumerSharedMediaState(t,{video:!e}),this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}}else this.logger.warn(`Processing participant ${r} producer ${e?"paused":"resumed"} broadcast for remote producer ${t} of a missing peer ${s}. Ignoring the event.`)}),this.roomSocketHandler.on(this.events.globalPeerPinBroadcast,s=>{let t;if(s&&(t=s.participantId),!this.mediaJoined)return;const e=t;this.onParticipantPinned(e);const r=this.participants.joined.get(e);r&&(this.logger.info(`globalPeerPinBroadcast: Scheduling audio/video consumer sync for pinned participant ${e} - ProducerCount: ${r.producers.length}, ConsumersSyncing: ${a(this,Fs)}, ProducerIds: [${r.producers.map(i=>i.producerId).join(", ")}]`),this.scheduleSyncConsumers({source:"GLOBAL_PEER_PIN"}))}),this.roomSocketHandler.on(this.events.selectedPeer,({audioPeers:s,compulsoryPeers:t})=>{this.mediaJoined&&this.onSelectedPeers(t.concat(s))}),this.roomSocketHandler.on(this.events.selectedPeerDiff,({entries:s})=>{if(!this.mediaJoined)return;const t=s.map(e=>({peerId:e.peerId,priority:e.priority}));this.updateActiveParticipantsWithPriorities(t,!0)})}waitingRoomRequestHandler(s){var r,i;this.logger.info(`Received waitlisted peers: ${((i=(r=s==null?void 0:s.requests)==null?void 0:r.map(n=>n.peerId))==null?void 0:i.join(", "))||"none"}`);const t=s.requests.filter(n=>!this.participants.waitlisted.get(n.peerId)),e=this.participants.waitlisted.toArray().filter(n=>!s.requests.find(o=>o.peerId===n.id));t.forEach(n=>this.participants.waitlisted.add(new hr(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))),e.forEach(n=>this.participants.waitlisted.delete(n.id))}get maxPreferredStreams(){return this.participants.maxActiveParticipantsCount}selectPagePeers(s){const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(d=>this.participants.joined.has(d)),r=Array.from(this.participants.pinned.keys()).filter(d=>!e.includes(d)),i=Array.from(this.participants.joined.toArray().filter(d=>d.stageStatus==="ON_STAGE").map(d=>d.id)),n=Math.max((s-1)*(this.maxPreferredStreams-e.length-r.length)),o=s*(this.maxPreferredStreams-e.length-r.length);return e.concat(r,i.slice(n,o))}selectActivePeers(s){const t=new Map,e=Array.from(this.participants.joined.toArray().filter(u=>u.stageStatus==="ON_STAGE").map(u=>(t.set(u.id,!0),u.id))),r=this.selectedPeers.peers,i=this.participants.pinned.toArray().reduce((u,h)=>(h.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(h.id):u.push(h.id),u),[]),n=this.self.stageStatus==="ON_STAGE"?1:0,o=s-n,c=new Set(r.concat(i).filter(u=>u!==this.self.id&&t.has(u)));let d=Array.from(c);const l=o-c.size;if(l>=0){const u=e.filter(h=>!c.has(h)&&h!==this.self.id).slice(0,l);d=Array.from(c).concat(u)}else d=d.slice(0,o);return d}updateMediaSubscribedMaps(s,t){const{page:e}=t!=null?t:{};s&&a(this,hs).mode!==s&&(a(this,hs).mode=s),e&&a(this,hs).page!==e&&(a(this,hs).page=e);const{mode:r,page:i}=a(this,hs);switch(r){case"PAGINATED":{if(!i)return;const n=this.selectPagePeers(i),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMap(this.participants.videoSubscribed,n),this.updateParticipantsMap(this.participants.audioSubscribed,o),this.logger.debug("ParticipantController::updateActive::updating_current_page_peers",{peerIds:n});break}case"ACTIVE_GRID":{const n=this.selectActivePeers(this.participants.maxActiveParticipantsCount),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMapMinReplacement(this.participants.videoSubscribed,n),this.updateParticipantsMap(this.participants.audioSubscribed,o);break}case"MANUAL":{this.reconcileManualSubscriptionMaps();break}default:throw new Error(`View mode ${s} not supported`)}}async scheduleSyncConsumers({source:s}){var e,r,i;const t=((e=a(this,hs))==null?void 0:e.mode)==="PAGINATED"&&!a(this,Fs)?200:0;this.logger.info(`scheduleSyncConsumers():: Source: ${s}, ViewMode: ${(r=a(this,hs))==null?void 0:r.mode}, ConsumersSyncing: ${a(this,Fs)}, Delay: ${t}, Page: ${(i=a(this,hs))==null?void 0:i.page}`),setTimeout(()=>this.syncConsumers(),t)}async syncConsumers(){var I,D,N,B,U,j,Z,re;const s=this.context.getValue("connectionHandler");if((I=s==null?void 0:s.socketState)!=null&&I.state&&s.socketState.state!=="connected"){R(this,gn,_d).call(this,"socket not connected"),this.logger.info("syncConsumers: Socket not connected, deferring sync.");return}if(((N=(D=s==null?void 0:s.mediaState)==null?void 0:D.recv)==null?void 0:N.state)!=="connected"){R(this,gn,_d).call(this,"Recv transport not connected"),this.logger.info("syncConsumers: Connection not ready, exiting.");return}if(R(this,du,pT).call(this),a(this,Fs)){f(this,pi,!0),this.logger.info("syncConsumers: Sync in progress, marking resyncRequired=true and exiting.");return}this.logger.info("syncConsumers: Starting sync operation."),f(this,Fs,!0),f(this,pi,!1);let t=[];this.participants.videoSubscribed.forEach(F=>{var vt,A;const ee=this.participants.joined.get(F.id),we=(A=(vt=F.producers)==null?void 0:vt.filter(S=>S.kind==="video"))!=null?A:[];ee&&(we!=null&&we.length)&&we.forEach(S=>{var ce,fe,V,_;const w=((fe=(ce=ee.manualProducerConfig)==null?void 0:ce.video)!=null?fe:!0)&&S.kind==="video"&&!S.screenShare,$=((_=(V=ee.manualProducerConfig)==null?void 0:V.screenshareVideo)!=null?_:!0)&&S.kind==="video"&&S.screenShare;(w||$)&&(S.pause||t.push(S))})}),this.participants.audioSubscribed.forEach(F=>{var vt,A;const ee=this.participants.joined.get(F.id),we=(A=(vt=F.producers)==null?void 0:vt.filter(S=>S.kind==="audio"))!=null?A:[];ee&&(we!=null&&we.length)&&we.forEach(S=>{var ce,fe,V,_;const w=((fe=(ce=ee.manualProducerConfig)==null?void 0:ce.audio)!=null?fe:!0)&&S.kind==="audio"&&!S.screenShare,$=((_=(V=ee.manualProducerConfig)==null?void 0:V.screenshareAudio)!=null?_:!0)&&S.kind==="audio"&&S.screenShare;(w||$)&&t.push(S)})}),t=$_(t,F=>F.producerId);const e=new Map;t.forEach(F=>{e.set(F.producerId,F)});const r=(U=(B=this.roomNodeClient)==null?void 0:B.getConsumers())!=null?U:new Map,i=[];r.forEach(F=>{F.closed&&i.push(F.id)});const n=(Z=(j=this.roomNodeClient)==null?void 0:j.removeClosedConsumers(i))!=null?Z:[];n.forEach(F=>{a(this,Ze).delete(F),this.consumerPeerMap.has(F)&&this.processConsumerClosed(F)}),n.length>0&&this.logger.info(`syncConsumers: Removed closed consumers: consumerIds=[${n.join(",")}].`);let o=[];const c=new Set,d=[],l=[];e.forEach(F=>{const ee=r.get(F.producerId);if(!ee){o.push(F);return}c.add(ee.id);const{needsRemap:we,wasMarkedForDeletion:vt}=R(this,gc,rm).call(this,ee,F);we&&l.push(ee.id),vt&&d.push(ee.id)});const u=[];r.forEach(F=>{F.closed||c.has(F.id)||R(this,lu,mT).call(this,F)&&u.push(F.id)});const h=Date.now(),g=[];let v=[];a(this,Ze).forEach((F,ee)=>{const we=r.get(ee);if(!we||we.closed){a(this,Ze).delete(ee);return}if(c.has(ee)){a(this,Ze).delete(ee);return}h-F>=W1?v.push(ee):g.push(ee)}),e.size>0&&this.logger.debug(`syncConsumers: Desired producer IDs: [${Array.from(e.keys()).join(",")}].`),r.size>0&&this.logger.debug(`syncConsumers: Current consumer IDs: [${Array.from(r.keys()).join(",")}].`),o.length>0&&this.logger.info(`syncConsumers: Producer IDs requiring consumers: [${o.map(({producerId:F})=>F).join(",")}].`),c.size>0&&this.logger.debug(`syncConsumers: Consumer IDs to keep: [${Array.from(c).join(",")}].`),l.length>0&&this.logger.info(`syncConsumers: Consumer IDs with consumer rewiring: [${l.join(",")}].`),d.length>0&&this.logger.info(`syncConsumers: Consumer IDs revived before deletion: [${d.join(",")}].`),u.length>0&&this.logger.info(`syncConsumers: Newly marked consumer IDs: [${u.join(",")}].`),g.length>0&&this.logger.info(`syncConsumers: Consumer IDs in deletion grace period: [${g.join(",")}].`),v.length>0&&this.logger.info(`syncConsumers: Consumer IDs ready for deletion: [${v.join(",")}].`);const y=35,k=35;o.length>y&&(this.logger.warn(`syncConsumers: Too many remote producers to create consumers: ${o.length}. Only adding ${y} in this run.`),o=o.slice(0,y),this.scheduleSyncConsumers({source:"SOFT_CAPPED_CREATE_CONSUMERS"})),v.length>k&&(this.logger.warn(`syncConsumers: Too many remote consumers ready to close: ${v.length}. Only removing ${k} in this run.`),v=v.slice(0,k),this.scheduleSyncConsumers({source:"SOFT_CAPPED_REMOVE_CONSUMERS"}));try{o.length>0||v.length>0?(this.logger.info(`syncConsumers: Calling updateConsumers: createProducerIds=[${o.map(({producerId:F})=>F).join(",")}], deleteConsumerIds=[${v.join(",")}].`),await this.updateConsumers(o,v),this.logger.info("syncConsumers: updateConsumers completed successfully.")):this.logger.info("syncConsumers: No changes needed, skipping updateConsumers.")}catch(F){this.logger.error("syncConsumers: updateConsumers failed with error.",{error:F})}finally{this.logger.info("syncConsumers: Setting consumersSyncing=false and completing sync."),f(this,Fs,!1),(re=s==null?void 0:s.socketState)!=null&&re.state&&s.socketState.state!=="connected"&&f(this,pi,!0)}a(this,pi)&&(this.logger.info("syncConsumers: Resync required, calling syncConsumers again."),this.syncConsumers())}computeActivateParticipants(s,t){const e=s.map((i,n)=>({peerId:i,priority:n+1})),r=t==null?void 0:t.map((i,n)=>({peerId:i,priority:-(n+1)}));e.push(...r!=null?r:[]),e.length>0&&this.updateActiveParticipantsWithPriorities(e)}createParticipantObjFromSocketPeer(s){const t=Qn.formatSocketPeerMessage(s);return new hr(this.context,{...t,isHost:!1,videoEnabled:!1,audioMuted:!0,videoTrack:void 0,audioTrack:void 0},this.self,this.roomSocketHandler)}updatePipSource(s,t){var e,r;t?(e=this.pip)==null||e.enableSource(s):(r=this.pip)==null||r.disableSource(s)}onParticipantMediaJoined(s,t){if(!this.mediaJoined||s===this.self.id)return;const e=this.participants.joined.get(s);if(!e){this.logger.warn(`Received media.peerJoinedBroadcast for non-existent peer ${s}`);return}this.logger.info(`processing media state of remote producers of peer ${s} with producerStates: ${JSON.stringify(t)}`),t.forEach(r=>{r.kind===Ns.AUDIO&&!r.screenShare?e.setAudioEnabled(!r.pause):r.kind===Ns.VIDEO&&!r.screenShare&&(e.setVideoEnabled(!r.pause),this.updatePipSource(e.id,!r.pause));const i={...r,producingTransportId:r.producingTransportId,kind:r.kind===Ns.AUDIO?"audio":"video",producingPeerId:s,mimeType:r.mimeType},n=e.producers.find(({producerId:o})=>o===i.producerId);n?Object.assign(n,i):e.producers.push(i)}),this.logger.info(`Reconciling consumers due to media join of peer ${s}. Media join is complete.`),this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}updateParticipantsMapMinReplacement(s,t){const e=Array.from(s.keys()),r=new Map(s),i=new Set(t),n=[];e.forEach((o,c)=>{(!i.has(o)||!this.participants.joined.get(o))&&n.push(c)}),t.forEach(o=>{if(s.get(o))return;if(e.length<t.length){e.push(o);return}const c=n.shift();e[c]=o}),n.forEach(o=>{e.splice(o,1)}),Array.from(s.keys()).forEach(o=>{s.delete(o,!i.has(o))}),e.forEach(o=>{const c=this.participants.joined.get(o);if(!c)return;const d=r.get(o),l=!d||d!==c;s.add(c,l)}),s.emit("participantsUpdate")}reconcileManualSubscriptionMaps(){const s=Array.from(this.participants.videoSubscribed.keys()),t=Array.from(this.participants.audioSubscribed.keys());this.updateParticipantsMap(this.participants.videoSubscribed,s.filter(e=>this.participants.joined.has(e))),this.updateParticipantsMap(this.participants.audioSubscribed,t.filter(e=>this.participants.joined.has(e)))}updateParticipantsMap(s,t){Array.from(s.keys()).forEach(r=>{t.includes(r)||s.delete(r,!0)}),t.forEach(r=>{const i=s.get(r),n=this.participants.joined.get(r);n&&i!==n&&(i&&s.delete(r,!1),s.add(n,!0))}),s.emit("participantsUpdate")}updatePinnedParticipants(){this.participants.pinned.forEach(s=>{s.setIsPinned(!1),this.participants.pinned.delete(s.id)})}applyPinnedSnapshot(s){const t=s[0];if(this.participants.pinned.forEach(i=>{i.id!==t&&(i.setIsPinned(!1),this.participants.pinned.delete(i.id))}),t===this.self.id){this.self.setIsPinned(!0),this.participants.pinned.emit("participantsUpdate");return}if(this.self.isPinned&&this.self.setIsPinned(!1),!t){this.participants.pinned.emit("participantsUpdate");return}const e=this.participants.joined.get(t),r=this.participants.pinned.get(t);if(!e){r&&this.participants.pinned.delete(t),this.participants.pinned.emit("participantsUpdate");return}r!==e&&(r&&(r.setIsPinned(!1),this.participants.pinned.delete(t,!1)),e.setIsPinned(!0),this.participants.pinned.add(e,!0)),this.participants.pinned.emit("participantsUpdate")}rewireConsumersOnLocalUserReconnect(){this.participants.joined.forEach(s=>{s.producers.forEach(t=>{const e=this.roomNodeClient.getConsumers().get(t.producerId);!e||e.closed||(R(this,gc,rm).call(this,e,t),t.pause&&!t.screenShare&&(t.kind==="audio"?s.setAudioEnabled(!1):(s.setVideoEnabled(!1),this.updatePipSource(s.id,!1))))})})}static replaceParticipantInMap(s,t,e,r){const i=s,n=i.get(t);if(!n)return;const o=new Set,c=Array.from(i.values()).reduce((d,l)=>{const u=l.id===t?e:l;return o.has(u.id)||(o.add(u.id),d.push(u)),d},[]);if(Array.from(i.keys()).forEach(d=>{i.delete(d,!1)}),c.forEach(d=>i.add(d,!1)),r){const d=i.emit.bind(i);d("participantLeft",n),d("participantJoined",e)}i.emit("participantsUpdate")}handleProducerHandover(s){const{oldPeerId:t,newPeerId:e,producerIds:r}=s;if(typeof t!="string"||typeof e!="string"||t===e||!Array.isArray(r)||r.length===0||r.some(u=>typeof u!="string")||e===this.self.id)return;const i=this.participants.joined.get(t),n=this.participants.joined.get(e);if(!i||!n||!i.userId||i.userId!==n.userId){this.logger.warn(`ParticipantController::producerHandover::participant validation failed from ${t} to ${e}`);return}this.selectedPeers.reassignPeer(t,e,this.context);const o=this.context.getValue("audioPlayback");o==null||o.reassignParticipantTrack(t,e),o==null||o.reassignParticipantTrack(`screenshare-${t}`,`screenshare-${e}`);const c=new Set(r),d=i.producers.filter(({producerId:u})=>c.has(u));if(d.length===0)return;d.some(u=>u.kind==="audio"&&!u.screenShare)&&(i.setAudioEnabled(!1),i.audioTrack=void 0),d.some(u=>u.screenShare)&&(i.setScreenShareEnabled(!1),i.screenShareTracks={audio:void 0,video:void 0}),n.manualProducerConfig={...i.manualProducerConfig},i.producers=i.producers.filter(({producerId:u})=>!c.has(u)),d.forEach(u=>{if(n.producers.some(({producerId:g})=>g===u.producerId))return;const h={...u};delete h.consumer,this.context.getValue("peerSessionStore").emit(P.NEW_PRODUCER,{peerId:e,producer:{...h,producingPeerId:e}})}),this.roomNodeClient.handoverPeerProducers(e,r).forEach(u=>{u.kind==="video"&&u.appData.screenShare!==!0&&this.videoPeerConsumerMap.get(t)===u.id&&(this.videoPeerConsumerMap.delete(t),this.updatePipSource(t,!1)),this.context.getValue("peerSessionStore").emit(P.NEW_CONSUMER_CREATED,{id:u.id,appData:u.appData,peerId:e})}),Qn.replaceParticipantInMap(this.participants.videoSubscribed,t,n,!0),Qn.replaceParticipantInMap(this.participants.audioSubscribed,t,n,!1),this.participants.pinned.has(t)&&(i.setIsPinned(!1),n.setIsPinned(!0),Qn.replaceParticipantInMap(this.participants.pinned,t,n,!0)),this.logger.info(`Removing old peer ${t} locally after handover.`),this.onParticipantLeave(t).catch(u=>{this.logger.error("Failed to remove old peer locally after handover",{error:u})})}setupEventsGlobal(){this.roomSocketHandler.on(x.joinRoom,({peer:s})=>{s.waitlisted||(this.logger.info(`Processing socket join for ${this.self.id===s.peerId?"local peer":"remote peer"} ${s.peerId}.`),this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(s)),this.logger.info(`Processed socket join for ${this.self.id===s.peerId?"local peer":"remote peer"} ${s.peerId}.`))}),this.roomSocketHandler.on(x.leaveRoom,async s=>{const{peerId:t}=s.peer;this.logger.info(`peer ${t} left the meeting. Removing it from selected peers`),this.selectedPeers.delete(t,this.context),this.onParticipantLeave(t)}),this.context.getValue("peerSessionStore").on(P.SOCKET_SERVICE_ROOM_JOINED,()=>{this.self.permissions.acceptWaitingRequests&&this.roomSocketHandler.getWaitingRoomRequests()}),this.self.permissions.on("permissionsUpdate",s=>{const{acceptWaitingRequests:t}=s;t!==void 0&&(t?this.roomSocketHandler.getWaitingRoomRequests():this.participants.waitlisted.clear())}),this.context.getValue("peerSessionStore").on(P.PEER_CLOSED,({id:s})=>{this.logger.info(`Remote peer ${s} has left media room. Scheduling delayed consumer cleanup.`),this.scheduleSyncConsumers({source:"REMOTE_PEER_CLOSED"})}),this.context.getValue("peerSessionStore").on(P.MEDIA_ROOM_JOIN_FAILED,()=>{this.isRebuildingReconnectSnapshot&&(this.isRebuildingReconnectSnapshot=!1)}),this.context.getValue("peerSessionStore").on(P.SOCKET_SERVICE_DISCONNECTED,()=>{this.isRebuildingReconnectSnapshot=!1,f(this,pi,!0),R(this,gn,_d).call(this,"socket disconnected"),this.logger.info("Socket disconnected — keeping participants visible for seamless reconnection")}),this.context.getValue("peerSessionStore").on(P.TRANSPORT_STATE_UPDATE,({transport:s,state:t})=>{if(s==="recv"){if(t!=="connected"){R(this,gn,_d).call(this,`Recv transport not yet connected. state: ${t}`);return}this.logger.info("Receive transport connected; scheduling consumer reconciliation"),this.scheduleSyncConsumers({source:"RECV_TRANSPORT_CONNECTED"})}}),this.context.getValue("peerSessionStore").on(P.CONSUMER_PAUSED,({id:s})=>{this.processConsumerPaused(s)}),this.context.getValue("peerSessionStore").on(P.CONSUMER_RESUMED,({id:s})=>{this.processConsumerResumed(s)}),this.context.getValue("peerSessionStore").on(P.NEW_CONSUMER_CREATED,({id:s})=>{this.processNewConsumer(s)}),this.context.getValue("peerSessionStore").on(P.CONSUMER_CLOSED,({id:s})=>{const t=a(this,Ze).delete(s);this.logger.info(`Consumer closed: consumerId=${s}, wasMarkedForDeletion=${t}.`),this.processConsumerClosed(s)}),this.context.getValue("peerSessionStore").on(P.ROOM_MESSAGE,async({payload:s,type:t,timestamp:e})=>{this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(P.MESSAGE,async({payload:s,type:t,timestamp:e})=>{t!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(P.LOW_CONSUMER_SCORE,({peerId:s,score:t,kind:e})=>{const r=this.participants.joined.get(s);r&&(r.emit("poorConnection",{score:t,kind:e}),this.participants.emit("poorConnection",{participantId:s,score:t,kind:e}))}),this.context.getValue("peerSessionStore").on(P.CONSUMER_SCORE_UPDATE,({score:s,kind:t,appData:e,peerId:r,scoreStats:i})=>{var c;const n=t==="video"&&((c=e==null?void 0:e.screenShare)!=null?c:!1),o=this.participants.joined.get(r);o&&(o.emit("mediaScoreUpdate",{kind:t,isScreenshare:n,score:s,participantId:r,scoreStats:i}),this.participants.emit("mediaScoreUpdate",{kind:t,isScreenshare:n,score:s,participantId:r,scoreStats:i}))}),this.context.getValue("peerSessionStore").onAsync(P.KICK_PEER,async({peerId:s})=>{const t=this.participants.joined.get(s);this.roomNodeClient.kick(s),await this.roomSocketHandler.kick(s),t?t.emit("kicked"):this.participants.joined.emit("kicked",{id:s})}),this.context.getValue("peerSessionStore").on(P.UPDATE_ACTIVE,({viewMode:s,page:t}={})=>{this.isRebuildingReconnectSnapshot||(this.logger.info(`UPDATE_ACTIVE event received - viewMode: ${a(this,hs).mode}, page: ${t}`),this.updateMediaSubscribedMaps(s,{page:t}),this.scheduleSyncConsumers({source:"UPDATE_ACTIVE"}))})}async onParticipantPinned(s){if(!s){this.self.isPinned&&this.self.setIsPinned(!1),this.participants.pinned.size!==0&&this.updatePinnedParticipants();return}if(s===this.self.id){this.participants.pinned.size!==0&&this.updatePinnedParticipants(),this.self.setIsPinned(!0);return}const t=this.participants.joined.get(s);this.self.isPinned&&this.self.setIsPinned(!1),this.updatePinnedParticipants(),t.setIsPinned(!0),this.participants.pinned.add(t)}async onParticipantSocketJoined(s){var t,e,r;this.self.id!==s.id&&!((t=s.flags)!=null&&t.recorder)&&!((e=s.flags)!=null&&e.hidden_participant)&&!((r=s.flags)!=null&&r.hiddenParticipant)&&(this.isRebuildingReconnectSnapshot||(this.participants.videoSubscribed.delete(s.id),this.participants.audioSubscribed.delete(s.id)),this.participants.joined.add(s),this.participants.waitlisted.delete(s.id),s.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&this.context.getValue("peerSessionStore").emit(P.UPDATE_STAGE_REQUESTS,{request:{displayName:s.name,userId:s.userId,peerId:s.id},add:!0})),this.context.getValue("peerSessionStore").emit(P.PEER_JOINED_INTERNAL,s)}async onParticipantLeave(s){var e;this.logger.info(`peer ${s} has left. Deleting peer from participant maps`);const t=this.participants.joined.get(s);if(this.participants.joined.delete(s,!0,!0),this.participants.pinned.delete(s,!0,!0),this.participants.waitlisted.delete(s,!0,!0),(e=this.pip)==null||e.removeSource(s),t&&t.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&this.context.getValue("peerSessionStore").emit(P.UPDATE_STAGE_REQUESTS,{request:{displayName:t.name,userId:t.userId,peerId:t.id},add:!1}),!this.isRebuildingReconnectSnapshot){if(this.participants.viewMode==="PAGINATED"){const r=Math.max(1,Math.min(this.participants.currentPage,this.participants.pageCount));if(r!==this.participants.currentPage){await this.participants.setPage(r);return}}this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}}processMedia(s){var h;const t=this.roomNodeClient.getConsumers(),{peerId:e,kind:r,appData:i,track:n,producerId:o,rtpReceiver:c,paused:d,localId:l}=(h=t.get(s))!=null?h:{};if(!e)return this.logger.warn("processMedia::Peer ID is undefined",{consumer:{id:s,kind:r,peerId:e,appData:{supportsRemoteControl:!!(i!=null&&i.supportsRemoteControl),screenShare:!!(i!=null&&i.screenShare)},remotelyPaused:d,producerId:o}}),{};const u=i;return r==="video"&&u.screenShare!==!0&&this.videoPeerConsumerMap.set(e,s),this.logger.info("ParticipantController::processMedia",{consumer:{id:s,peerId:e,kind:r,appData:u,remotelyPaused:d,producerId:o}}),this.consumerPeerMap.set(s,{type:r,peerId:e,appData:u,remotelyPaused:d,producerId:o,trackId:n==null?void 0:n.id}),{peerId:e,kind:r,appData:u,remotelyPaused:d,track:n,producerId:o,rtpReceiver:c,localId:l}}processConsumerClosed(s){var l;const{peerId:t,type:e,appData:r,remotelyPaused:i,producerId:n,trackId:o}=this.consumerPeerMap.get(s)||{},c=this.participants.joined.get(t);if(this.logger.info("ParticipantController::processConsumerClosed",{consumer:{id:s,peerId:t,appData:r,kind:e,remotelyPaused:i,producerId:n}}),this.consumerPeerMap.delete(s),e==="video"&&(r==null?void 0:r.screenShare)!==!0&&this.videoPeerConsumerMap.get(t)===s&&this.videoPeerConsumerMap.delete(t),r!=null&&r.e2ee&&o&&this.context.getValue("peerSessionStore").emit(P.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:o}),!c)return;r!=null&&r.screenShare?this.context.getValue("callstats").consumerSharedMediaState(s,{screen:!1}):e==="audio"?this.context.getValue("callstats").consumerSharedMediaState(s,{audio:!1}):e==="video"&&this.context.getValue("callstats").consumerSharedMediaState(s,{video:!1});const d=c.producers.find(u=>u.producerId===n);if(((l=d==null?void 0:d.consumer)==null?void 0:l.id)!==s){this.logger.info(`Ignoring stale consumer media cleanup: consumerId=${s}, producerId=${n}, peerId=${t}.`);return}d.consumer={id:s,peerId:t,kind:void 0,appData:r,paused:i,producerId:n,rtpReceiver:void 0,localId:void 0},!(e!=="audio"&&e!=="video")&&this.clearParticipantMediaState(c,e,(r==null?void 0:r.screenShare)===!0)}processConsumerResumed(s){var g;const t=this.processMedia(s),{peerId:e,kind:r,appData:i,track:n,remotelyPaused:o,producerId:c,rtpReceiver:d,localId:l}=t;if(!e)return;this.logger.info("ParticipantController::processConsumerResumed",{consumer:{id:s,peerId:e,kind:r,appData:i,remotelyPaused:o,producerId:c}});const u=this.participants.joined.get(e);if(!u)return;const h=u.producers.find(v=>v.producerId===c);if(h&&(h.consumer={id:s,peerId:e,kind:r,appData:i,paused:o,producerId:c,rtpReceiver:d,localId:l}),i.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:d,track:n}),i.screenShare){r==="video"?u.screenShareTracks.video=n:r==="audio"&&(u.screenShareTracks.audio=n),u.setScreenShareEnabled(!0),(g=this.context)==null||g.getValue("callstats").consumerSharedMediaState(s,{screen:!0});return}r==="video"?(u.videoTrack=n,u.setVideoEnabled(!0),this.updatePipSource(u.id,!0),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!0})):r==="audio"&&(u.audioTrack=n,u.setAudioEnabled(u.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:u.audioEnabled}))}processConsumerPaused(s){this.logger.info(`ParticipantController::processConsumerPaused called for consumerId: ${s}`);const{peerId:t,kind:e,track:r,appData:i,remotelyPaused:n,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(s);if(!t)return;this.logger.info("ParticipantController::processConsumerPaused",{consumer:{id:s,peerId:t,kind:e,appData:i,remotelyPaused:n,producerId:o}});const l=this.participants.joined.get(t);if(!l)return;const u=l.producers.find(h=>h.producerId===o);u&&(u.consumer={id:s,peerId:t,kind:e,appData:i,paused:n,producerId:o,rtpReceiver:c,localId:d}),r&&i.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:r.id}),e==="video"?(l.videoTrack=r,l.setVideoEnabled(!1),this.updatePipSource(l.id,!1),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!1})):e==="audio"&&(l.audioTrack=r,l.setAudioEnabled(l.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:l.audioEnabled}))}processNewConsumer(s){const{peerId:t,kind:e,remotelyPaused:r,track:i,appData:n,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(s);if(!t)return;this.logger.info("ParticipantController::processNewConsumer",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:n,producerId:o}});const l=this.participants.joined.get(t);if(!l)return;const u=l.producers.find(h=>h.producerId===o);if(u&&(u.consumer={id:s,peerId:t,kind:e,appData:n,paused:r,producerId:o,rtpReceiver:c,localId:d}),n.screenShare){e==="video"?l.screenShareTracks.video=i:e==="audio"&&(l.screenShareTracks.audio=i),(!r||this.self.permissions.isRecorder)&&l.setScreenShareEnabled(!0),n.supportsRemoteControl&&(l.supportsRemoteControl=!0),this.participants.broadcastMessage("screenshareConsumerCreated",{producerId:o,peerId:t,screenShare:!0,consumerId:s,consumerPeerId:this.self.id}),this.logger.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:n,producerId:o}});return}e==="video"?(l.videoTrack=i,r||(l.setVideoEnabled(!0),this.updatePipSource(l.id,!0)),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!r})):e==="audio"&&(l.audioTrack=i,r||l.setAudioEnabled(!0),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:!r})),!r&&n.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_CONSUMER,{peerId:t,rtpReceiver:c,track:i}),this.context.getValue("peerSessionStore").emit(P.ENABLE_E2EE_CRYPTOR_ON_NEW_CONSUMER,{appData:n,peerId:l.id})}static formatSocketPeerMessage(s){var e,r,i,n,o,c;if(!s)return;const t=lp(s.stageType);return{id:s.peerId,userId:s.userId,name:s.displayName,displayName:s.displayName,stageType:t,customParticipantId:s.customParticipantId,presetId:s.presetId,picture:s.displayPictureUrl,waitlisted:s.waitlisted,stageStatus:t,metadata:{preset_name:(e=s.flags)==null?void 0:e.presetName},recorderType:(r=s.flags)==null?void 0:r.recorderType,flags:{hiddenParticipant:(i=s.flags)==null?void 0:i.hiddenParticipant,hidden_participant:(n=s.flags)==null?void 0:n.hiddenParticipant,recorder:((o=s.flags)==null?void 0:o.recorderType)!==void 0&&((c=s.flags)==null?void 0:c.recorderType)!=="NONE"}}}async onSelectedPeers(s,t){this.participants.viewMode==="ACTIVE_GRID"&&this.computeActivateParticipants(s,t)}updateActiveParticipantsWithPriorities(s,t=!1){if(this.participants.viewMode==="MANUAL")return;if(!this.mediaJoined){this.logger.warn("Skipped::ParticipantController::updateActiveParticipantsWithPriorities",{roomJoined:this.mediaJoined});return}s.forEach(r=>{this.selectedPeers.add(r.peerId,r.priority,this.context)});const e=this.selectedPeers.activeSpeakerPeers.at(0);e!==void 0&&e!==this.participants.lastActiveSpeaker&&(this.participants.lastActiveSpeaker=e,this.participants.emit("activeSpeaker",{peerId:e,volume:1})),t&&this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}},hs=new WeakMap,Fs=new WeakMap,pi=new WeakMap,Ze=new WeakMap,kr=new WeakMap,mn=new WeakMap,gn=new WeakSet,_d=function(s){a(this,kr)===void 0&&(f(this,kr,Date.now()),this.logger.info(`Consumer deletion aging paused: reason="${s}", consumerIds=[${Array.from(a(this,Ze).keys()).join(",")}].`))},du=new WeakSet,pT=function(){if(a(this,kr)===void 0)return;const s=Date.now()-a(this,kr);a(this,Ze).forEach((t,e)=>{a(this,Ze).set(e,t+s)}),f(this,kr,void 0),this.logger.info(`Consumer deletion aging resumed: pausedDurationMs=${s}, consumerIds=[${Array.from(a(this,Ze).keys()).join(",")}].`)},lu=new WeakSet,mT=function(s){return a(this,Ze).has(s.id)?!1:(a(this,Ze).set(s.id,Date.now()),!0)},gc=new WeakSet,rm=function(s,t){const e=s.peerId,r=!t.consumer||t.consumer.peerId!==t.producingPeerId||e!==t.producingPeerId;s.reassignPeer(t.producingPeerId);const i=a(this,Ze).delete(s.id);return r&&this.processNewConsumer(s.id),{needsRemap:r,wasMarkedForDeletion:i}},uu=new WeakSet,gT=function(){f(this,mn,setInterval(()=>{a(this,Ze).size!==0&&(this.logger.info(`Consumer deletion sweep scheduling reconciliation: consumerIds=[${Array.from(a(this,Ze).keys()).join(",")}].`),this.scheduleSyncConsumers({source:"CONSUMER_DELETION_SWEEP"}))},G1))},hu=new WeakSet,fT=function(){a(this,mn)!==void 0&&(clearInterval(a(this,mn)),f(this,mn,void 0))},pu=new WeakMap,ZS);let pr=Qn;Bi([E.trace("ParticipantController.setupEvents")],pr.prototype,"setupEvents",1),Bi([E.trace("ParticipantController.setupEvents")],pr.prototype,"setupEventsGlobal",1),Bi([E.trace("ParticipantController.processMedia")],pr.prototype,"processMedia",1),Bi([E.trace("ParticipantController.processConsumerClosed")],pr.prototype,"processConsumerClosed",1),Bi([E.trace("ParticipantController.processConsumerResumed")],pr.prototype,"processConsumerResumed",1),Bi([E.trace("ParticipantController.processConsumerPaused")],pr.prototype,"processConsumerPaused",1),Bi([E.trace("ParticipantController.processNewConsumer")],pr.prototype,"processNewConsumer",1);const De=Ls(Lh().permissions),gu=class extends Bt{constructor(e,r,i,n=!1){const o=e.getValue("logger");super(o);m(this,Pt);m(this,z,void 0);m(this,Ia,void 0);m(this,Aa,void 0);m(this,mu,e=>{var l,u,h;const{chat:r,connectedMeetings:i,plugins:n,polls:o,media:c,...d}=e;if(r&&(r.private&&Ur(a(this,z).chat.private,r.private),r.public&&Ur(a(this,z).chat.public,r.public),this.emit("chatUpdate")),i&&Ur(a(this,z).connectedMeetings,i),c){const g=y=>{switch(y){case Fr.NONE:return G.Allowed;case Fr.ALLOWED:return G.Allowed;case Fr.NOT_ALLOWED:return G.NotAllowed;case Fr.CAN_REQUEST:return G.CanRequest;default:return}},v={audio:void 0,video:void 0,screenshare:void 0};(l=c.audio)!=null&&l.canProduce&&(v.audio={canProduce:g(c.audio.canProduce)}),(u=c.video)!=null&&u.canProduce&&(v.video={canProduce:g(c.video.canProduce)}),(h=c.screenshare)!=null&&h.canProduce&&(v.screenshare={canProduce:g(c.screenshare.canProduce)}),Ur(a(this,z).media,v)}n&&(Ur(a(this,z).plugins,n),this.emit("pluginsUpdate")),o&&(Ur(a(this,z).polls,o),this.emit("pollsUpdate")),Object.keys(d).length!==0&&Ur(a(this,z),d),this.emit("permissionsUpdate",e)});if(!r)throw this.logger.error("PermissionPreset::load_preset_permissions_failed"),new C("Could not load preset permissions.","0904");f(this,Aa,e),f(this,Ia,i),f(this,z,r),n&&this.setupEvents()}setupEvents(){a(this,Aa).getValue("peerSessionStore").on(P.UPDATE_PERMISSIONS,a(this,mu))}static init(e,r,i){let n;return i?n=new gu(e,i,r,!0):n=new gu(e,De,r),n}get mediaRoomType(){return"CF"}get stageEnabled(){var e;return((e=a(this,z))==null?void 0:e.stageEnabled)||a(this,Ia)===Ss.Webinar||a(this,Ia)===Ss.Livestream}get acceptStageRequests(){var e,r;return this.stageEnabled?((e=a(this,z))==null?void 0:e.acceptStageRequests)||((r=a(this,z))==null?void 0:r.canAcceptProductionRequests):!1}get stageAccess(){var e,r,i;return((e=a(this,z))==null?void 0:e.stageAccess)===G.NotAllowed?G.NotAllowed:((r=a(this,z))==null?void 0:r.stageAccess)===G.CanRequest?G.CanRequest:((i=a(this,z))==null?void 0:i.stageAccess)===G.Allowed||a(this,z).media.audio.canProduce===G.Allowed||a(this,z).media.video.canProduce===G.Allowed||a(this,z).media.screenshare.canProduce===G.Allowed?G.Allowed:a(this,z).media.audio.canProduce===G.CanRequest||a(this,z).media.video.canProduce===G.CanRequest||a(this,z).media.screenshare.canProduce===G.CanRequest?G.CanRequest:G.NotAllowed}get acceptWaitingRequests(){var e,r;return(r=(e=a(this,z))==null?void 0:e.acceptWaitingRequests)!=null?r:De.acceptWaitingRequests}get requestProduceVideo(){var e,r,i;return((i=(r=(e=a(this,z))==null?void 0:e.media)==null?void 0:r.video)==null?void 0:i.canProduce)===G.CanRequest}get requestProduceAudio(){var e,r,i;return((i=(r=(e=a(this,z))==null?void 0:e.media)==null?void 0:r.audio)==null?void 0:i.canProduce)===G.CanRequest}get requestProduceScreenshare(){var e,r,i;return((i=(r=(e=a(this,z))==null?void 0:e.media)==null?void 0:r.screenshare)==null?void 0:i.canProduce)===G.CanRequest}get canAllowParticipantAudio(){var e,r;return(r=(e=a(this,z))==null?void 0:e.disableParticipantAudio)!=null?r:De.disableParticipantAudio}get canAllowParticipantScreensharing(){var e,r;return(r=(e=a(this,z))==null?void 0:e.canAcceptProductionRequests)!=null?r:De.canAcceptProductionRequests}get canAllowParticipantVideo(){var e,r;return(r=(e=a(this,z))==null?void 0:e.disableParticipantVideo)!=null?r:De.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var e,r;return(r=(e=a(this,z))==null?void 0:e.kickParticipant)!=null?r:De.kickParticipant}get pinParticipant(){var e,r;return(r=(e=a(this,z))==null?void 0:e.pinParticipant)!=null?r:De.pinParticipant}get canRecord(){var e,r;return(r=(e=a(this,z))==null?void 0:e.canRecord)!=null?r:De.canRecord}get waitingRoomBehaviour(){var e,r;return(r=(e=a(this,z))==null?void 0:e.waitingRoomType)!=null?r:De.waitingRoomType}get plugins(){var e,r;return(r=(e=a(this,z))==null?void 0:e.plugins)!=null?r:De.plugins}get polls(){var e,r;return(r=(e=a(this,z))==null?void 0:e.polls)!=null?r:De.polls}get canProduceVideo(){var r;const e=(r=a(this,z).media.video.canProduce)!=null?r:De.media.video.canProduce;return this.stageEnabled&&(a(this,Pt,es)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Pt,es)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,Pt,es)==="OFF_STAGE"||a(this,Pt,es)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get canProduceScreenshare(){var r;const e=(r=a(this,z).media.screenshare.canProduce)!=null?r:De.media.screenshare.canProduce;return this.stageEnabled&&(a(this,Pt,es)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Pt,es)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,Pt,es)==="OFF_STAGE"||a(this,Pt,es)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get canProduceAudio(){var r;const e=(r=a(this,z).media.audio.canProduce)!=null?r:De.media.audio.canProduce;return this.stageEnabled&&(a(this,Pt,es)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Pt,es)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,Pt,es)==="OFF_STAGE"||a(this,Pt,es)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get chatPublic(){var e,r,i;return(i=(r=(e=a(this,z))==null?void 0:e.chat)==null?void 0:r.public)!=null?i:De.chat.public}get chatPrivate(){var e,r,i;return(i=(r=(e=a(this,z))==null?void 0:e.chat)==null?void 0:r.private)!=null?i:De.chat.private}get connectedMeetings(){var e,r;return(r=(e=a(this,z))==null?void 0:e.connectedMeetings)!=null?r:De==null?void 0:De.connectedMeetings}get hiddenParticipant(){var e,r;return(r=(e=a(this,z))==null?void 0:e.hiddenParticipant)!=null?r:De.hiddenParticipant}get showParticipantList(){var e;return(e=a(this,z).showParticipantList)!=null?e:De.showParticipantList}get canChangeParticipantPermissions(){var e,r;return(r=(e=a(this,z))==null?void 0:e.canChangeParticipantPermissions)!=null?r:De.canChangeParticipantPermissions}get canEditDisplayName(){var e;return(e=a(this,z).canEditDisplayName)!=null?e:!1}get canEditMeetingTitle(){var e,r;return(r=(e=a(this,z))==null?void 0:e.canEditMeetingTitle)!=null?r:!1}get isRecorder(){return a(this,z).isRecorder}get canSpotlight(){return a(this,z).canSpotlight}get canLivestream(){return a(this,z).canLivestream}get transcriptionEnabled(){return a(this,z).transcriptionEnabled}};let bp=gu;z=new WeakMap,Ia=new WeakMap,Aa=new WeakMap,mu=new WeakMap,Pt=new WeakSet,es=function(){return a(this,Aa).getValue("stageStatus")};class sS extends Bt{constructor(e,r){super(r);p(this,"localMediaHandler");m(this,zt,void 0);f(this,zt,e)}async updatePermission(){var d,l;const e=(u,h)=>{this.mediaPermissions[u]=h;const g={message:this.mediaPermissions[u],kind:u};h==="DENIED"?a(this,zt).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_ERROR,g):a(this,zt).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,g)};if(Pe.getName()==="firefox")return;const r="microphone",i="camera",n=await((d=navigator==null?void 0:navigator.permissions)==null?void 0:d.query({name:r})),o=await((l=navigator==null?void 0:navigator.permissions)==null?void 0:l.query({name:i})),c=(u,h)=>{switch(h){case"granted":e(u,"ACCEPTED");break;case"denied":e(u,"DENIED");break;case"prompt":e(u,"NOT_REQUESTED");break}this.localMediaHandler.repopulateAvailableDevices()};n&&(n.onchange=()=>c("audio",n.state)),o&&(o.onchange=()=>c("video",o.state))}async populateMediaPermissionsInCallstats({message:e,kind:r}){var i,n,o,c;switch(r){case"audio":{(i=a(this,zt))==null||i.getValue("callstats").mediaPermission("AUDIO",e),(n=a(this,zt))==null||n.getValue("callstats").mediaPermission("SPEAKER",e);break}case"video":{(o=a(this,zt))==null||o.getValue("callstats").mediaPermission("VIDEO",e);break}case"screenshare":{(c=a(this,zt))==null||c.getValue("callstats").mediaPermission("SCREENSHARE",e);break}}}get peerId(){var e;return(e=a(this,zt))==null?void 0:e.getValue("peerId")}async init(e={},r=!1,i=null){var n,o,c,d,l,u,h;if(Pe.init(),i&&f(this,zt,i),!this.localMediaHandler)try{let g=!0;if((n=i==null?void 0:i.getValue("defaults"))!=null&&n.mediaHandler)g=!1,this.localMediaHandler=i.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:v}=navigator;this.localMediaHandler=await v.init(e)}else this.localMediaHandler=new Dt(i,e.constraints,(o=i==null?void 0:i.getValue("defaults"))==null?void 0:o.isNonPreferredDevice,(c=i==null?void 0:i.getValue("defaults"))==null?void 0:c.autoSwitchAudioDevice);if(i==null||i.getValue("peerSessionStore").on(P.MEDIA_PERMISSION_UPDATE,async v=>{if(this.populateMediaPermissionsInCallstats({message:v.message,kind:v.kind}),v.message==="NOT_REQUESTED")switch(v==null?void 0:v.kind){case"audio":this.rawAudioTrack&&(this.logger.info("Disabling audio due to media permission update"),this.disableAudio());break;case"video":this.rawVideoTrack&&(this.logger.info("Disabling video due to media permission update"),this.disableVideo());break;default:break}this.emit("mediaPermissionUpdate",v)}),i==null||i.getValue("peerSessionStore").on(P.MEDIA_PERMISSION_ERROR,async v=>{const{kind:y,message:k,constraints:I}=v;this.populateMediaPermissionsInCallstats({message:k,kind:y}),y==="audio"?(this.logger.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):y==="video"&&(this.logger.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),this.logger.error("SelfController::mediaPermissionError",{error:{message:k},constraints:I,mediaPermissionsErrors:{kind:y,message:k}}),this.emit("mediaPermissionError",v),this.emit("mediaPermissionUpdate",{message:k,kind:y})}),g){this.logger.info(`Setting up SelfMedia streams using media handler. audio:${(d=e==null?void 0:e.audio)!=null?d:!0} video:${(l=e==null?void 0:e.video)!=null?l:!0}`);const v=this.localMediaHandler.setupStreams({video:(u=e==null?void 0:e.video)!=null?u:!0,audio:(h=e==null?void 0:e.audio)!=null?h:!0});r||await v}}catch(g){this.logger.error("Self::init::Failed To Setup Streams",{error:{name:g.name,message:g.message}})}}set context(e){f(this,zt,e),this.localMediaHandler.context=e}get audioTrack(){return this.localMediaHandler.audioTrack}get rawAudioTrack(){return this.localMediaHandler.rawAudioTrack}get mediaPermissions(){return this.localMediaHandler.permissions}async addAudioMiddleware(e){return this.localMediaHandler.addAudioMiddleware(e)}async removeAudioMiddleware(e){return this.localMediaHandler.removeAudioMiddleware(e)}async removeAllAudioMiddlewares(){return this.localMediaHandler.removeAllAudioMiddlewares()}get videoTrack(){return this.localMediaHandler.videoTrack}get rawVideoTrack(){return this.localMediaHandler.rawVideoTrack}async addVideoMiddleware(e){return this.localMediaHandler.addVideoMiddleware(e)}async setVideoMiddlewareGlobalConfig(e={disablePerFrameCanvasRendering:!1}){return this.localMediaHandler.setVideoMiddlewareGlobalConfig(e)}async removeVideoMiddleware(e){return this.localMediaHandler.removeVideoMiddleware(e)}async removeAllVideoMiddlewares(){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}async enableAudio(){await this.localMediaHandler.enableAudio(),this.logger.info(`Emitting audioUpdate to the UI Kit for self. Audio enabled: ${this.audioEnabled}. Audio track available: ${!!this.audioTrack}.`),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableVideo(){await this.localMediaHandler.enableVideo(),this.logger.info(`Emitting videoUpdate to the UI Kit for self. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}async disableAudio(){this.localMediaHandler.disableAudio(),this.logger.info(`Emitting audioUpdate to the UI Kit for self. Audio enabled: ${this.audioEnabled}. Audio track available: ${!!this.audioTrack}.`),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableScreenShare(){var e;await this.localMediaHandler.enableScreenShare(),this.logger.info(`Emitting screenShareUpdate to the UI Kit for self. Screen sharing enabled: ${this.screenShareEnabled}. Video track available: ${!!((e=this.screenShareTracks)!=null&&e.video)}.`),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableScreenShare(){var e;await this.localMediaHandler.disableScreenShare(),this.logger.info(`Emitting screenShareUpdate to the UI Kit for self. Screen sharing enabled: ${this.screenShareEnabled}. Video track available: ${!!((e=this.screenShareTracks)!=null&&e.video)}.`),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableVideo(){await this.localMediaHandler.disableVideo(),this.logger.info(`Emitting videoUpdate to the UI Kit for self. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}getCurrentDevices(){return this.localMediaHandler.getCurrentDevices()}async getAudioDevices(){return await this.localMediaHandler.getAudioDevices()}async getVideoDevices(){return await this.localMediaHandler.getVideoDevices()}async getSpeakerDevices(){return await this.localMediaHandler.getSpeakerDevices()}getDeviceById(e,r){let i;return r==="audio"?i="audioinput":r==="video"?i="videoinput":r==="speaker"&&(i="audiooutput"),this.localMediaHandler.getDeviceById(e,i)}async setDevice(e){switch(e.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(e,{saveDevicePreference:!0})}catch(r){}finally{this.logger.info(`Emitting audioUpdate to the UI Kit for self. Audio enabled: ${this.audioEnabled}. Audio track available: ${!!this.audioTrack}.`),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":await this.localMediaHandler.setSpeakerDevice(e,{saveDevicePreference:!0});break;case"videoinput":try{await this.localMediaHandler.setVideoDevice(e,{saveDevicePreference:!0})}catch(r){}finally{this.logger.info(`Emitting videoUpdate to the UI Kit for self. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})}}zt=new WeakMap;var J1=Object.defineProperty,K1=Object.getOwnPropertyDescriptor,yt=(s,t,e,r)=>{for(var i=r>1?void 0:r?K1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&J1(t,e,i),i};let ze=(eT=class extends sS{constructor(t,e,r,i,n){const o=t.getValue("logger");super(t,o);m(this,_r);m(this,tt);m(this,Da);m(this,Fe);m(this,fc);p(this,"name");p(this,"picture");p(this,"customParticipantId");p(this,"waitlistStatus");m(this,Ma,void 0);m(this,kt,void 0);m(this,Oa,void 0);p(this,"role");p(this,"userId");p(this,"organizationId");p(this,"supportsRemoteControl",!1);p(this,"device");m(this,et,void 0);p(this,"hidden",!1);p(this,"presetName");p(this,"roomState","init");m(this,Na,new Set);m(this,La,new Set);f(this,et,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=e.customParticipantId,this.waitlistStatus="none",f(this,kt,r),f(this,Ma,i),this.hidden=!1,f(this,Oa,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=Pe.isElectron(),this.device=Pe.getDeviceInfo(),this.presetName=n,this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),R(this,fc,im).call(this)}get telemetry(){return a(this,et).getValue("telemetry")}get stageStatus(){return a(this,et).getValue("stageStatus")}get producers(){var t,e;return Array.from((e=(t=a(this,tt,St).getProducers())==null?void 0:t.values())!=null?e:[])}get id(){return this.peerId}get peerId(){return a(this,et).getValue("peerId")}static async __init__(t,e,r,i,n,o=!1){var g,v,y,k,I,D;let c=(v=(g=t.getValue("defaults"))==null?void 0:g.audio)!=null?v:!0,d=(k=(y=t.getValue("defaults"))==null?void 0:y.video)!=null?k:!0;r.canProduceAudio!=="ALLOWED"&&(c=!1),r.canProduceVideo!=="ALLOWED"&&(d=!1);const l=new ze(t,e,r,i,n),u=r1(i.mediaConstraints);Ur(u,(I=t.getValue("defaults"))==null?void 0:I.mediaConfiguration);const h=(D=t.getValue("defaults"))==null?void 0:D.mediaHandler;return h&&(h.context=t),await l.init({audio:c,video:d,constraints:u},o,t),l.setupEvents(),l}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"),a(this,kt).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",R(this,fc,im));const t=a(this,Da,ih);t&&t.onError(e=>{this.emit("autoplayError",e)}),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::AUDIO_TRACK_CHANGE",{...Ui(this)}),a(this,Fe,Je)&&this.audioEnabled)try{await a(this,tt,St).shareMic(this.audioTrack)}catch(e){this.logger.error("Self::setupEvents::Error while sharing mic",{error:e}),this.localMediaHandler.disableAudio()}this.logger.info(`Emitting audioUpdate to the UI Kit for self. Audio enabled: ${this.audioEnabled}. Audio track available: ${!!this.audioTrack}.`),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}),this.localMediaHandler.on("VIDEO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::VIDEO_TRACK_CHANGE",{...Ui(this)}),a(this,Fe,Je)&&this.rawVideoTrack===void 0)this.logger.info("Self::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&a(this,Fe,Je))try{await a(this,tt,St).shareWebcam(this.videoTrack)}catch(e){this.logger.error("Self::setupEvents::failed shareWebcam",{error:e}),this.videoEnabled&&await this.localMediaHandler.disableVideo()}this.logger.info(`Emitting videoUpdate to the UI Kit for self. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}),this.localMediaHandler.on("DEVICE_CHANGE",async({device:e})=>{var r;this.emit("deviceUpdate",{device:e}),e.kind==="audiooutput"&&typeof HTMLAudioElement.prototype.setSinkId=="function"&&((r=a(this,Da,ih))==null||r.setSpeakerDevice(e.deviceId))}),this.localMediaHandler.on("DEVICE_LIST_UPDATED",e=>{this.emit("deviceListUpdate",e)}),this.localMediaHandler.on("SCREENSHARE_TRACK_CHANGE",async()=>{var e;if(!a(this,Fe,Je)){this.logger.error("Self.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{await a(this,tt,St).shareScreen(this.screenShareTracks)}catch(r){this.logger.error("Self::setupEvents::Error while sharing screen",{error:r}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.logger.info("Self::setupEvents::SCREENSHARE_TRACK_CHANGE",{...Ui(this)}),this.logger.info(`Emitting screenShareUpdate to the UI Kit for self. Screen sharing enabled: ${this.screenShareEnabled}. Video track available: ${!!((e=this.screenShareTracks)!=null&&e.video)}.`),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}),this.localMediaHandler.on("SCREENSHARE_ENDED",async()=>{this.logger.log("Disabling screenshare due to SCREENSHARE_ENDED"),await this.disableScreenShare(),this.logger.info("Self::setupEvents::SCREENSHARE_ENDED",{...Ui(this)})}),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{var e;(e=a(this,et))==null||e.getValue("callstats").mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",async()=>{var e;a(this,Fe,Je)&&await a(this,tt,St).pauseWebcam(),this.logger.info(`Emitting videoUpdate to the UI Kit for self. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(e=a(this,et))==null||e.getValue("callstats").videoOff()}),a(this,kt).on("permissionsUpdate",e=>{var r,i,n;(r=e==null?void 0:e.media)!=null&&r.audio&&a(this,kt).canProduceAudio!==G.Allowed&&(this.disableAudio(),this.logger.info(`Disabled audio due to dynamic preset change: canProduceAudio: ${this.permissions.canProduceAudio}`)),(i=e==null?void 0:e.media)!=null&&i.video&&a(this,kt).canProduceVideo!==G.Allowed&&(this.disableVideo(),this.logger.info(`Disabled video due to dynamic preset change: canProduceVideo: ${this.permissions.canProduceVideo}`)),(n=e==null?void 0:e.media)!=null&&n.screenshare&&a(this,kt).canProduceScreenshare!==G.Allowed&&(this.disableScreenShare(),this.logger.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return a(this,kt)}get config(){return a(this,Ma)}get roomJoined(){var t;return a(this,Ma).viewType===Ss.Livestream&&this.stageStatus!=="ON_STAGE"?((t=a(this,et).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:a(this,Fe,Je)}setName(t){if(!t)throw new C("Name cannot be empty.","1103");this.name=t}async setupTracks(t={}){t.forceReset,await this.disableAudio(),await this.disableVideo(),this.localMediaHandler.removeAudioTrack(),this.localMediaHandler.removeVideoTrack(),t.audio&&await this.enableAudio(),t.video&&await this.enableVideo()}async destructMediaHandler(){return this.localMediaHandler.destruct()}async removeDocumentEventListeners(){return this.localMediaHandler.removeDocumentEventListeners()}async enableAudio(t){var e;if(this.permissions.canProduceAudio!==G.NotAllowed&&!(a(this,kt).canProduceAudio===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if((e=a(this,et))==null||e.getValue("callstats").audioOn(),await this.localMediaHandler.enableAudio(t),a(this,Fe,Je)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{await a(this,tt,St).shareMic(this.audioTrack)}catch(r){this.logger.error("Self::enableAudio::Error while sharing mic",{error:r}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return}this.logger.info(`Emitting audioUpdate to the UI Kit for self. Audio enabled: ${this.audioEnabled}. Audio track available: ${!!this.audioTrack}.`),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}}async enableVideo(t){var e;if(a(this,kt).canProduceVideo!==G.NotAllowed&&!(a(this,kt).canProduceVideo===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if((e=a(this,et))==null||e.getValue("callstats").videoOn(),await this.localMediaHandler.enableVideo(t),a(this,Fe,Je)&&this.stageStatus==="ON_STAGE")try{await a(this,tt,St).shareWebcam(this.videoTrack)}catch(r){this.logger.error("Self::enableVideo::Error while sharing video",{error:r}),this.videoEnabled&&this.localMediaHandler.disableVideo()}this.logger.info(`Emitting videoUpdate to the UI Kit for self. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),this.logger.info("Self.enableVideo",{...Ui(this)})}}async updateVideoConstraints(t){if(!this.localMediaHandler.updateVideoConstraints)throw new C("Unsupported","1102");await this.localMediaHandler.updateVideoConstraints(t)}async enableScreenShare(){var t;if(!a(this,Fe,Je))throw new C("Can`t enable screenshare without joining room","1105");if(a(this,kt).canProduceScreenshare!==G.NotAllowed&&!(a(this,kt).canProduceScreenshare===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&(this.screenShareEnabled&&this.logger.info("An screen share is already active, showing picker to select a new screen share"),await this.localMediaHandler.enableScreenShare(),this.screenShareTracks.audio||this.screenShareTracks.video)){try{await a(this,tt,St).shareScreen(this.screenShareTracks)}catch(e){this.logger.error("Self::enableScreenShare::Error while sharing screen",{error:e}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.logger.info(`Emitting screenShareUpdate to the UI Kit for self. Screen sharing enabled: ${this.screenShareEnabled}. Video track available: ${!!((t=this.screenShareTracks)!=null&&t.video)}.`),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}}async updateScreenshareConstraints(t){if(!this.localMediaHandler.updateScreenshareConstraints)throw new C("Unsupported","1102");await this.localMediaHandler.updateScreenshareConstraints(t)}async disableAudio(){var t;this.audioEnabled&&(this.localMediaHandler.disableAudio(),a(this,Fe,Je)&&a(this,tt,St).muteSelf(),this.logger.info(`Emitting audioUpdate to the UI Kit for self. Audio enabled: ${this.audioEnabled}. Audio track available: ${!!this.audioTrack}.`),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),(t=a(this,et))==null||t.getValue("callstats").audioOff())}async disableVideo(){var t;this.videoEnabled&&(await this.localMediaHandler.disableVideo(),a(this,Fe,Je)&&await a(this,tt,St).pauseWebcam(),this.logger.info(`Emitting videoUpdate to the UI Kit for self. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(t=a(this,et))==null||t.getValue("callstats").videoOff())}async disableScreenShare(){var t;this.screenShareEnabled&&(await this.localMediaHandler.disableScreenShare(),a(this,Fe,Je)&&await a(this,tt,St).disableScreenShare(),this.logger.info(`Emitting screenShareUpdate to the UI Kit for self. Screen sharing enabled: ${this.screenShareEnabled}. Video track available: ${!!((t=this.screenShareTracks)!=null&&t.video)}.`),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var i;f(this,Oa,t);const r=t?"pinned":"unpinned";(i=a(this,_r,Vn))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}get isPinned(){return a(this,Oa)}async pin(){if(!a(this,Fe,Je))throw new C("Can`t pin participants without joining room","1105");return this.show(),a(this,tt,St).pinPeer(this.id)}async unpin(){if(!a(this,Fe,Je))throw new C("Can`t unpin participants without joining room","1105");return a(this,tt,St).pinPeer(null)}async hide(){if(!a(this,Fe,Je))throw new C("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})}show(){if(!a(this,Fe,Je))throw new C("Can`t toggle participant tile without joining room","1105");this.hidden=!1,this.emit("toggleTile",{hidden:this.hidden})}async setDevice(t){var r,i,n;if(!t)throw new C("No device selected","1104");const e=this.getCurrentDevices();switch(t.deviceId&&(((r=e==null?void 0:e.audio)==null?void 0:r.deviceId)===t.deviceId||((i=e==null?void 0:e.video)==null?void 0:i.deviceId)===t.deviceId||((n=e==null?void 0:e.speaker)==null?void 0:n.deviceId)===t.deviceId)&&this.logger.warn("Self.setDevice.setting_to_in_use_device",{devices:[t]}),t.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(t,{saveDevicePreference:!0})}catch(o){a(this,Fe,Je)&&await a(this,tt,St).muteSelf(),this.logger.info(`Emitting audioUpdate to the UI Kit for self. Audio enabled: ${this.audioEnabled}. Audio track available: ${!!this.audioTrack}.`),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":await this.localMediaHandler.setSpeakerDevice(t,{saveDevicePreference:!0});break;case"videoinput":try{await this.localMediaHandler.setVideoDevice(t,{saveDevicePreference:!0})}catch(o){a(this,Fe,Je)&&await a(this,tt,St).pauseWebcam(),this.logger.info(`Emitting videoUpdate to the UI Kit for self. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}}cleanUpTracks(){var t,e,r,i;(t=this.audioTrack)==null||t.stop(),(e=this.rawAudioTrack)==null||e.stop(),(r=this.videoTrack)==null||r.stop(),(i=this.rawVideoTrack)==null||i.stop()}playAudio(){var t;return(t=a(this,Da,ih))==null?void 0:t.play()}registerVideoElement(t,e=!1){var r,i;t&&(e?a(this,Na).add(t):a(this,La).add(t),this.updateVideo(t),e||(i=a(this,_r,Vn))==null||i.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(r=this.raised)!=null?r:!1))}deregisterVideoElement(t,e=!1){if(!t){a(this,_r,Vn).removeSource(this.id);return}t.srcObject=void 0,e?a(this,Na).delete(t):(a(this,La).delete(t),a(this,_r,Vn).removeSource(this.id))}updateVideo(t,e=!1){var r,i,n;if(this.videoEnabled){if(this.videoTrack==null)return;const o=(r=t.srcObject)==null?void 0:r.getTracks()[0];if((o==null?void 0:o.id)===this.videoTrack.id)return;const c=new MediaStream;c.addTrack(this.videoTrack),t.srcObject=c,e||(i=a(this,_r,Vn))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(n=a(this,_r,Vn))==null||n.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},Ma=new WeakMap,kt=new WeakMap,Oa=new WeakMap,et=new WeakMap,_r=new WeakSet,Vn=function(){return a(this,et).getValue("pip")},tt=new WeakSet,St=function(){return a(this,et).getValue("roomNodeClient")},Da=new WeakSet,ih=function(){return a(this,et).getValue("audioPlayback")},Fe=new WeakSet,Je=function(){var t;return((t=a(this,et).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Na=new WeakMap,La=new WeakMap,fc=new WeakSet,im=function(){Array.from(a(this,La)).forEach(t=>this.updateVideo(t,!1)),Array.from(a(this,Na)).forEach(t=>this.updateVideo(t,!0))},eT);yt([E.trace("Self.cleanupEvents")],ze.prototype,"cleanupEvents",1),yt([E.trace("Self.setupEvents")],ze.prototype,"setupEvents",1),yt([E.trace("Self.setupTracks")],ze.prototype,"setupTracks",1),yt([E.trace("Self.destructMediaHandler")],ze.prototype,"destructMediaHandler",1),yt([E.trace("Self.removeDocumentEventListeners")],ze.prototype,"removeDocumentEventListeners",1),yt([ur.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"Self.toggleAudio",timeout:3e3}),E.trace("Self.enableAudio")],ze.prototype,"enableAudio",1),yt([ur.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"Self.toggleVideo",timeout:3e3}),E.trace("Self.enableVideo")],ze.prototype,"enableVideo",1),yt([E.trace("Self.updateVideoConstraints")],ze.prototype,"updateVideoConstraints",1),yt([E.trace("Self.enableScreenShare"),ur.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3})],ze.prototype,"enableScreenShare",1),yt([E.trace("Self.updateScreenshareConstraints")],ze.prototype,"updateScreenshareConstraints",1),yt([ur.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"Self.toggleAudio",timeout:3e3}),E.trace("Self.disableAudio")],ze.prototype,"disableAudio",1),yt([ur.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"Self.toggleVideo",timeout:3e3}),E.trace("Self.disableVideo")],ze.prototype,"disableVideo",1),yt([ur.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3}),E.trace("Self.disableScreenShare")],ze.prototype,"disableScreenShare",1),yt([E.trace("Self.setDevice")],ze.prototype,"setDevice",1),ze=yt([pt("1100")],ze);class wp extends Error{constructor(t){super(t!=null?t:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,wp)}}class Pp extends Error{constructor(t){super(t!=null?t:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Pp)}}class kp{constructor(t,e=!1){p(this,"pendingTasks",new Map);p(this,"nextTaskId",0);p(this,"stopping",!1);m(this,vc,void 0);this.log=e,f(this,vc,{info:e&&t?t.info:()=>{}})}get size(){return this.pendingTasks.size}async push(t,e,r){if(e=e!=null?e:t.name,typeof t!="function")throw new TypeError("given task is not a function");if(e)try{Object.defineProperty(t,"name",{value:e})}catch(i){}return new Promise((i,n)=>{const o={id:this.nextTaskId++,task:t,metadata:r,name:e,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:c=>{if(o.completed)return;o.completed=!0,this.pendingTasks.delete(o.id),i(c);const[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)},reject:c=>{if(!o.completed&&(o.completed=!0,this.pendingTasks.delete(o.id),n(c),!this.stopping)){const[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)}}};this.pendingTasks.set(o.id,o),this.pendingTasks.size===1&&this.execute(o)})}stop(){this.stopping=!0;for(const t of this.pendingTasks.values())t.reject(new wp);this.stopping=!1}remove(t){const e=Array.from(this.pendingTasks.values())[t];e&&e.reject(new Pp)}get(t){return Array.from(this.pendingTasks.values())[t]}dump(){const t=Date.now();let e=0;return Array.from(this.pendingTasks.values()).map(r=>({idx:e++,task:r.task,name:r.name,enqueuedTime:r.executedAt?r.executedAt-r.enqueuedAt:t-r.enqueuedAt,executionTime:r.executedAt?t-r.executedAt:0}))}async execute(t){if(t.executedAt)throw new Error("task already being executed");t.executedAt=Date.now();try{const e=this.pendingTasks.size,r=await t.task(),i=Date.now();a(this,vc).info(`AwaitQueue.push(${t.name})_timings`,{awaitQueueTask:{id:t.id,metadata:t.metadata,queueSizeAtStart:e,execTime:(i-t.executedAt)/1e3,taskStartTime:(t.executedAt-t.enqueuedAt)/1e3}}),t.resolve(r)}catch(e){t.reject(e)}}}vc=new WeakMap;class Ao extends Error{constructor(t){super(t),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Ao):this.stack=new Error(t).stack}}class Nt extends Error{constructor(t){super(t),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Nt):this.stack=new Error(t).stack}}class Jr extends Error{constructor(t){super(t),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Nt):this.stack=new Error(t).stack}}const rS=s=>new Promise(t=>setTimeout(t,s));async function _l(s,t){return new Promise(async(e,r)=>{const{strategy:i,maxRetryCount:n,delayTime:o}={strategy:"linear",maxRetryCount:3,delayTime:10,...t};let c=0,d,l=!1;const u=h=>{l=!0,r(h)};for(;c<n;){try{const h=await s(c,u);return e(h)}catch(h){if(d=h,l)break;if(c<n)i==="linear"?await rS(o*(c+1)):i==="exponential"&&await rS(o*(c+Math.max(0,c-1)));else break}c+=1}return r(d)})}const Cl={VP8:"video/VP8",VP9:"video/VP9",H264:"video/H264",H265:"video/H265",AV1:"video/AV1"},Fi={OPUS:"audio/opus",PCMA:"audio/PCMA",PCMU:"audio/PCMU"},iS={video:Cl.VP8,audio:Fi.OPUS,screenshareVideo:Cl.VP8,screenshareAudio:Fi.OPUS};function z1(s,t){return typeof s=="string"&&Object.prototype.hasOwnProperty.call(t,s)}function Rl(s,t,e){const r=s||e;if(!z1(r,t))return{valid:!1,message:`Invalid codec "${String(r)}". Expected one of: ${Object.keys(t).join(", ")}.`};const i=t[r],n=i.startsWith("audio/")?"audio":"video",o=RTCRtpSender.getCapabilities(n);return o!=null&&o.codecs.some(c=>c.mimeType.toLowerCase()===i.toLowerCase())?{valid:!0,mimeType:i}:{valid:!1,message:`Codec "${r}" (${i}) is not supported for sending ${n} in this browser.`}}function Y1(s){var n,o,c,d;const t=Rl((n=s==null?void 0:s.video)==null?void 0:n.codec,Cl,"VP8");if(t.valid===!1)return{valid:!1,message:`defaults.mediaProducerConfiguration.video.codec: ${t.message}`};const e=Rl((o=s==null?void 0:s.audio)==null?void 0:o.codec,Fi,"OPUS");if(e.valid===!1)return{valid:!1,message:`defaults.mediaProducerConfiguration.audio.codec: ${e.message}`};const r=Rl((c=s==null?void 0:s.screenshareVideo)==null?void 0:c.codec,Cl,"VP8");if(r.valid===!1)return{valid:!1,message:`defaults.mediaProducerConfiguration.screenshareVideo.codec: ${r.message}`};const i=Rl((d=s==null?void 0:s.screenshareAudio)==null?void 0:d.codec,Fi,"OPUS");return i.valid===!1?{valid:!1,message:`defaults.mediaProducerConfiguration.screenshareAudio.codec: ${i.message}`}:{valid:!0,codecs:{video:t.mimeType,audio:e.mimeType,screenshareVideo:r.mimeType,screenshareAudio:i.mimeType}}}function Q1(s){return s.map(t=>({channels:t.channels,clockRate:t.clockRate,mimeType:t.mimeType,sdpFmtpLine:t.sdpFmtpLine}))}function X1(s){return s.map(t=>({uri:t.uri}))}function Il(s,t){const e=t?s.codecs.filter(({mimeType:i})=>t.some(n=>n.toLowerCase()===i.toLowerCase())):s.codecs;return{codecs:Q1(e),headerExtensions:X1(s.headerExtensions?s.headerExtensions:[])}}function Z1(s=iS){const t=RTCRtpReceiver.getCapabilities("audio"),e=RTCRtpReceiver.getCapabilities("video"),r=RTCRtpSender.getCapabilities("audio"),i=RTCRtpSender.getCapabilities("video"),n={audio:Il(t),video:Il(e)};return{sender:{audio:Il(r,[s.audio,s.screenshareAudio]),video:Il(i,[s.video,s.screenshareVideo])},receiver:n}}var nS={},Al={},eN={get exports(){return Al},set exports(s){Al=s}},aS=eN.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(s){return s.encoding?"rtpmap:%d %s/%s/%s":s.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(s){return s.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(s){return s.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(s){return"extmap:%d"+(s.direction?"/%s":"%v")+(s["encrypt-uri"]?" %s":"%v")+" %s"+(s.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(s){return s.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{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(s){var t="candidate:%s %d %s %d %s %d typ %s";return t+=s.raddr!=null?" raddr %s rport %d":"%v%v",t+=s.tcptype!=null?" tcptype %s":"%v",s.generation!=null&&(t+=" generation %d"),t+=s["network-id"]!=null?" network-id %d":"%v",t+=s["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(s){var t="ssrc:%d";return s.attribute!=null&&(t+=" %s",s.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(s){return s.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(s){return s.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(s){return"imageattr:%s %s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(s){return"simulcast:%s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(s){return"ts-refclk:%s"+(s.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(s){var t="mediaclk:";return t+=s.id!=null?"id=%s %s":"%v%s",t+=s.mediaClockValue!=null?"=%s":"",t+=s.rateNumerator!=null?" rate=%s":"",t+=s.rateDenominator!=null?"/%s":"",t}},{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(aS).forEach(function(s){var t=aS[s];t.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})}),function(s){var t=function(c){return String(Number(c))===c?Number(c):c},e=function(c,d,l,u){if(u&&!l)d[u]=t(c[1]);else for(var h=0;h<l.length;h+=1)c[h+1]!=null&&(d[l[h]]=t(c[h+1]))},r=function(c,d,l){var u=c.name&&c.names;c.push&&!d[c.push]?d[c.push]=[]:u&&!d[c.name]&&(d[c.name]={});var h=c.push?{}:u?d[c.name]:d;e(l.match(c.reg),h,c.names,c.name),c.push&&d[c.push].push(h)},i=Al,n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);s.parse=function(c){var d={},l=[],u=d;return c.split(/(\r\n|\r|\n)/).filter(n).forEach(function(h){var g=h[0],v=h.slice(2);g==="m"&&(l.push({rtp:[],fmtp:[]}),u=l[l.length-1]);for(var y=0;y<(i[g]||[]).length;y+=1){var k=i[g][y];if(k.reg.test(v))return r(k,u,v)}}),d.media=l,d};var o=function(c,d){var l=d.split(/=(.+)/,2);return l.length===2?c[l[0]]=t(l[1]):l.length===1&&d.length>1&&(c[l[0]]=void 0),c};s.parseParams=function(c){return c.split(/;\s?/).reduce(o,{})},s.parseFmtpConfig=s.parseParams,s.parsePayloads=function(c){return c.toString().split(" ").map(Number)},s.parseRemoteCandidates=function(c){for(var d=[],l=c.split(" ").map(t),u=0;u<l.length;u+=3)d.push({component:l[u],ip:l[u+1],port:l[u+2]});return d},s.parseImageAttributes=function(c){return c.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(o,{})})},s.parseSimulcastStreamList=function(c){return c.split(";").map(function(d){return d.split(",").map(function(l){var u,h=!1;return l[0]!=="~"?u=t(l):(u=t(l.substring(1,l.length)),h=!0),{scid:u,paused:h}})})}}(nS);var _p=Al,tN=/%[sdv%]/g,sN=function(s){var t=1,e=arguments,r=e.length;return s.replace(tN,function(i){if(t>=r)return i;var n=e[t];switch(t+=1,i){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}})},Mo=function(s,t,e){var r=t.format instanceof Function?t.format(t.push?e:e[t.name]):t.format,i=[s+"="+r];if(t.names)for(var n=0;n<t.names.length;n+=1){var o=t.names[n];t.name?i.push(e[t.name][o]):i.push(e[t.names[n]])}else i.push(e[t.name]);return sN.apply(null,i)},rN=["v","o","s","i","u","e","p","c","b","t","r","z","a"],iN=["i","c","b","a"],nN=function(s,t){t=t||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(n){n.payloads==null&&(n.payloads="")});var e=t.outerOrder||rN,r=t.innerOrder||iN,i=[];return e.forEach(function(n){_p[n].forEach(function(o){o.name in s&&s[o.name]!=null?i.push(Mo(n,o,s)):o.push in s&&s[o.push]!=null&&s[o.push].forEach(function(c){i.push(Mo(n,o,c))})})}),s.media.forEach(function(n){i.push(Mo("m",_p.m[0],n)),r.forEach(function(o){_p[o].forEach(function(c){c.name in n&&n[c.name]!=null?i.push(Mo(o,c,n)):c.push in n&&n[c.push]!=null&&n[c.push].forEach(function(d){i.push(Mo(o,c,d))})})})}),i.join(`\r
|
|
15
15
|
`)+`\r
|
|
16
|
-
`},Hi=rS,iN=rN,Al=iN,qi=Hi.parse;Hi.parseParams,Hi.parseFmtpConfig,Hi.parsePayloads,Hi.parseRemoteCandidates,Hi.parseImageAttributes,Hi.parseSimulcastStreamList;class Ml extends Tt.EventEmitter{constructor(e){super();m(this,vc,void 0);f(this,vc,e),this.setMaxListeners(1/0)}get logger(){return a(this,vc).getValue("logger")}safeEmit(e,...r){const i=this.listenerCount(e);try{return this.emit(e,...r)}catch(n){return this.logger.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:n}),Boolean(i)}}async safeEmitAsPromise(e,...r){const i={}.EVENT_PROMISE_TIMEOUT?parseInt({}.EVENT_PROMISE_TIMEOUT,10):1e4;return this.safeEmitAsPromiseWithTimeout(e,i,...r)}async safeEmitAsPromiseWithTimeout(e,r,...i){return new Promise((n,o)=>{setTimeout(o,r,"event request timeout");try{this.emit(e.toString(),...i,n,o)}catch(c){this.logger.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:c}),o(c)}})}}vc=new WeakMap;function nN(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}class aN extends Ml{constructor(e,r){var i;super(e);m(this,qs);m(this,Tc);m(this,fu);m(this,vu);p(this,"rtpReceiver");p(this,"id");p(this,"localId");p(this,"producerId");p(this,"producingTransportId");p(this,"mimeType");p(this,"track");p(this,"peerId");p(this,"appData");p(this,"transceiver");m(this,Sc,void 0);m(this,fn,void 0);m(this,Hs,void 0);m(this,gu,void 0);this.id=r.id,this.localId=r.localId,f(this,Sc,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,f(this,Hs,!1),this.producerId=r.producerId,this.track=r.track,f(this,fn,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,R(this,fu,gT).call(this),f(this,gu,e)}get closed(){return a(this,Hs)}get kind(){return this.track.kind}get paused(){return a(this,fn)}reassignPeer(e){this.peerId=e}close(e,r){a(this,Hs)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,a(this,qs,Pi)),f(this,Hs,!0),r&&(R(this,vu,fT).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(a(this,Hs))throw new Nt("closed");return a(this,Sc).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",a(this,qs,Pi)),a(this,Hs)){this.logger.error("consumer::pause() | Consumer closed",a(this,qs,Pi));return}f(this,fn,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",a(this,qs,Pi)),a(this,Hs)){this.logger.error("Consumer::resume() | Consumer closed",a(this,qs,Pi));return}f(this,fn,!1),this.track.enabled=!0,this.safeEmit("resume")}}Sc=new WeakMap,fn=new WeakMap,Hs=new WeakMap,gu=new WeakMap,qs=new WeakSet,Pi=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},Tc=new WeakSet,rm=function(){this.logger.debug('Consumer::track "ended" event',a(this,qs,Pi)),this.safeEmit("trackended")},fu=new WeakSet,gT=function(){this.track.addEventListener("ended",R(this,Tc,rm).bind(this))},vu=new WeakSet,fT=function(){try{this.track.removeEventListener("ended",R(this,Tc,rm)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...a(this,qs,Pi),error:e})}};class oN extends Ml{constructor(e,r){var i,n;super(e);m(this,Yt);p(this,"id");p(this,"localId");m(this,Cs,void 0);p(this,"kind");p(this,"appData");p(this,"rtpSender");m(this,Va,void 0);m(this,xa,void 0);m(this,vn,void 0);m(this,ps,!1);m(this,dt,void 0);m(this,mi,void 0);m(this,$a,void 0);m(this,Su,void 0);this.id=r.id,this.localId=r.localId,f(this,dt,r.track),this.kind=(i=r.track)==null?void 0:i.kind,f(this,mi,r.disableTrackOnPause?!((n=r.track)!=null&&n.enabled):!1),f(this,$a,void 0),f(this,Va,r.stopTracks),f(this,xa,r.disableTrackOnPause),f(this,vn,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),f(this,Cs,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),f(this,Su,e)}get closed(){return a(this,ps)}get track(){return a(this,dt)}get paused(){return a(this,mi)}get maxSpatialLayer(){return a(this,$a)}async close(e){if(a(this,ps))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,a(this,Yt,As)),f(this,ps,!0),this._destroyTrack(),e===Ol){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await a(this,Cs).stopSending(this.localId),{answer:n}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(n)}async getStats(){if(a(this,ps))throw new Nt("closed");return a(this,Cs).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",a(this,Yt,As)),a(this,ps)&&this.logger.error("Producer::pause() | Producer closed",a(this,Yt,As)),f(this,mi,!0),a(this,dt)&&a(this,xa)&&(a(this,dt).enabled=!1),a(this,vn)&&a(this,Cs).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",a(this,Yt,As)),a(this,ps)){this.logger.error("Producer::resume() | Producer closed",a(this,Yt,As));return}f(this,mi,!1),a(this,dt)&&a(this,xa)&&(a(this,dt).enabled=!0),a(this,vn)&&a(this,Cs).replaceTrack(this.localId,a(this,dt)),this.emit("resume")}async replaceTrack({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,a(this,Yt,As)),a(this,ps)){if(e&&a(this,Va))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...a(this,Yt,As),error:r})}throw new Nt("closed")}else if(e&&e.readyState==="ended")throw new Nt("track ended");if(e===a(this,dt)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,a(this,Yt,As));return}(!a(this,vn)||!a(this,mi))&&await a(this,Cs).replaceTrack(this.localId,e),this._destroyTrack(),f(this,dt,e),this._handleTrack()}async setMaxSpatialLayer(e){if(a(this,ps))throw new Nt("closed");if(this.kind!=="video")throw new Ao("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await a(this,Cs).setMaxSpatialLayer(this.localId,e),f(this,$a,e)}async setRtpEncodingParameters(e){if(a(this,ps))throw new Nt("closed");if(typeof e!="object")throw new TypeError("invalid params");await a(this,Cs).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,a(this,Yt,As)),this.safeEmit("trackended",this.track.id)}_handleTrack(){a(this,dt)&&a(this,dt).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(a(this,dt))try{a(this,dt).removeEventListener("ended",this._onTrackEnded),a(this,Va)&&a(this,dt).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...a(this,Yt,As),error:r})}}}Cs=new WeakMap,Va=new WeakMap,xa=new WeakMap,vn=new WeakMap,ps=new WeakMap,dt=new WeakMap,mi=new WeakMap,$a=new WeakMap,Su=new WeakMap,Yt=new WeakSet,As=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};const Ol="transport closed",cN=3e4,Ba=class extends Ml{constructor(e,{id:r,direction:i,handlerFactory:n,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:u,config:h}){var k,I,D;super(e);p(this,"awaitQueue");p(this,"observer");p(this,"id");p(this,"serverId");p(this,"direction");p(this,"maxSctpMessageSize");p(this,"handler");p(this,"connectionState","new");p(this,"producers");p(this,"consumers");p(this,"connected",!1);p(this,"transportConnectionPromise");p(this,"consumerTrackEvents");p(this,"unknownTracksMap");p(this,"appData");m(this,Ua,void 0);f(this,Ua,e);const g=e.getValue("logger");g.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const v=nN(l,{});delete v.iceServers,delete v.iceTransportPolicy,delete v.bundlePolicy,delete v.rtcpMuxPolicy,delete v.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new Pp(g,!0),this.handler=n(),this.handler.enableHighBitrate=(k=h==null?void 0:h.enableHighBitrate)!=null?k:!1,this.handler.enableStereo=(I=h==null?void 0:h.enableStereo)!=null?I:!1,this.handler.enableDtx=(D=h==null?void 0:h.enableDtx)!=null?D:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:o,iceTransportPolicy:c,additionalSettings:l,proprietaryConstraints:d}),this.appData=u||{};const y=3e4;this.transportConnectionPromise=new Promise(N=>{const B=setTimeout(()=>{g.error("ICE connection timeout - possible firewall blocking WebRTC or TURN unreachable",{transport:{id:this.id,type:this.direction}}),N(!1)},y);this.once("connected",()=>{clearTimeout(B),N(!0)}),this.once("disconnect",()=>{clearTimeout(B),N(!1)}),this.once("close",()=>{clearTimeout(B),N(!1)})}),this.handler.on("@connectionstatechange",N=>{N!==this.connectionState&&(this.connectionState=N,N==="connected"&&(this.connected=!0,this.emit("connected")),N==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(N==="failed"||N==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",N))}),this.handler.on("@icecandidate",({candidate:N})=>{this.closed||this.safeEmit("icecandidate",N)})}get closed(){return this.connectionState==="closed"}setServerId(e){this.serverId!==e&&(this.serverId=e,this.emit("serveridchange",e))}close(){this.closed||(this.logger.debug("Transport close called"),this.connectionState="closed",this.awaitQueue.stop(),this.awaitQueue=void 0,this.connected=!1,this.handler.close(),Array.from(this.producers.values()).forEach(e=>{e.close(Ol).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(Ol)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new Nt("closed");return this.handler.getTransportStats()}async connect(e){try{if(await this.awaitQueue.push(async()=>{const{offerSdp:r,callback:i}=await this.handler.connect(),{transportId:n,answer:o}=await e(r);this.setServerId(n),await i(o)}),!await this.transportConnectionPromise)throw new Error("ice connection failed")}catch(r){throw this.logger.error("transport failed to connect:",{error:r}),r}}async restartIce(){if(this.logger.debug("restartIce()"),this.closed)throw new Nt("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new Ao("not a sending Transport");if(r.readyState==="ended")throw new Nt("track ended");if(i&&typeof i!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!await this.transportConnectionPromise)throw new Jr("transport not connected");return!0}async produce(e,r){if(!await this.canProduce(e))throw new Error("Cannot produce");const{track:n,encodings:o,codecOptions:c,stopTracks:d=!0,disableTrackOnPause:l=!0,zeroRtpOnPause:u=!1,appData:h={}}=e;this.logger.debug(`produce() [track:${n.id}]`);const{producerId:g,localId:v,rtpSender:y}=await this.awaitQueue.push(async()=>{const{offerSdp:k,callback:I,sender:D,mid:N}=await this.handler.send({track:n,encodings:o,codecOptions:c,screenShare:h==null?void 0:h.screenShare}),{answer:B,producerId:U}=await r({offer:k,kind:n.kind,paused:l?!n.enabled||Object.hasOwn(n,"fakeTracks"):!1,appData:{...h||{},mid:N},codecOptions:c,producingTransportId:this.serverId}),j=await I(B);return{producerId:U,localId:j,rtpSender:D}},"Transport.produce");return this.createProducerObject({id:g,localId:v,track:n,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:u,appData:h,handler:this.handler,rtpSender:y})}async createProducerObject(e){const r=new oN(a(this,Ua),e);return this.producers.set(r.id,r),r.once("close",()=>{this.producers.delete(r.id)}),this.emit("newproducer",r),r}async closeProducer(e){await this.awaitQueue.push(e.close.bind(e),"Transport.closeProducer")}async canConsume(){if(this.closed)throw new Nt("closed");if(this.direction!=="recv")throw new Ao("not a receiving transport");if(!await this.transportConnectionPromise)throw new Jr("transport not connected");return!0}async consume(e,r,i){return this.awaitQueue.push(async()=>{const n={},{consumerStates:o,sessionDescription:c,failedProducers:d}=await r(e);o.forEach((u,h)=>{n[h]=this.createConsumerObjectAndWaitForTrack({...u,producerId:h})}),c&&(this.logger.info("Session description found, sending negotiation request"),await i(c));const l=[];return await Promise.all(Object.entries(n).map(([u,h])=>h.then(g=>l.push(g)).catch(()=>{this.logger.error(`Failed to create consumer object, producer: ${u}`,{error:{message:"This should not happen"},transport:{serverId:this.serverId}})}))),{consumers:l,failedProducers:d}},"Transport.consume",{producersLength:e.length})}static parseCodecAndFmtpMappings(e,r){const i=qi(e.sdp),n={};return i.media.forEach(o=>{r.includes(o.mid.toString())&&(n[o.mid.toString()]={rtp:o.rtp,fmtp:o.fmtp,payloads:o.payloads,rtcpFb:o.rtcpFb})}),n}static setCodecAndFmtpMappings(e,r,i){const n=qi(e.sdp);return n.media=n.media.map(c=>{if(r.includes(c.mid.toString())){const d={...c};return d.rtp=i[c.mid.toString()].rtp,d.fmtp=i[c.mid.toString()].fmtp,d.payloads=i[c.mid.toString()].payloads,d.rtcpFb=i[c.mid.toString()].rtcpFb,d}return c}),{...e,sdp:Al(n)}}static parseHeaderExtensionMappings(e){const r=qi(e.sdp),i={};return r.media.forEach(n=>{i[n.mid]=n.ext}),i}static setHeaderExtensionMappings(e,r){const i=qi(e.sdp);return i.media=i.media.map(o=>{const c={...o};return c.ext=r[o.mid],c}),{...e,sdp:Al(i)}}async closeConsumers(e,r){try{const i=e.map(l=>l.transceiver.mid),n=Ba.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=Ba.parseHeaderExtensionMappings(this.handler.pc.remoteDescription);this.logger.info("Stopping transceivers",{consumerIds:e.map(({id:l})=>l)}),e.forEach(l=>l.close(void 0,!0));let c=await this.handler.pc.createOffer();this.logger.info("[SDP] Created offer for closing consumers",{sdp:c.sdp}),c=Ba.setCodecAndFmtpMappings(c,i,n),c=Ba.setHeaderExtensionMappings(c,o),this.logger.info("[SDP] Updated codec and fmtp mappings in close consumer offer",{sdp:c.sdp}),await this.setLocalDescription(c),this.logger.info("Successfully set local description in close consumers");const d=await r(e,c);this.logger.info("[SDP] Received answer in close consumers",{sdp:d.sdp}),await this.setRemoteDescription(d),this.logger.info("[SDP] Remote description was set successfully in close consumers",{sdp:d.sdp})}catch(i){this.logger.error("Failed to close consumers",{error:i})}}async setRemoteOffer(e){try{this.logger.info("[SDP] Received offer from SFU",{sdp:e.sdp}),await this.setRemoteDescription(e);const r=await this.handler.pc.createAnswer();this.logger.info("[SDP] Created answer corresponding to received offer",{sdp:r.sdp});const i=qi(r.sdp);return i.media=i.media.map(n=>{if(n.type==="audio"){const o={...n},c=o.fmtp.find(l=>l.payload===111);return c&&(c.config+=";stereo=1;sprop-stereo=1"),o.rtcpFb||(o.rtcpFb=[]),o.rtcpFb.some(l=>l.type==="nack")||o.rtcpFb.push({payload:parseInt(o.payloads,10),type:"nack"}),o}return n}),r.sdp=Al(i),this.logger.info("[SDP] Setting munged SDP",{sdp:r.sdp}),await this.setLocalDescription(r),this.logger.info("[SDP] Successfully set local description",{sdp:r.sdp}),r}catch(r){throw this.logger.error("Set remote offer failed",{error:r}),r}}_ontrack(e){const{track:r,transceiver:i}=e;this.logger.info(`track event received [trackId: ${r.id}] [mid: ${i.mid}]`);const n=`${i.mid}:${r.kind}`;r.addEventListener("ended",()=>{this.logger.info(`rtc consumer track ended [trackId: ${r.id}]`),this.unknownTracksMap.delete(n)});const o=this.consumerTrackEvents.get(n);o?(o(r,i),this.consumerTrackEvents.delete(n)):(this.logger.warn(`track event handler not found ${n}`),this.unknownTracksMap.set(n,e))}async createConsumerObjectAndWaitForTrack(e){const{consumerId:r,producerId:i,producingPeerId:n,producingTransportId:o,streamId:c,paused:d,screenShare:l,appData:u,kind:h,mimeType:g}=e,v=`${c}:${h}`,y={...e,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(k,I)=>{const D=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${v} producingPeerId: ${n}`),this.consumerTrackEvents.delete(v),y.isTimedout=!0,I(y)},cN),N=(U,j)=>{try{if(U.readyState==="ended")clearTimeout(D),I(y);else{const Z=U;Z.enabled=!0,this.handler.midTransceiverMap.set(j.mid,j);const re=new aN(a(this,Ua),{id:r,localId:j.mid,transceiver:j,track:Z,paused:d,producerId:i,producingPeerId:n,producingTransportId:o,handler:this.handler,appData:{...u,screenShare:l,peerId:n},rtpReceiver:j.receiver,mimeType:g});this.consumers.set(r,re),re.once("close",()=>{this.consumers.delete(re.id),this.handler.midTransceiverMap.delete(j.mid)}),this.logger.info(`${l?"screenshare":"participant"} ${h} consumer ${r} created for producer ${i} of remote producing peer ${n} with track ${U.id} on mid ${j.mid}`),this.emit("newconsumer",re),clearTimeout(D),k(re)}}catch(Z){this.logger.error(`Error while creating ${l?"screenshare":"participant"} ${h} consumer for producerId ${i} of remote peer ${n}`,Z),clearTimeout(D),I(y)}},B=this.unknownTracksMap.get(v);B?(this.logger.info(`track event already received for ${l?"screenshare":"participant"} ${h} consumer ${r} of a remote peer ${n} with trackId ${B.track.id} on mid ${B.transceiver.mid} having key ${v}`),this.unknownTracksMap.delete(v),N(B.track,B.transceiver)):(this.logger.info(`Registering onTrack handler for ${l?"screenshare":"participant"} ${h} consumer ${r} of a remote peer ${n} with key ${v}`),this.consumerTrackEvents.set(v,N))})}async setRemoteDescription(e){await this.handler.pc.setRemoteDescription(e)}async setLocalDescription(e){this.logger.debug(`[SDP] ${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),await this.handler.pc.setLocalDescription(e)}};let _p=Ba;Ua=new WeakMap;class dN{constructor(t){m(this,st,void 0);p(this,"events");f(this,st,t),this.events=Es}async joinRoom(t,e,r,i=!1){const n={roomUuid:t,displayName:e,prejoined:i,capabilities:r};return(await a(this,st).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:vR.toBinary(n),timeout:5e3})).payload}async connectTransport(t){const e=(await a(this,st).sendMessagePromise(this.events.createWebRTCTransport,GC.toBinary(t))).payload,{transportId:r,description:i,producerIds:n}=Gf.fromBinary(e),o={sdp:i==null?void 0:i.sdp,type:i.type};return{transportId:r,answer:o,producerIds:n}}async produce(t){var n,o;const e=(await a(this,st).sendMessagePromise(this.events.produce,OR.toBinary(t))).payload,r=pI.fromBinary(e);return{answer:{sdp:(n=r==null?void 0:r.description)==null?void 0:n.sdp,type:(o=r==null?void 0:r.description)==null?void 0:o.type},producerId:r.producerId}}async consume(t){const e=(await a(this,st).sendMessagePromise(this.events.consume,_R.toBinary(t))).payload,{consumerIdsMap:{map:r},description:i}=uI.fromBinary(e);return{consumerStateMap:r,sessionDescription:i}}async closeProducer(t){const e=(await a(this,st).sendMessagePromise(this.events.closeProducer,UR.toBinary(t))).payload,{description:r}=yI.fromBinary(e);return r}async closeConsumer(t){return(await a(this,st).sendMessagePromise(this.events.closeConsumer,FR.toBinary(t))).payload}async updateConsumersSimulcastConfig(t){return(await a(this,st).sendMessagePromise(this.events.updateConsumersSimulcastConfig,AR.toBinary(t))).payload}async hostControlForPeer(t,e){const r={audio:e==="audio",screeShare:!1,video:e==="video",participantId:t},i=(await a(this,st).sendMessagePromise(this.events.hostControlPeer,JR.toBinary(r))).payload;if(!i)return!1;const{status:n}=CI.fromBinary(i);return n==="success"}async hostControlForAll(t){const e={audio:t==="audio",screenShare:!1,video:t==="video"},r=(await a(this,st).sendMessagePromise(this.events.hostControlAllPeers,zR.toBinary(e))).payload;if(!r)return!1;const{status:i}=II.fromBinary(r);return i==="success"}async kickAll(){const t={propagateKickAcrossRooms:!1};a(this,st).sendMessagePromise(x.kickAll,Qf.toBinary(t))}async kickPeer(t){a(this,st).sendMessagePromise(x.kick,uv.toBinary(t))}async changeDisplayName(t){const e=(await a(this,st).sendMessagePromise(this.events.changeDisplayName,GR.toBinary(t))).payload;if(!e)return!1;const{status:r}=MI.fromBinary(e);return r==="success"}async notifySelfJoinComplete(){const t={},e=(await a(this,st).sendMessagePromise(this.events.selfJoinComplete,TR.toBinary(t))).payload;return qh.fromBinary(e)}async audioActivity(t){a(this,st).sendMessage(this.events.audioActivity,JC.toBinary(t))}}st=new WeakMap;var as=(s=>(s.NEW="new",s.CONNECTING="connecting",s.RECONNECTING="reconnecting",s.DISCONNECTED="disconnected",s.CONNECTED="connected",s.FAILED="failed",s.CLOSED="closed",s))(as||{});class Cp extends Ml{constructor(){super(...arguments);p(this,"_sendWebStream",new MediaStream);p(this,"_sendScreenShareStream",new MediaStream);p(this,"_direction");p(this,"pc");p(this,"_transportReady",!1);p(this,"_mapMidTransceiver",new Map);p(this,"enableHighBitrate",!1);p(this,"enableStereo",!1);p(this,"enableDtx",!0)}get midTransceiverMap(){return this._mapMidTransceiver}close(){if(this.logger.debug(`${this.name}::close()`),this.pc)try{this.pc.close()}catch(e){this.logger.error(`${this.name}::pc.close()`,{error:e})}}async restartIce(){this.logger.debug(`${this.name}::restartIce()`);const e=await this.pc.createOffer({iceRestart:!0});return this.logger.debug(`[SDP] ${this.name}::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:async i=>{this.logger.info(`[SDP] ${this.name}::restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),await this.pc.setRemoteDescription(i)}}}init({direction:e,iceServers:r,iceTransportPolicy:i,additionalSettings:n,proprietaryConstraints:o,onTrackHandler:c}){this.logger.debug("HandlerInterface::init()"),this._direction=e,this.pc=new RTCPeerConnection({iceServers:r||[],iceTransportPolicy:i||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...n},o),c&&this.pc.addEventListener("track",d=>{c(d)}),this._addEventListeners()}async connect(){this.pc.addTransceiver("audio",{direction:"sendonly"}),this.pc.addTransceiver("video",{direction:"sendonly",...this._direction==="send"?{sendEncodings:[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]}:{}});const e=await this.pc.createOffer();return await this.pc.setLocalDescription(e),this.logger.info(`[SDP] connect offer: ${JSON.stringify(e)}`),{offerSdp:e,callback:async i=>{this.logger.debug(`[SDP] ${this.name}::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),await this.pc.setRemoteDescription(i)}}}async getTransportStats(){return this.pc.getStats()}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}async getReceiverStats(e){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()}async stopSending(e){this._assertSendDirection(),this.logger.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 i=await this.pc.createOffer();return this.logger.debug(`[SDP] stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(i)}]`),await this.pc.setLocalDescription(i),{offerSdp:i,callback:async o=>{this.logger.debug(`[SDP] stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(o)}]`),await this.pc.setRemoteDescription(o),this.midTransceiverMap.delete(e)}}}async replaceTrack(e,r){this._assertSendDirection(),r?this.logger.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):this.logger.debug(`replaceTrack() [localId:${e}, no track]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");await i.sender.replaceTrack(r)}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters();n.encodings.forEach((o,c)=>{c<=r?o.active=!0:o.active=!1}),await i.sender.setParameters(n)}async setRtpEncodingParameters(e,r){this._assertSendDirection(),this.logger.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters();n.encodings.forEach((o,c)=>{n.encodings[c]={...o,...r}}),await i.sender.setParameters(n)}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}_addEventListeners(){this.pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this.pc.addEventListener("iceconnectionstatechange",()=>{switch(this.pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:this.logger.warn("unknown state");break}}),this.pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),this.logger.debug("negotiationneeded")}),this.pc.addEventListener("icegatheringstatechange",()=>{switch(this.pc.iceGatheringState){case"gathering":this.logger.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":this.logger.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:this.logger.warn("unknown state");break}}),this.pc.addEventListener("icecandidateerror",e=>{this.logger.warn("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})})}}class Rp extends Cp{static createFactory(t){return()=>new Rp(t)}get name(){return"Chrome74"}init({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:i,proprietaryConstraints:n,onTrackHandler:o}){this._direction=t,this.pc=new RTCPeerConnection({iceServers:e||[],iceTransportPolicy:r||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...i},n),o&&this.pc.addEventListener("track",c=>{o(c)}),this._addEventListeners()}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection();const n=typeof t=="string"?t:t.kind,o=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e});if(!navigator.isReactNative){this.logger.debug("creating new transceiver");const l=RTCRtpSender.getCapabilities(n);this.logger.info(`senders available params: ${JSON.stringify(l)}`);const u=[];r&&r.length&&r.forEach(h=>{var v;const g=l.codecs.find(y=>y.mimeType.toLowerCase()===h.mimeType.toLowerCase());if(h.parameters){this.logger.debug(`codecOption.parameters:${JSON.stringify(h.parameters)}`);const y=((v=g.sdpFmtpLine)==null?void 0:v.split(";"))||[];y.push(...h.parameters);const k=Array.from(new Set(y).values());g.sdpFmtpLine=k.join(";")}u.push(g)}),this.logger.info(`selected codecs: ${JSON.stringify(u)}`),o.setCodecPreferences(u)}const c=await this.pc.createOffer();if(await this.pc.setLocalDescription(c),r!=null&&r.some(({mimeType:l})=>l===Fi.OPUS)){const{enableDtx:l,enableStereo:u}=this,h=this.enableHighBitrate?u?128e3:64e3:u?64e3:32e3;c.sdp=c.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${l?"usedtx=1;":""}${u?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${h}`),c.sdp+=`a=rtcp-fb:111 nack\r
|
|
17
|
-
`}this.midTransceiverMap.set(o.mid,o);const d=async l=>(this.logger.debug(`[SDP] send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(l)}]`),await this.pc.setRemoteDescription(l),o.mid);return this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(c,void 0,2)}]`),{offerSdp:c,callback:d,sender:o.sender,mid:o.mid}}}class Dl extends Cp{constructor(e,r){super(e);p(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new Dl(e,r)}get name(){return"Firefox60"}async send({track:e,encodings:r,codecOptions:i,screenShare:n}){this._assertSendDirection();const o=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},c=this.pc.addTransceiver(e,{direction:"sendonly",streams:[n?this._sendScreenShareStream:this._sendWebStream],...o});if(!this.supportsSendEncodings&&r){r.reverse();const h=c.sender.getParameters();h.encodings=r,await c.sender.setParameters(h)}const d=(h,g)=>{var B;const v=qi(h),y=v.media[v.media.length-1],k=y.rtp.filter(U=>g.some(j=>j.mimeType.toLowerCase()===`${y.type}/${U.codec}`.toLowerCase())),I=y.fmtp.filter(U=>k.some(j=>j.payload===U.payload)),D=(B=y.rtcpFb)==null?void 0:B.filter(U=>k.some(j=>j.payload===U.payload)),N=k.map(U=>U.payload);return v.media[v.media.length-1].rtp=k,v.media[v.media.length-1].fmtp=I,v.media[v.media.length-1].rtcpFb=D,v.media[v.media.length-1].payloads=N.join(" "),Al(v)},l=await this.pc.createOffer();if(l.sdp=d(l.sdp,i),this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer:${JSON.stringify(l)}]`),await this.pc.setLocalDescription(l),i!=null&&i.some(({mimeType:h})=>h===Fi.OPUS)){const{enableDtx:h,enableStereo:g}=this,v=this.enableHighBitrate?g?128e3:64e3:g?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${g?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${v}`)}return this.midTransceiverMap.set(c.mid,c),{offerSdp:l,callback:async h=>(this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),await this.pc.setRemoteDescription(h),c.mid),sender:c.sender,mid:c.mid}}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters(),o=n.encodings.length-1-r;n.encodings.forEach((c,d)=>{d>=o?c.active=!0:c.active=!1}),await i.sender.setParameters(n)}}class Ip extends Cp{static createFactory(t){return()=>new Ip(t)}get name(){return"Safari12"}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection();const n=typeof t=="string"?t:t.kind;this.logger.debug("Safari12::creating new transceiver");const o=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e}),c=RTCRtpSender.getCapabilities(n);this.logger.info(`Safari12::senders available params: ${JSON.stringify(c)}`);const d=[];r&&r.length>0&&r.forEach(h=>{var v;const g=c.codecs.find(y=>y.mimeType.toLowerCase()===h.mimeType.toLowerCase());if(h.parameters){this.logger.info(`Safari12::codecOption.parameters:, ${JSON.stringify(h.parameters)}`);const y=((v=g.sdpFmtpLine)==null?void 0:v.split(";"))||[];y.push(...h.parameters);const k=[...new Set(y).values()];g.sdpFmtpLine=k.join(";")}d.push(g)}),this.logger.info(`Safari12::selected codecs: ${JSON.stringify(d)}`),o.setCodecPreferences(d);const l=await this.pc.createOffer();if(await this.pc.setLocalDescription(l),r!=null&&r.some(({mimeType:h})=>h===Fi.OPUS)){const{enableStereo:h,enableDtx:g}=this,v=this.enableHighBitrate?h?128e3:64e3:h?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${g?"usedtx=1;":""}${h?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${v}`)}return this.midTransceiverMap.set(o.mid,o),{offerSdp:l,callback:async h=>(this.logger.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),await this.pc.setRemoteDescription(h),o.mid),sender:o.sender,mid:o.mid}}}function lN(s){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){s.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return s.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=Pm.getParser(t),r=e.getEngine();if(e.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(e.satisfies({chrome:">=55",chromium:">=55"}))return;if(e.satisfies({firefox:">=110"}))return"Firefox110";if(e.satisfies({firefox:">=60"}))return"Firefox60";if(e.satisfies({ios:{OS:">=14.3",firefox:">=30.0"}})||e.satisfies({safari:">=12.0"})&&typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(e.satisfies({safari:">=11"})||e.satisfies({"microsoft edge":">=11"})&&e.satisfies({"microsoft edge":"<=18"}))return;if(r.name&&r.name.toLowerCase()==="blink"){const i=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);return i?Number(i[1])>=74?"Chrome74":void 0:"Chrome74"}if(r.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":void 0;s.warn("Device::this._detectDevice() | browser not supported");return}s.warn("Device::this._detectDevice() | unknown device")}class uN{constructor(t,{handlerName:e,handlerFactory:r}={}){p(this,"handlerFactory");m(this,Cr,void 0);m(this,Sn,void 0);const i=t.getValue("logger");if(i.debug("Device constructor() called."),f(this,Cr,t),f(this,Sn,i),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)a(this,Sn).debug(`Device::constructor() | handler given: ${e}`);else if(e=lN(a(this,Sn)),e)a(this,Sn).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=Rp.createFactory(a(this,Cr));break;case"Safari12":this.handlerFactory=Ip.createFactory(a(this,Cr));break;case"Firefox60":this.handlerFactory=Dl.createFactory(a(this,Cr),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=Dl.createFactory(a(this,Cr),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=Ci();return new _p(a(this,Cr),{id:e,...t,handlerFactory:this.handlerFactory})}}Cr=new WeakMap,Sn=new WeakMap;const hN=2e3;class pN extends Tt.EventEmitter{constructor(e,r){super();m(this,Gs);m(this,wc);m(this,Tu);m(this,Pc);m(this,yu);m(this,Eu);m(this,bu);m(this,wu);m(this,Pu);m(this,kc);m(this,Ws);p(this,"context");m(this,Fa,void 0);m(this,rt,void 0);m(this,it,void 0);m(this,yc,void 0);m(this,Ec,void 0);m(this,Tn,void 0);m(this,Ha,void 0);m(this,bc,void 0);m(this,qa,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});m(this,yn,void 0);m(this,js,"all");this.context=e,f(this,Tn,r),f(this,Fa,new uN(e)),f(this,Ha,new dN(r)),f(this,bc,Es),a(this,Gs,ki).mediaState={send:{state:as.NEW},recv:{state:as.NEW}},So(this.context,"forceRelay")&&f(this,js,"relay"),this.logger.info(`ICE Transport Policy initially set to ${a(this,js)}`),R(this,wc,im).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return a(this,Tn)}get socketHandler(){return a(this,Ha)}get sendTransport(){return a(this,rt)}get recvTransport(){return a(this,it)}get events(){return a(this,bc)}set sendTransportConnectedCallback(e){f(this,yc,e)}set recvTransportConnectedCallback(e){f(this,Ec,e)}async setupTransports(e){await R(this,Tu,vT).call(this,e);let r,i;e.send&&(r=R(this,Pc,nm).call(this,a(this,rt)).then(n=>{try{a(this,yc).call(this,n)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=R(this,Pc,nm).call(this,a(this,it)).then(n=>{try{a(this,Ec).call(this,n)}catch(o){this.logger.error("Failed to run recv transport callback")}})),await Promise.all([r,i])}stopTransports(e){var r,i;if(e.send&&this.sendTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,rt);this.logger.info("Closing send transport",{transport:{id:n,serverId:o,type:c}}),a(this,rt).close(),a(this,rt).removeAllListeners(),f(this,rt,void 0)}if(e.send&&(a(this,Gs,ki).mediaState.send.state!==as.CLOSED||a(this,Gs,ki).mediaState.send.sfuSessionId!==void 0)&&R(this,Ws,_i).call(this,{direction:"send",state:as.CLOSED}),e.recv&&this.recvTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,it);this.logger.info("Closing recv transport",{transport:{id:n,serverId:o,type:c}}),(r=a(this,it))==null||r.close(),(i=a(this,it))==null||i.removeAllListeners(),f(this,it,void 0)}e.recv&&(a(this,Gs,ki).mediaState.recv.state!==as.CLOSED||a(this,Gs,ki).mediaState.recv.sfuSessionId!==void 0)&&R(this,Ws,_i).call(this,{direction:"recv",state:as.CLOSED}),R(this,wc,im).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}Fa=new WeakMap,rt=new WeakMap,it=new WeakMap,yc=new WeakMap,Ec=new WeakMap,Tn=new WeakMap,Ha=new WeakMap,bc=new WeakMap,qa=new WeakMap,yn=new WeakMap,js=new WeakMap,Gs=new WeakSet,ki=function(){return this.context.getValue("connectionHandler")},wc=new WeakSet,im=function(){f(this,yn,{send:void 0,recv:void 0})},Tu=new WeakSet,vT=async function(e){var o,c,d,l,u,h,g,v;So(this.context,"forceRelay")&&f(this,js,"relay"),this.logger.info(`ICE Transport Policy set to ${a(this,js)}`);const n=await Ht().getICEServers().catch(y=>(this.logger.warn(`failed to get iceservers from server: ${y.message}`),[]));e.send&&R(this,Eu,TT).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(o=this.context.getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(l=(d=(c=this.context.getValue("defaults").mediaConfiguration)==null?void 0:c.audio)==null?void 0:d.enableHighBitrate)!=null?l:!1,enableStereo:(g=(h=(u=this.context.getValue("defaults").mediaConfiguration)==null?void 0:u.audio)==null?void 0:h.enableStereo)!=null?g:!1,enableDtx:!1},iceTransportPolicy:a(this,js)}),e.recv&&R(this,bu,yT).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(v=this.context.getValue("modules").e2ee)==null?void 0:v.enabled},iceTransportPolicy:a(this,js)})},Pc=new WeakSet,nm=async function(e){const{id:r,serverId:i,direction:n}=e;R(this,wu,ET).call(this,e);try{return await kl(async(c,d)=>{c>0&&this.logger.info(`Retrying ${n} transport connect, count: ${c}`,{transport:{id:r,serverId:i,type:n}});try{if(e.closed)throw new Jr("Cannot reconnect closed transport");await R(this,yu,ST).call(this,e)}catch(l){if(l instanceof Jr){this.logger.error(`Failed to connect ${n} transport. It will not be retried.`,{transport:e,error:l}),d(l);return}throw this.logger.error(`Failed to connect ${n} transport, retrying`,{transport:e,error:l}),l}},{delayTime:100,strategy:"exponential",maxRetryCount:15}),e}catch(o){throw this.logger.error(`Failed to connect ${n} transport after retries: ${e.id}. Transport reconnection will not be retried.`,{error:o,transport:{id:r,serverId:i,type:n}}),e.close(),e.removeAllListeners(),o}},yu=new WeakSet,ST=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!a(this,Tn).isConnected)throw new Jr("Socket is not connected");if(e.connectionState==="closed")throw new Jr("Transport is closed");try{await e.connect(n=>R(this,Pu,bT).call(this,i,n)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(n){throw a(this,qa).transportFailureCount[i]+=1,n.message==="ice connection failed"?new Jr(n.message):n}},Eu=new WeakSet,TT=function(e){var r,i;if(a(this,rt)&&a(this,rt).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=a(this,rt))==null?void 0:r.id,serverId:(i=a(this,rt))==null?void 0:i.serverId,type:"send"}});return}f(this,rt,a(this,Fa).createTransport({...e,direction:"send"})),R(this,Ws,_i).call(this,{state:as.NEW,direction:"send",sfuSessionId:a(this,rt).serverId}),this.context.getValue("callstats").configureSendTransport(a(this,rt))},bu=new WeakSet,yT=function(e){var r,i;if(a(this,it)&&a(this,it).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=a(this,it))==null?void 0:r.id,serverId:(i=a(this,it))==null?void 0:i.serverId,type:"recv"}});return}f(this,it,a(this,Fa).createTransport({...e,direction:"recv"})),R(this,Ws,_i).call(this,{state:as.NEW,direction:"recv",sfuSessionId:a(this,it).serverId}),this.context.getValue("callstats").configureRecvTransport(a(this,it))},wu=new WeakSet,ET=function(e){const{direction:r,id:i}=e;e.on("serveridchange",n=>{R(this,Ws,_i).call(this,{state:e.connectionState,direction:r,sfuSessionId:n})}),e.on("connectionstatechange",async n=>{R(this,Ws,_i).call(this,{state:n,direction:r,sfuSessionId:e.serverId}),this.logger.info(`Transport connection state changed to ${n} for ${r} transport`,{transport:{id:i,serverId:e.serverId,type:r,status:n}});const o=()=>{const c=a(this,yn)[r];c!==void 0&&(clearTimeout(c),a(this,yn)[r]=void 0)};switch(n){case"connected":o(),a(this,qa).lastConnectionTime=performance.now();break;case"disconnected":a(this,yn)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await R(this,kc,am).call(this,e.direction)},hN);break;case"failed":if(e.closed)return;o(),this.logger.warn(`${r} transport is in failed state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await R(this,kc,am).call(this,e.direction);break}}),e.on("icecandidate",async n=>{this.logger.debug("Sending iceCandidate:",{iceCandidate:n})})},Pu=new WeakSet,bT=async function(e,r){const i=e==="recv";try{const{sdp:n,type:o}=r,c={consuming:i,description:{sdp:n,type:o,target:i?nr.SUBSCRIBER:nr.PUBLISHER},producers:[]};return a(this,Ha).connectTransport(c)}catch(n){throw this.logger.error(`Error in ${e} transport connection:`,{error:n}),n}},kc=new WeakSet,am=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),a(this,Tn).isConnected&&a(this,qa).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),f(this,js,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:a(this,rt)}),this.context.getValue("peerSessionStore").emit(P.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:a(this,it)}),this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE);break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}const r=e==="send"?a(this,rt):a(this,it);R(this,Ws,_i).call(this,{state:as.CONNECTED,direction:e,sfuSessionId:r.serverId})},Ws=new WeakSet,_i=function(e){const{state:r,direction:i,sfuSessionId:n}=e;a(this,Gs,ki).mediaState[i]={state:r,sfuSessionId:n},this.context.getValue("peerSessionStore").emit(P.TRANSPORT_STATE_UPDATE,{transport:i,...a(this,Gs,ki).mediaState[i]})};class mN{constructor(t,e,r,i,n){m(this,ku,void 0);m(this,ms,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=n,f(this,ku,t),f(this,ms,t.getValue("logger"))}async create(t){if(!t||t&&t.length===0)throw new Error("List of producers is required");const e=new Map,r=[];t.forEach(d=>{const{producingPeerId:l,producerId:u,producingTransportId:h}=d,g={simulcast:{preferredRid:"f",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}};e.set(u,l),r.push({producingPeerId:l,producerId:u,producingTransportId:h,...g})});const i=await this.socketHandler.consume({requests:r,consumingTransportId:this.recvTransport.serverId}),n=new Map;t.forEach(d=>n.set(d.producerId,d));const o=new Map,c=[];return Object.entries(i.consumerStateMap).forEach(([d,l])=>{const u=n.get(d);if(!u)return;if(l.errorCode){a(this,ms).warn(`Consumer request failed for producer ${d}`,{error:{message:l.errorCode}}),c.push({...u,errorCode:l.errorCode});return}let h={};try{h=JSON.parse(l.producerState.appData)}catch(g){}try{const g=u.appData?JSON.parse(u.appData):{};g!=null&&g.e2ee&&Object.assign(h,{e2ee:g.e2ee})}catch(g){}o.set(d,{consumerId:l.consumerId,producingTransportId:u.producingTransportId,producingPeerId:u.producingPeerId,kind:u.kind,paused:u.pause,streamId:l.producerTrack.streamId,trackId:l.producerTrack.trackId,screenShare:u.screenShare,mimeType:u.mimeType,appData:h})}),{consumerStates:o,sessionDescription:i.sessionDescription,failedProducers:c}}async negotiate(t){try{a(this,ms).info("Negotiating socket consumer",{transport:this.recvTransport}),a(this,ms).debug(`[SDP] setting remote offer: ${JSON.stringify(t)} on recvTransport`,{transport:this.recvTransport});const e=await this.recvTransport.setRemoteOffer(t),r={transportId:this.recvTransport.serverId,description:{sdp:e.sdp,type:e.type,target:nr.SUBSCRIBER}};return a(this,ms).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,YC.toBinary(r)),a(this,ms).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){a(this,ms).error("Failed to renegotiate",{error:e});return}}async close(t){if(!t.length)return;const e=async(r,i)=>{const n=r.map(l=>l.localId);a(this,ms).info(`Closing consumers: ${JSON.stringify(n)}`);const o={description:{sdp:i.sdp,type:i.type,target:nr.SUBSCRIBER},consumerIds:n,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=bI.fromBinary(c).description;return{sdp:d.sdp,type:d.type}};await this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(t,e),"SocketConsumerStrategy.close",{consumersLength:t.length})}async switchConsumersToLayer(t,e){const r={requests:[],consumingTransportId:this.recvTransport.serverId},i=t.filter(n=>n&&n.id);i.forEach(({id:n,producingTransportId:o,localId:c})=>{r.requests.push({producerId:n,producingTransportId:o,mid:c,simulcast:{preferredRid:e===0?"q":"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}})}),await this.socketHandler.updateConsumersSimulcastConfig(r),a(this,ms).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:n})=>n)})}}ku=new WeakMap,ms=new WeakMap;class Ap{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return qi(t).media.filter(n=>e==="video"?n.type==="video":n.type==="audio").at(-1).msid}async create({offer:t,kind:e,paused:r,appData:i,codecOptions:n,producingTransportId:o}){var h,g;const c=Ap.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:nr.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(h=i.screenShare)!=null?h:!1,mimeType:(g=n==null?void 0:n[0])==null?void 0:g.mimeType,producingTransportId:o},{answer:l,producerId:u}=await this.socketHandler.produce(d);return{answer:l,producerId:u}}}function gN(s){try{const t=JSON.parse(s.message);if(typeof t!="object"||t===null)return{};const{errorCode:e,errorDescription:r}=t;return{...typeof e=="string"&&{errorCode:e},...typeof r=="string"&&{errorDescription:r}}}catch(t){return{}}}class fN extends pN{constructor(e,r){super(e,r);m(this,Cc);m(this,Cu);m(this,Ru);m(this,Iu);m(this,Au);m(this,En,void 0);m(this,Js,void 0);m(this,_c,void 0);m(this,Ks,void 0);m(this,_u,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});m(this,Rr,[]);m(this,ja,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{f(this,_c,new Ap(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{f(this,Ks,new mN(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return a(this,En)}get consumers(){return a(this,Js)}get logger(){return this.context.getValue("logger")}reset(){f(this,En,new Map),f(this,Js,new Map)}async createProducer(e,r){var i,n,o,c,d;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const l=(n=(i=e.codecOptions)==null?void 0:i[0])==null?void 0:n.mimeType,u=await this.sendTransport.produce(e,R(this,Cu,wT).bind(this));return(o=e.appData)!=null&&o.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_PRODUCER,u),R(this,Ru,PT).call(this,u,r),this.logger.info(`Created ${(c=u.appData)!=null&&c.screenShare?"screenshare":"participant"} ${u.kind} producer ${u.id} for local peer on mid ${u.localId} with codec ${l}.`),u}catch(l){throw this.logger.error(`Failed to create ${((d=e==null?void 0:e.track)==null?void 0:d.kind)||"unknown"} producer`,{error:l}),a(this,_u).producerCreationFailureCount+=1,l}}async closeProducer(e,r){var n,o;const i=this.producers.get(e);if(!i){this.logger.warn(`Producer with ID ${e} was not found`);return}r!=null&&r.stopTrack&&i.track.stop();try{await this.sendTransport.closeProducer(i),this.logger.info(`Closed ${(n=i.appData)!=null&&n.screenShare?"screenshare":"participant"} ${i.kind} producer ${e} of local peer on mid ${i.localId}. `),(o=this.context.getValue("modules").e2ee)!=null&&o.enabled&&this.context.getValue("peerSessionStore").emit(P.E2EE_INACTIVE_PRODUCER,i)}catch(c){this.logger.error("Failed to close producer on server",{error:c,producer:i})}}closeAllProducers(){return Promise.all(Array.from(a(this,En).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){a(this,ja)||clearTimeout(a(this,ja)),f(this,Rr,a(this,Rr).concat(e)),await R(this,Cc,om).call(this)}removeClosedConsumers(e){return e.filter(r=>{const i=a(this,Js).get(r);return i!=null&&i.closed?(a(this,Js).delete(r),!0):!1})}async closeConsumers(e){if(!a(this,Ks))return;const r=e.map(i=>this.consumers.get(i)).filter(i=>i!==void 0);r.length!==0&&await a(this,Ks).close(r)}closeAllConsumers(){return this.closeConsumers(Array.from(a(this,Js).keys()))}async switchConsumersToLayer(e,r){a(this,Ks).switchConsumersToLayer(e,r)}}En=new WeakMap,Js=new WeakMap,_c=new WeakMap,Ks=new WeakMap,_u=new WeakMap,Rr=new WeakMap,ja=new WeakMap,Cc=new WeakSet,om=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=a(this,Rr).splice(0,a(this,Rr).length);try{const i=new Set(Array.from(this.consumers.values()).map(({producerId:d})=>d)),n=r.filter(({producerId:d})=>!this.producers.get(d)&&!i.has(d));if(n.length===0)return;const{consumers:o,failedProducers:c}=await this.recvTransport.consume(n,R(this,Iu,kT).bind(this),a(this,Ks).negotiate.bind(a(this,Ks)));if(o.forEach(R(this,Au,_T).bind(this)),c!=null&&c.length){this.logger.error("Failed to create consumers for producers",{producers:c});const d=c.filter(({errorCode:l,producerId:u})=>l==="not_found_track_error"?(this.logger.error(`Track not found for producer: ${u}. This will not be retried.`),!1):l==="backend_error"?(this.logger.error("Unrecoverable error: backend error"),!1):!0);f(this,Rr,a(this,Rr).concat(d)),f(this,ja,setTimeout(R(this,Cc,om).bind(this),e))}}catch(i){const n=i instanceof Error?i:new Error(String(i));this.logger.error("failed to consume on transport",{error:n});const{errorCode:o,errorDescription:c}=gN(n);if(o==="internal_error"&&c==="Backend error"||o==="invalid_session_description"){this.logger.error("Irrecoverable error, closing current recvTransport to create a new one",{transport:this.recvTransport,error:{code:o,message:c}});try{this.stopTransports({recv:!0})}catch(d){}await this.setupTransports({recv:!0})}}},Cu=new WeakSet,wT=function(e){return a(this,_c).create(e)},Ru=new WeakSet,PT=function(e,r){e.on("close",async(i,n)=>{const{reason:o}=i,{offer:c}=i;if(this.logger.info("producer::closing",{debuggingHint:o,producer:{...e,status:"closing"}}),o!==Ol){const d={producerId:e.id,description:{sdp:c.sdp,type:c.type,target:nr.PUBLISHER}};try{const l=await this.socketHandler.closeProducer(d),u={sdp:l==null?void 0:l.sdp,type:l==null?void 0:l.type};this.logger.info("producer::closed",{producer:{...e,status:"closed"}}),n({answer:u})}catch(l){this.logger.error("producer close error",l)}}this.producers.delete(e.id),r()}),e.on("trackended",()=>{this.logger.info("producer::trackended",{producer:{...e,status:"UNKNOWN"}})}),a(this,En).set(e.id,e)},Iu=new WeakSet,kT=async function(e){try{return await this.recvTransport.canConsume(),await a(this,Ks).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},Au=new WeakSet,_T=function(e){e.on("close",async r=>{this.logger.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),a(this,Js).delete(e.id),this.context.getValue("peerSessionStore").emit(P.CONSUMER_CLOSED,{id:e.id})}),a(this,Js).set(e.id,e),this.context.getValue("peerSessionStore").emit(P.NEW_CONSUMER_CREATED,{id:e.id,appData:e.appData,peerId:e.peerId})};const Lu=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:r=3,hangoverFrames:i=5,noiseAdaptationRate:n=.95,voiceAdaptationRate:o=.99,minEnergyThreshold:c=.005,maxEnergyThreshold:d=.2,energyRatioThreshold:l=1.5,noiseHistorySize:u=50}={}){m(this,Mu);m(this,Ou);m(this,Rc,void 0);m(this,Ic,void 0);m(this,Ac,void 0);m(this,Ga,void 0);m(this,Wa,void 0);m(this,Ja,void 0);m(this,Mc,void 0);m(this,Oc,void 0);m(this,Ka,void 0);m(this,xt,void 0);m(this,Rs,void 0);m(this,Is,!1);m(this,bn,0);m(this,wn,0);m(this,Ir,[]);m(this,Dc,void 0);f(this,Ga,t),f(this,xt,t),f(this,Rc,e),f(this,Ic,r),f(this,Ac,i),f(this,Wa,n),f(this,Ja,o),f(this,Mc,c),f(this,Oc,d),f(this,Ka,l),f(this,Dc,u),f(this,Rs,t/2)}get voiceDetected(){return a(this,Is)}processAudioChunk(t){var o,c;const e=R(o=Lu,Du,IT).call(o,t),r=R(c=Lu,Nu,AT).call(c,t);return R(this,Mu,CT).call(this,e),e/a(this,Rs)>a(this,Ka)&&e>a(this,xt)&&r>a(this,Rc)?(f(this,bn,a(this,bn)+1),f(this,wn,a(this,Ac)),a(this,bn)>=a(this,Ic)&&f(this,Is,!0)):(f(this,bn,0),a(this,wn)>0?f(this,wn,a(this,wn)-1):a(this,Is)&&f(this,Is,!1),a(this,Is)||R(this,Ou,RT).call(this,e)),{energy:e,isVoice:a(this,Is)}}reset(){f(this,Is,!1),f(this,bn,0),f(this,wn,0),f(this,xt,a(this,Ga)),f(this,Rs,a(this,Ga)/2),f(this,Ir,[])}getThresholdInfo(){return{currentEnergyThreshold:a(this,xt),backgroundNoiseEnergy:a(this,Rs),energyRatioThreshold:a(this,Ka)}}};let Oo=Lu;Rc=new WeakMap,Ic=new WeakMap,Ac=new WeakMap,Ga=new WeakMap,Wa=new WeakMap,Ja=new WeakMap,Mc=new WeakMap,Oc=new WeakMap,Ka=new WeakMap,xt=new WeakMap,Rs=new WeakMap,Is=new WeakMap,bn=new WeakMap,wn=new WeakMap,Ir=new WeakMap,Dc=new WeakMap,Mu=new WeakSet,CT=function(t){a(this,Is)?f(this,xt,a(this,Ja)*a(this,xt)+(1-a(this,Ja))*t):f(this,xt,a(this,Wa)*a(this,xt)+(1-a(this,Wa))*a(this,Rs)),f(this,xt,Math.max(a(this,Mc),Math.min(a(this,Oc),a(this,xt))))},Ou=new WeakSet,RT=function(t){if(t<a(this,xt)*1.2)if(a(this,Ir).push(t),a(this,Ir).length>a(this,Dc)&&a(this,Ir).shift(),a(this,Ir).length>=10){const e=[...a(this,Ir)].sort((i,n)=>i-n),r=Math.floor(e.length/2);f(this,Rs,e[r])}else f(this,Rs,.95*a(this,Rs)+.05*t)},Du=new WeakSet,IT=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Nu=new WeakSet,AT=function(t){let e=0;for(let r=1;r<t.length;r+=1)(t[r]>=0&&t[r-1]<0||t[r]<0&&t[r-1]>=0)&&(e+=1);return e},m(Oo,Du),m(Oo,Nu);class nS{constructor(t){p(this,"RNAudioSampleHandler");m(this,Nc,void 0);f(this,Nc,t);const{RNAudioSampleHandlerImpl:e}=navigator;e==null||e.init().then(r=>{this.RNAudioSampleHandler=r}).catch(r=>{this.logger.error("ReactNativeAudioSampler: Failed to initialize audio sampler",r)})}get logger(){return a(this,Nc).getValue("logger")}get samples(){var e;const t=new Float32Array(1024);return(e=this.RNAudioSampleHandler)==null||e.getFloatTimeDomainData(t),t}stop(){var t;(t=this.RNAudioSampleHandler)==null||t.destructor()}}Nc=new WeakMap;class aS{constructor(t){p(this,"audioContext");p(this,"analyser");m(this,Lc,void 0);f(this,Lc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return a(this,Lc).getValue("logger")}get samples(){if(this.audioContext.state==="suspended")try{this.audioContext.resume()}catch(e){this.logger.error("AudioContextSampler: Failed to resume audio context",e)}const t=new Float32Array(this.analyser.frequencyBinCount);return this.analyser.getFloatTimeDomainData(t),t}set audioTrack(t){const e=new MediaStream;e.addTrack(t),this.audioContext.createMediaStreamSource(e).connect(this.analyser)}}Lc=new WeakMap;class oS{static setInterval(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setInterval(t,e,...r):global.setInterval(t,e,...r)}static clearInterval(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearInterval(t):global.clearInterval(t)}static setTimeout(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setTimeout(t,e,...r):global.setTimeout(t,e,...r)}static clearTimeout(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearTimeout(t):global.clearTimeout(t)}}const vN=60,SN=400,Bc=class{constructor(t,e){m(this,xc);m(this,Vu);m(this,Uc);m(this,Ar,void 0);m(this,Mr,void 0);m(this,Or,void 0);m(this,Vc,void 0);m(this,za,void 0);m(this,Ya,void 0);m(this,gi,void 0);m(this,Pn,void 0);m(this,Qa,void 0);m(this,kn,void 0);m(this,Dr,void 0);m(this,zs,void 0);this.reportRequest=e,f(this,kn,t),f(this,Ya,new Oo);const{isReactNative:r}=navigator;f(this,Dr,r?new nS(a(this,kn)):new aS(a(this,kn))),f(this,zs,r?oS:mp)}get logger(){return a(this,kn).getValue("logger")}set producerId(t){f(this,Or,t)}set audioTrack(t){f(this,Vc,t),a(this,Dr)instanceof aS&&(a(this,Dr).audioTrack=t)}start(t=!1){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter of audio producer ${a(this,Or)}.`),a(this,Ar)&&a(this,zs).clearInterval(a(this,Ar)),f(this,Ar,a(this,zs).setInterval(R(this,xc,cm).bind(this),vN)),a(this,Mr)&&a(this,zs).clearInterval(a(this,Mr)),f(this,Mr,a(this,zs).setInterval(R(this,Uc,lm).bind(this),SN)),t&&(R(this,xc,cm).call(this),R(this,Uc,lm).call(this))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter of audio producer ${a(this,Or)}`),a(this,Ar)&&(a(this,zs).clearInterval(a(this,Ar)),f(this,Ar,void 0)),a(this,Mr)&&(a(this,zs).clearInterval(a(this,Mr)),f(this,Mr,void 0))}catch(t){}a(this,Ya).reset(),a(this,Dr)instanceof nS&&a(this,Dr).stop()}};let Do=Bc;Ar=new WeakMap,Mr=new WeakMap,Or=new WeakMap,Vc=new WeakMap,za=new WeakMap,Ya=new WeakMap,gi=new WeakMap,Pn=new WeakMap,Qa=new WeakMap,kn=new WeakMap,Dr=new WeakMap,zs=new WeakMap,xc=new WeakSet,cm=function(){var i;if(!a(this,Vc)||!a(this,Or))return;const{energy:t}=R(this,Vu,MT).call(this),e=R(i=Bc,$c,dm).call(i,t);let r=.9;a(this,Qa)!==e&&a(this,Qa)?r=.9:e?r=.3:r=.5,f(this,za,(a(this,za)||0)*(1-r)+t*r)},Vu=new WeakSet,MT=function(){var o;const{samples:t}=a(this,Dr),{energy:e,isVoice:r}=a(this,Ya).processAudioChunk(t),i=R(o=Bc,xu,OT).call(o,e);return i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,gi)||i<a(this,gi))&&f(this,gi,i),(!a(this,Pn)||i>a(this,Pn))&&f(this,Pn,i),{energy:(i-a(this,gi))/(a(this,Pn)-a(this,gi))*10||0,isVoice:r})},$c=new WeakSet,dm=function(t){return t<5},Uc=new WeakSet,lm=function(t=a(this,za)){var r;if(!a(this,Or)||!t)return;const e={producerId:a(this,Or),energy:Math.round(t),silent:R(r=Bc,$c,dm).call(r,t)};f(this,Qa,e.silent),this.reportRequest(e)},xu=new WeakSet,OT=function(t){const e=Math.log10(t);return Math.round(e)},m(Do,$c),m(Do,xu);var TN=Object.defineProperty,yN=Object.getOwnPropertyDescriptor,he=(s,t,e,r)=>{for(var i=r>1?void 0:r?yN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&TN(t,e,i),i};class de{constructor(t,e){m(this,Vr);m(this,fi);m(this,jc);m(this,Uu);m(this,Bu);m(this,Fu);m(this,Gc);m(this,Hu);m(this,qu);m(this,lt);m(this,Rn);m(this,Wc);m(this,ju);m(this,Gu);m(this,Wu);p(this,"context");p(this,"authToken");p(this,"e2ee");m(this,Fc,void 0);m(this,Hc,void 0);m(this,nt,void 0);m(this,H,void 0);m(this,$u,void 0);m(this,_t,void 0);m(this,Nr,void 0);m(this,_n,void 0);m(this,Cn,void 0);m(this,qc,void 0);m(this,Qt,null);m(this,Lr,void 0);m(this,Ct,void 0);m(this,Rt,void 0);var i,n;this.context=t;const{socket:r}=e;this.mediaJoined=!1,f(this,nt,r),f(this,Nr,!1),f(this,H,new fN(t,r)),f(this,_t,a(this,H).events),f(this,Lr,new Set),f(this,Ct,new Map),f(this,_n,!1),f(this,Cn,new Pp(t.getValue("logger"))),f(this,Rt,new Do(this.context,a(this,H).socketHandler.audioActivity.bind(a(this,H).socketHandler))),this.e2ee=(n=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,qc,Ih(async()=>{if(!a(this,Vr,xn).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(a(this,Hc),a(this,Fc),!0);o&&(this.context.getValue("peerSessionStore").emit(P.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_RECONNECTED))},5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get mediaJoined(){return a(this,Vr,xn).mediaJoined}set mediaJoined(t){a(this,Vr,xn).mediaJoined=t}reset({resetTransportQueue:t}){this.logger.info(`Resetting media node client: closing all transports, producers, consumers, and queues(resetTransportQueue: ${t}).`),a(this,H).closeAllProducers(),a(this,H).closeAllConsumers(),a(this,Ct).clear(),a(this,Lr).clear(),f(this,Qt,null),t&&a(this,Cn).stop(),a(this,H).stopAllTransports(),a(this,H).reset(),t&&f(this,Cn,new Pp)}async joinRoom(t,e,r=!1,i={}){a(this,Vr,xn).mediaJoinAttempted=!0,f(this,Nr,!0);const n=this.peerId;try{const o=await a(this,Cn).push(()=>R(this,Uu,DT).call(this,t,e,r,i),"joinRoom");return o.roomJoined||R(this,jc,um).call(this,n),o}catch(o){return this.logger.error("Error in room joining process",{error:o}),R(this,jc,um).call(this,n),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_FAILED),{roomJoined:!1,error:o}}}async initializeConnection(t,e,r=!1,i={}){return a(this,Qt)?a(this,Qt):(f(this,Qt,(async()=>{try{await R(this,Gc,hm).call(this,t,e,r,i)}catch(n){throw f(this,Qt,null),n}})()),a(this,Qt))}getConsumers(){return a(this,H).consumers}getProducers(){return a(this,H).producers}handoverPeerProducers(t,e){const r=new Set(e);return Array.from(a(this,H).consumers.values()).filter(i=>r.has(i.producerId)?(i.reassignPeer(t),!0):!1)}async leaveRoom(){var r;(r=a(this,Rt))==null||r.stop(),a(this,H).stopAllTransports(),f(this,_n,!1),a(this,Vr,xn).mediaJoinAttempted=!1;const t={closeRoom:!1};try{a(this,nt).sendMessage(a(this,_t).leaveRoom,ER.toBinary(t))||this.logger.warn("MediaNodeClient.leaveRoom: media leave was not sent")}catch(i){this.logger.error("MediaNodeClient.leaveRoom: media leave failed",{error:i})}this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct().catch(i=>{this.logger.error("leaveRoom::telemetry_destruct_failed",{error:i})})}async activatePeers(t){return this.createConsumers(t)}async createConsumers(t){return t.length===0?Promise.resolve():a(this,H).createConsumers(t)}removeClosedConsumers(t){return a(this,H).removeClosedConsumers(t)}async closeConsumersById(t){t.length&&await a(this,H).closeConsumers(t)}async _shareWebcam(t){var u,h,g,v;const e=_e.WEBCAM,r=R(this,lt,Mt).call(this,e);if(r){const y=await r;if(a(this,H).producers.has(y)){const k=a(this,H).producers.get(y);if(!k.closed)return await k.replaceTrack({track:t}),await this.resumeWebcam(e),t;await this.disableWebcam()}return this._shareWebcam(t)}const i=R(this,Wu,BT).call(this,t),n=So(this.context,"disableSimulcast"),o=(h=(u=this.context)==null?void 0:u.getValue("overrides"))==null?void 0:h.simulcastConfig;n||o&&o.disable||!((v=(g=this.context)==null?void 0:g.getValue("theme"))!=null&&v.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),i.encodings=ZD(this.context,t),this.logger.info(`Simulcast encodings: ${JSON.stringify(i.encodings)}`));const d=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,Ct).delete(e)},l=a(this,H).createProducer(i,d);return R(this,Rn,_d).call(this,e,l.then(y=>y.id)),l.then(y=>y.track)}async shareWebcam(t){return t===void 0?null:this._shareWebcam(t)}async shareScreen(t){const{video:e,audio:r}=t;if(e===void 0)return;const i=await R(this,lt,Mt).call(this,_e.SCREENSHARE_VIDEO),n=await R(this,lt,Mt).call(this,_e.SCREENSHARE_AUDIO),o=a(this,H).producers.get(i),c=a(this,H).producers.get(n),d=[];if(o&&!o.closed)d.push(o.replaceTrack({track:e}));else{const l={track:e,codecOptions:[{mimeType:a(this,fi,ro).screenshareVideo}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Pe.isElectron()},stopTracks:!1},u=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,Ct).delete(_e.SCREENSHARE_VIDEO),a(this,Ct).delete(_e.SCREENSHARE_AUDIO)},h=a(this,H).createProducer(l,u);R(this,Rn,_d).call(this,_e.SCREENSHARE_VIDEO,h.then(g=>g.id)),d.push(h)}if(r)if(c&&!c.closed)d.push(c.replaceTrack({track:r}));else{const l={track:r,codecOptions:[{mimeType:a(this,fi,ro).screenshareAudio}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Pe.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},u=()=>{},h=a(this,H).createProducer(l,u);R(this,Rn,_d).call(this,_e.SCREENSHARE_AUDIO,h.then(g=>g.id)),d.push(h)}else n&&(R(this,Wc,pm).call(this,_e.SCREENSHARE_AUDIO),d.push(a(this,H).closeProducer(n)));await Promise.all(d),this.context.getValue("callstats").screenShareStart()}async shareMic(t){try{if(t===void 0)throw new Nt("track undefined");const e=R(this,lt,Mt).call(this,_e.MIC);if(e){const o=await e;if(a(this,H).producers.has(o)){const c=a(this,H).producers.get(o);if(!c.closed){await c.replaceTrack({track:t}),await this.resumeMic(),a(this,Rt)&&(a(this,Rt).audioTrack=t,a(this,Rt).producerId=o,a(this,Rt).start(!0));return}await a(this,H).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=R(this,Gu,UT).call(this,t),i=()=>{a(this,Ct).delete(_e.MIC)},n=a(this,H).createProducer(r,i);R(this,Rn,_d).call(this,_e.MIC,n.then(o=>o.id)),await n.then(o=>{a(this,Rt)&&(a(this,Rt).audioTrack=o.track,a(this,Rt).producerId=o.id,a(this,Rt).start())})}catch(e){throw new C(e)}}async pauseMic(){var i;const t=await R(this,lt,Mt).call(this,_e.MIC),e=a(this,H).producers.get(t);if(!e){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(e.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}e.pause(),(i=a(this,Rt))==null||i.stop();const r={producerId:e.id,pause:!0};a(this,nt).sendMessage(a(this,_t).toggleProducer,ol.toBinary(r)),this.logger.info(`Paused mic producer ${e.id} of local peer ${this.peerId}. Remote peers will stop hearing this peer.`)}async pauseWebcam(){const t=await R(this,lt,Mt).call(this,_e.WEBCAM),e=a(this,H).producers.get(t);if(!e){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}e.pause();const r={producerId:e.id,pause:!0};a(this,nt).sendMessage(a(this,_t).toggleProducer,ol.toBinary(r)),this.logger.info(`Paused webcam producer ${e.id} of local peer ${this.peerId}. Remote peers will stop seeing this peer.`)}async resumeMic(){const t=await R(this,lt,Mt).call(this,_e.MIC),e=a(this,H).producers.get(t);if(!e){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,nt).sendMessage(a(this,_t).toggleProducer,ol.toBinary(r)),this.logger.info(`Resumed mic producer ${e.id} of local peer ${this.peerId}. Remote peers will start hearing this peer.`)}async resumeWebcam(t=_e.WEBCAM){const e=await R(this,lt,Mt).call(this,t),r=a(this,H).producers.get(e);if(!r){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!r.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}r.resume(),r.appData.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};a(this,nt).sendMessage(a(this,_t).toggleProducer,ol.toBinary(i)),this.logger.info(`Resumed webcam producer ${r.id} of local peer ${this.peerId}. Remote peers will start seeing this peer.`)}async disableWebcam(){const t=_e.WEBCAM,e=await R(this,lt,Mt).call(this,t);R(this,Wc,pm).call(this,t),e&&await a(this,H).closeProducer(e)}async disableMic(){var e;const t=await R(this,lt,Mt).call(this,_e.MIC);t&&await a(this,H).closeProducer(t),(e=a(this,Rt))==null||e.stop(),a(this,Ct).delete(_e.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await R(this,lt,Mt).call(this,_e.SCREENSHARE_VIDEO),e=await R(this,lt,Mt).call(this,_e.SCREENSHARE_AUDIO);t&&await a(this,H).closeProducer(t),e&&await a(this,H).closeProducer(e),a(this,Lr).clear(),a(this,Ct).delete(_e.SCREENSHARE_VIDEO),a(this,Ct).delete(_e.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await R(this,lt,Mt).call(this,_e.WEBCAM);await a(this,H).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await R(this,lt,Mt).call(this,_e.SCREENSHARE_VIDEO);await a(this,H).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:e})}}async changeDisplayName(t,e){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!await a(this,H).socketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}kick(t){const e={peerIds:[t]};a(this,H).socketHandler.kickPeer(e)}kickAll(){a(this,H).socketHandler.kickAll()}async muteAll(t){if(!await a(this,H).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await a(this,H).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await a(this,H).socketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await a(this,H).socketHandler.hostControlForPeer(t,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(t){const e={participantId:t!=null?t:""};try{await a(this,nt).sendMessagePromise(a(this,_t).globalPinPeer,LR.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&a(this,H).producers.get(t.producerId)&&a(this,Lr).add(t.consumerPeerId),a(this,Lr).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));a(this,H).switchConsumersToLayer(r,e)}async handleSocketEvents(){a(this,nt).on(a(this,_t).peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{R(this,ju,$T).call(this,$I.fromBinary(t))}catch(e){this.logger.error("error in peer-producer-create-broadcast",{error:e})}}),a(this,nt).on(a(this,_t).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const e=sv.fromBinary(t),{participantId:r,initiatorParticipantId:i,producerState:{kind:n,pause:o,producerId:c,screenShare:d}}=e;if(d)return;const l=n===Ns.AUDIO?"audio":"video";if(this.logger.info(`Received participant ${l} producer ${o?"paused":"resumed"} broadcast for ${r===this.peerId?"local":"remote"} producer ${c} of peer ${r}. payload: ${sv.toJsonString(e)}`),r===this.peerId&&i!==this.peerId&&o&&(this.logger.info(`${i?`Remote peer ${i}`:"Kick/Kick-all api"} has paused the ${l==="audio"?"audio":"video"} feed of local peer ${this.peerId}. Reconciling the local state.`),this.context.getValue("peerSessionStore").emit(l==="audio"?P.MUTE_SELF:P.MUTE_SELF_VIDEO)),r===this.peerId)return;this.context.getValue("peerSessionStore").emit(P.PRODUCER_TOGGLE,{peerId:r,producerId:c,paused:o,kind:l}),Array.from(this.getConsumers().values()).filter(h=>h.producerId===c).forEach(h=>{h.kind==="video"&&o||h.paused!==o&&(this.logger.debug(`consumer state mismatched for ${h.id}. updating consumer pause state ${h.paused} to ${o}`),o?(h.pause(),this.context.getValue("peerSessionStore").emit(P.CONSUMER_PAUSED,{id:h.id})):(h.resume(),this.context.getValue("peerSessionStore").emit(P.CONSUMER_RESUMED,{id:h.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),a(this,nt).on(a(this,_t).peerLeaveBroadcast,async({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=jh.fromBinary(t);if(e===this.peerId)return;this.logger.info(`Received peer left broadcast of remote peer ${e}`),a(this,Lr).delete(e),this.context.getValue("peerSessionStore").emit(P.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast of remote peer",{error:e})}}),a(this,nt).on(a(this,_t).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=FI.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(P.PRODUCER_CLOSED,{peerId:e,producerId:r})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),a(this,nt).on(a(this,_t).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,Nr)&&!a(this,_n)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_DISCONNECTED),a(this,qc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=a(this,H).consumers.get(r);i&&this.context.getValue("peerSessionStore").emit(P.CONSUMER_SCORE_UPDATE,{id:r,kind:i.kind,peerId:i.peerId,score:e.score,scoreStats:e})})}),this.context.getValue("callstats").onProducerScore(t=>{t.forEach((e,r)=>{const i=Array.from(a(this,H).producers.values()).find(n=>n.id===r);i&&this.context.getValue("peerSessionStore").emit(P.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:e.score,scoreStats:e})})})}}Fc=new WeakMap,Hc=new WeakMap,nt=new WeakMap,H=new WeakMap,$u=new WeakMap,_t=new WeakMap,Nr=new WeakMap,_n=new WeakMap,Cn=new WeakMap,qc=new WeakMap,Qt=new WeakMap,Lr=new WeakMap,Ct=new WeakMap,Rt=new WeakMap,Vr=new WeakSet,xn=function(){return this.context.getValue("connectionHandler")},fi=new WeakSet,ro=function(){var t;return(t=this.context.getValue("mediaProducerCodecs"))!=null?t:sS},jc=new WeakSet,um=function(t){this.mediaJoined=!1,f(this,Nr,!1),a(this,nt).isConnected&&this.peerId===t&&this.context.getValue("peerSessionStore").emit(P.MEDIA_ROOM_JOIN_FAILED)},Uu=new WeakSet,DT=async function(t,e,r,i){var o;f(this,Hc,t);let n=!1;if(r){const{recv:c,send:d}=(o=a(this,Vr,xn).mediaState)!=null?o:{};(d==null?void 0:d.state)===as.CONNECTED&&(c==null?void 0:c.state)===as.CONNECTED?(this.logger.info("MediaNodeClient.joinRoom: transports healthy — preserving all producers for ownership handover"),f(this,Qt,null),n=!0):(this.logger.info("MediaNodeClient.joinRoom: transports unhealthy — full reset"),this.reset({resetTransportQueue:!1}))}try{a(this,Qt)?await a(this,Qt):await R(this,Gc,hm).call(this,t,e,r,i,n),R(this,Fu,LT).call(this,e);const{joined:c,error:d}=await R(this,Bu,NT).call(this);return{roomJoined:c,error:d}}catch(c){return this.logger.error("Failed to complete room join",{error:c}),{roomJoined:!1,error:c}}finally{f(this,Qt,null)}},Bu=new WeakSet,NT=async function(){const t=this.peerId;try{this.mediaJoined=!0;const{roomState:e}=await kl(async(r,i)=>{if(!a(this,nt).isConnected||this.peerId!==t){const n=new Error("Media room join completion superseded by a newer connection");throw i(n),n}return r>0&&this.logger.warn(`Retrying media room join completion for peer ${t}: attempt=${r+1}`),a(this,H).socketHandler.notifySelfJoinComplete()},{strategy:"exponential",maxRetryCount:3,delayTime:1e3});return f(this,Fc,e.roomUuid),f(this,_n,!0),f(this,Nr,!1),{joined:!0}}catch(e){return this.logger.error("Error completing room join",{error:e}),this.mediaJoined=!1,f(this,Nr,!1),{joined:!1,error:e}}},Fu=new WeakSet,LT=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const r={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:{...Pe.getDeviceInfo(),userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency},sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};this.context.getValue("callstats").roomJoined(r)}catch(e){this.logger.error("Error reporting room joined analytics",{error:e})}},0)},Gc=new WeakSet,hm=async function(t,e,r,i,n=!1){try{const o=R(this,Hu,VT).call(this);await R(this,qu,xT).call(this,t,e,r,o),n?this.logger.info("MediaNodeClient: reusing existing transports on rejoin"):await a(this,H).setupTransports({send:!0,recv:!0})}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},Hu=new WeakSet,VT=function(){const t=Q1(a(this,fi,ro));return f(this,$u,t),t},qu=new WeakSet,xT=async function(t,e,r,i){await kl(async(n,o)=>{if(!a(this,nt).isConnected){o(new Error("Socket is not connected"));return}n>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${n}`});try{await a(this,H).socketHandler.joinRoom(e,t,i,r)}catch(c){throw this.logger.error("Failed to send joinRoom message after retries",{error:c}),c}},{delayTime:1e3,strategy:"exponential",maxRetryCount:15})},lt=new WeakSet,Mt=function(t){return a(this,Ct).get(t)},Rn=new WeakSet,_d=function(t,e){return a(this,Ct).set(t,e)},Wc=new WeakSet,pm=function(t){return a(this,Ct).delete(t)},ju=new WeakSet,$T=function({participantId:t,producerState:e}){var i;if(t===this.peerId||!e)return;this.logger.info(`Received remote ${e.screenShare?"screenshare":"participant"} ${e.kind===Ns.AUDIO?"audio":"video"} producer created broadcast for peer ${t} with producer state ${JSON.stringify(e)}.`);const r=(i=e.mimeType)!=null?i:e.kind===Ns.AUDIO?"audio/opus":"video/VP8";this.context.getValue("peerSessionStore").emit(P.NEW_PRODUCER,{peerId:t,producer:{...e,mimeType:r,kind:e.kind===Ns.AUDIO?"audio":"video",producingPeerId:t}})},Gu=new WeakSet,UT=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{mimeType:a(this,fi,ro).audio}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},Wu=new WeakSet,BT=function(t){return{track:t,codecOptions:[{mimeType:a(this,fi,ro).video}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},he([E.trace("MediaNodeClient.reset")],de.prototype,"reset",1),he([E.trace("MediaNodeClient.joinRoom")],de.prototype,"joinRoom",1),he([E.trace("MediaNodeClient.leaveRoom")],de.prototype,"leaveRoom",1),he([E.trace("MediaNodeClient.activatePeers")],de.prototype,"activatePeers",1),he([E.trace("MediaNodeClient.createConsumers")],de.prototype,"createConsumers",1),he([E.trace("MediaNodeClient.closeConsumersById")],de.prototype,"closeConsumersById",1),he([E.trace("MediaNodeClient._shareWebcam")],de.prototype,"_shareWebcam",1),he([E.trace("MediaNodeClient.shareWebcam")],de.prototype,"shareWebcam",1),he([E.trace("MediaNodeClient.shareScreen")],de.prototype,"shareScreen",1),he([E.trace("MediaNodeClient.shareMic")],de.prototype,"shareMic",1),he([E.trace("MediaNodeClient.pauseMic")],de.prototype,"pauseMic",1),he([E.trace("MediaNodeClient.pauseWebcam")],de.prototype,"pauseWebcam",1),he([E.trace("MediaNodeClient.resumeMic")],de.prototype,"resumeMic",1),he([E.trace("MediaNodeClient.resumeWebcam")],de.prototype,"resumeWebcam",1),he([E.trace("MediaNodeClient.disableWebcam")],de.prototype,"disableWebcam",1),he([E.trace("MediaNodeClient.disableMic")],de.prototype,"disableMic",1),he([E.trace("MediaNodeClient.disableScreenShare")],de.prototype,"disableScreenShare",1),he([E.trace("MediaNodeClient.muteSelf")],de.prototype,"muteSelf",1),he([E.trace("MediaNodeClient.resetVideoProducers")],de.prototype,"resetVideoProducers",1),he([E.trace("MediaNodeClient.changeDisplayName")],de.prototype,"changeDisplayName",1),he([E.trace("MediaNodeClient.kickPeer")],de.prototype,"kick",1),he([E.trace("MediaNodeClient.kickAllPeers")],de.prototype,"kickAll",1),he([E.trace("MediaNodeClient.muteAll")],de.prototype,"muteAll",1),he([E.trace("MediaNodeClient.muteAllVideo")],de.prototype,"muteAllVideo",1),he([E.trace("MediaNodeClient.disableAudio")],de.prototype,"disableAudio",1),he([E.trace("MediaNodeClient.disableVideo")],de.prototype,"disableVideo",1),he([E.trace("MediaNodeClient.pinPeer")],de.prototype,"pinPeer",1),he([E.trace("MediaNodeClient.validateScreenShare")],de.prototype,"validateScreenShare",1);function cS(s,t){const e=s.getValue("roomNodeClient");if(e){if(e)return e;throw new Error("Room node client already set up.")}const r=new de(s,t);return s.setValue("roomNodeClient",r),r}function EN(s){const t=s.getValue("roomNodeClient");try{t==null||t.leaveRoom()}catch(e){s.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}s.setValue("roomNodeClient",void 0)}var bN=Object.defineProperty,wN=Object.getOwnPropertyDescriptor,ji=(s,t,e,r)=>{for(var i=r>1?void 0:r?wN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&bN(t,e,i),i};const dS=(ZS=class{constructor(s,t,e,r){m(this,ft);p(this,"self");p(this,"authToken");m(this,Xa,void 0);p(this,"viewType");m(this,gs,void 0);m(this,te,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,f(this,te,s),this.viewType=r,this.authToken=n,f(this,Xa,i),f(this,gs,e),this.setupEvents()}get peerId(){return a(this,te).getValue("peerId")}get telemetry(){return a(this,te).getValue("telemetry")}get logger(){return a(this,te).getValue("logger")}get mediaJoined(){return a(this,te).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const n=Ht(),o=!!s.getValue("cachedUserDetails"),c=await ze.__init__(s,e,r,i,i.name,o);s.setValue("self",c);const d=s.getValue("logger");return navigator.product!=="ReactNative"?setTimeout(async()=>{const u=await c.getAllDevices();d.info("populated_full_device_list",{devices:JSON.stringify(u)}),s.getValue("callstats").devices("AUDIO",u==null?void 0:u.filter(h=>h.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",u==null?void 0:u.filter(h=>h.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",u==null?void 0:u.filter(h=>h.kind==="audiooutput")),d.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:s.getValue("peerId"),engineName:Pe.getDeviceInfo().engineName,env:s.getValue("env")==="prod"?"prod":"devel",iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:{},logger:d,apiHostnames:B_(s),skipConnectivityChecks:!0,authToken:s.getValue("authToken")}),t.socket.updateCallstatsPeerId(s.getValue("peerId")),d.info("Callstats:: initialized")}catch(h){d.error("Callstats:: initialization failed",{error:h})}},0):d.info("Callstats:: Skipped initialization due to navigator product being ReactNative."),new dS(s,c,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:n,screenShareTracks:o}=this.self;if(e.canProduceAudio===G.Allowed&&r)if((s==null?void 0:s.readyState)==="live")try{await a(this,ft,Ut).shareMic(s),this.self.audioEnabled||a(this,ft,Ut).pauseMic()}catch(d){this.self.disableAudio()}else this.logger.warn("shareMediaTracks: audio track is dead, disabling audio"),this.self.disableAudio();if(e.canProduceVideo===G.Allowed&&i)if((t==null?void 0:t.readyState)==="live")try{await a(this,ft,Ut).shareWebcam(t),this.self.videoEnabled||a(this,ft,Ut).pauseWebcam()}catch(d){this.self.disableVideo()}else this.logger.warn("shareMediaTracks: video track is dead, disabling video"),this.self.disableVideo();if(e.canProduceScreenshare===G.Allowed&&n){const d=o.video,l=o.audio;if((d==null?void 0:d.readyState)==="live")try{await((c=a(this,ft,Ut))==null?void 0:c.shareScreen({video:d,audio:(l==null?void 0:l.readyState)==="live"?l:void 0}))}catch(u){this.self.disableScreenShare()}else this.logger.warn("shareMediaTracks: screenshare video track is dead, disabling screenshare"),this.self.disableScreenShare()}}async kickHandler(s){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)}waitlistedHandler(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}async resetSelf(s){var r;const{wasSocketJoinAttempted:t,wasMediaJoinAttempted:e}=s;a(this,te).getValue("callstats").callEnded(),t||e?(this.logger.info(`Resetting Self post reconnect. Peer has earlier tried joining the ${e?"media room":"socket room only"}. Not closing transports.`),await this.joinRoom({reconnected:!0,joinAttempts:s})):(this.logger.info("Resetting Self post reconnect. User never joined the room so doing full reset."),(r=a(this,ft,Ut))==null||r.reset({resetTransportQueue:!0}))}setupEvents(){a(this,te).getValue("peerSessionStore").on(P.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&await this.shareMediaTracks()}),a(this,te).getValue("peerSessionStore").on(P.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,te).getValue("peerSessionStore").on(P.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,te).getValue("peerSessionStore").on(P.ROOM_NODE_FAILED,()=>{this.logger.error("Room node failed. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,te).getValue("peerSessionStore").on(P.SOCKET_SERVICE_RECONNECTED,s=>{!s.wasSocketJoinAttempted&&!s.wasMediaJoinAttempted&&(this.self.roomState="init"),this.resetSelf(s).catch(t=>{this.logger.error("Failed to reset self after socket reconnection",{error:t})})}),a(this,te).getValue("peerSessionStore").on(P.SOCKET_SERVICE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,te).getValue("peerSessionStore").on(P.SOCKET_SERVICE_FAILED,()=>{this.logger.error("Socket reconnection failed after exhausting all attempts. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,gs).on(x.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,gs).on(ml.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,te).getValue("peerSessionStore").emit(P.UPDATE_PERMISSIONS,t.patch)})}),a(this,gs).on(x.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,gs).on(x.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,gs).on(x.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,te).getValue("peerSessionStore").onAsync(P.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,te).getValue("peerSessionStore").on(P.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var n;const i=(n=e==null?void 0:e.screenShare)!=null?n:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),a(this,te).getValue("peerSessionStore").on(P.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,te).getValue("callstats").audioOff())}),a(this,te).getValue("peerSessionStore").on(P.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,te).getValue("callstats").videoOff())}),a(this,te).getValue("peerSessionStore").onAsync(P.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,te).getValue("peerSessionStore").on(P.PIP_HANGUP,this.leaveRoom.bind(this))}async joinSocketRoomWithRetry(){const s=this.self.id;return kl(async(t,e)=>{if(!a(this,Xa).isConnected||this.self.id!==s){const i=new Error("Socket room join superseded by a newer connection");throw e(i),i}t>0&&this.logger.warn(`Retrying socket room join for peer ${s}: attempt=${t+1}`);const r=await a(this,gs).joinRoom(this.self);if(this.self.id!==s){const i=new Error("Socket room join completed for a superseded peer ID");throw e(i),i}return r},{strategy:"exponential",maxRetryCount:3,delayTime:1e3})}async joinRoom({reconnected:s=!1,joinAttempts:t}={}){var e,r;try{this.logger.info("Local peer is joining socket room.");const{peer:i}=await this.joinSocketRoomWithRetry();this.logger.info("Local peer has joined socket room."),a(this,gs).socket.flush();const n=dp(i.stageType);if(a(this,te).setValue("stageStatus",n,!1),i.waitlisted){this.logger.info("Peer was waitlisted. Skipped joining media room."),s&&(this.logger.info("Peer reconnected while waitlisted. Resetting media node client."),(e=a(this,ft,Ut))==null||e.reset({resetTransportQueue:!0})),this.waitlistedHandler();return}}catch(i){throw this.logger.error("SelfController.joinRoom: socket join failed",{error:i}),new C("Check the network and try again.","0002")}if(this.viewType===Ss.Livestream&&(t!=null&&t.wasSocketJoinAttempted)&&!t.wasMediaJoinAttempted&&a(this,te).getValue("stageStatus")!=="ON_STAGE"){this.logger.info("Local livestream peer that only joined the socket room is not ON_STAGE. Closing transports, if any."),(r=a(this,ft,Ut))==null||r.reset({resetTransportQueue:!0}),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s}),a(this,te).notify("stageStatus");return}try{this.logger.info("Local peer is joining media room."),await this.joinMediaRoom(s),this.logger.info("Local peer has joined media room."),a(this,te).notify("stageStatus")}catch(i){throw this.logger.error("SelfController.joinRoom: media room join failed",{error:i}),i instanceof Jr&&i.message==="ice connection failed"?new C("A firewall or network restriction may be blocking the connection.","0014"):new C("Check the network and try again.","0014")}}async leaveRoom(s="left"){var e;if(this.logger.info(`Leaving room with state: ${s}`),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}if(this.self.setIsPinned(!1),a(this,te).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,te).setValue("roomNodeClient",void 0),a(this,te).notify("stageStatus"),a(this,te).getValue("connectionHandler").socketJoined)try{a(this,gs).leaveRoom(this.self)||this.logger.warn("SelfController.leaveRoom: socket leave was not sent")}catch(r){this.logger.error("SelfController.leaveRoom: socket leave failed",{error:r})}(e=a(this,te).getValue("roomSocketHandler"))==null||e.cleanup(),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var n,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=a(this,te).getAllValues();try{if(e===Ss.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}cS(a(this,te),{socket:a(this,Xa),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u,error:h}=(o=await((n=a(this,ft,Ut))==null?void 0:n.joinRoom(this.self.name,r,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)throw h!=null?h:new Error("Could not connect to media server");this.logger.info(i==="ON_STAGE"?"Peer is on stage. Sharing media tracks":"Peer is not on stage. Not sharing media tracks"),i==="ON_STAGE"&&await this.shareMediaTracks(),this.logger.info(i==="ON_STAGE"?"Peer is on stage. Shared media tracks":"Peer is not on stage. Did not share media tracks"),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("SelfController.mediaRoomJoin",{error:c}),c}}async leaveMediaRoom(s){const t=a(this,te).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===Ss.Webinar)&&a(this,ft,Ut)&&(a(this,ft,Ut).mediaJoined&&s!=="disconnected"&&await a(this,ft,Ut).leaveRoom(),!(s==="stageLeft"&&t===Ss.Livestream)&&(a(this,ft,Ut).mediaJoined=!1))}async cleanupSelf(){await this.self.disableAudio(),await this.self.disableVideo(),await this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()}},Xa=new WeakMap,gs=new WeakMap,te=new WeakMap,ft=new WeakSet,Ut=function(){return a(this,te).getValue("roomNodeClient")},ZS);let Kr=dS;ji([E.trace("SelfController.resetSelf")],Kr.prototype,"resetSelf",1),ji([E.trace("SelfController.setupEvents")],Kr.prototype,"setupEvents",1),ji([E.trace("SelfController.joinRoom")],Kr.prototype,"joinRoom",1),ji([E.trace("SelfController.leaveRoom")],Kr.prototype,"leaveRoom",1),ji([E.trace("SelfController.joinMediaRoom")],Kr.prototype,"joinMediaRoom",1),ji([E.trace("SelfController.leaveMediaRoom")],Kr.prototype,"leaveMediaRoom",1),ji([E.trace("SelfController.init")],Kr,"init",1);class PN{constructor(t){m(this,Jc,void 0);f(this,Jc,t)}on(t,e){let r;t===x.roomPeerCount?r=nv.fromBinary.bind(nv):r=Sv.fromBinary.bind(Sv),a(this,Jc).on(t,({payload:i})=>{if(t===x.roomPeerCount&&!i)return;const n=r(i);e(n)})}}Jc=new WeakMap;class kN{constructor(t,e){m(this,Kc,void 0);m(this,zc,void 0);f(this,Kc,e),f(this,zc,t)}get logger(){return a(this,zc).getValue("logger")}on(t,e){let r,i;switch(t){case x.transcript:{r=Gh.fromBinary.bind(Gh),i=Gh.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Kc).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("aiSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}Kc=new WeakMap,zc=new WeakMap;var _N=Object.defineProperty,CN=Object.getOwnPropertyDescriptor,Mp=(s,t,e,r)=>{for(var i=r>1?void 0:r?CN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&_N(t,e,i),i};class Nl{constructor(t,e){m(this,xr,void 0);m(this,Za,void 0);f(this,xr,e),f(this,Za,t)}get logger(){return a(this,Za).getValue("logger")}get telemetry(){return a(this,Za).getValue("telemetry")}getPolls(){return a(this,xr).sendMessagePromise(cr.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,xr).sendMessage(cr.createPoll,yO.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,xr).sendMessage(cr.votePoll,bO.toBinary(r))}on(t,e){let r,i;switch(t){case cr.updatePoll:case cr.createPoll:case cr.votePoll:{r=rp.fromBinary.bind(rp),i=rp.create();break}}a(this,xr).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}removeListeners(t){a(this,xr).removeListeners(t)}}xr=new WeakMap,Za=new WeakMap,Mp([E.trace("PollSocketHandler.getPolls")],Nl.prototype,"getPolls",1),Mp([E.trace("PollSocketHandler.createPoll")],Nl.prototype,"createPoll",1),Mp([E.trace("PollSocketHandler.votePoll")],Nl.prototype,"votePoll",1);var RN=Object.defineProperty,IN=Object.getOwnPropertyDescriptor,AN=(s,t,e,r)=>{for(var i=r>1?void 0:r?IN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&RN(t,e,i),i};class lS{constructor(t,e){p(this,"socket");m(this,Xt,void 0);f(this,Xt,t),this.socket=e,this.handleSocketEvents(),a(this,Xt).setValue("roomSocketHandler",this)}get telemetry(){return a(this,Xt).getValue("telemetry")}get logger(){return a(this,Xt).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}async joinRoom(t){var i;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(i=t.name)!=null?i:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise(x.joinRoom,S0.toBinary(e));try{const{peer:n}=Gn.fromBinary((await r).payload);a(this,Xt).getValue("connectionHandler").socketJoined=!0,a(this,Xt).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_ROOM_JOINED,{peer:n});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=await Promise.all([o,c]);return a(this,Xt).getValue("peerSessionStore").emit(P.ROOM_STATE,d),a(this,Xt).getValue("peerSessionStore").emit(P.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),n}}async getAllAddedParticipants(){try{return iA.fromBinary((await this.socket.sendMessagePromise(x.getAllAddedParticipants)).payload).participants.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}async getRoomPeers(t,e,r){let i;try{const n={seachQuery:t,limit:e,offset:r},o=await this.socket.sendMessagePromise(x.getRoomPeersInfo,c0.toBinary(n));i=Kh.fromBinary(o.payload)}catch(n){this.logger.error("getRoomPeers::binary_decode_error",{error:n})}return i}async getRoomPeersNonPaginated(){let t;try{const e=await this.socket.sendMessagePromise(x.getRoomPeersInfo);t=Kh.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getStagePeers(){let t;try{const e=await this.socket.sendMessagePromise(x.getRoomPeersInfo);t=Kh.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getPeerInfo(t){let e;try{const r=await this.socket.sendMessagePromise(x.getPeerInfo,cv.toBinary({peerId:t}));e=Gn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=ov.create();try{const e=await this.socket.sendMessagePromise(x.getRoomInfo);t=ov.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=pv.create();try{const e=await this.socket.sendMessagePromise(x.getRoomStageState);t=pv.fromBinary(e.payload)}catch(e){this.logger.error("getRoomStageState::binary_decode_error",{error:e})}return t}updateRoomTitle(t){return this.socket.sendMessagePromise(x.updateRoomInfo,ll.toBinary(ll.create({room:{title:t}})))}async broadcastMessage(t,e){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(x.broadcastMessage,Eo.toBinary(r))}async broadcastToMeetings(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(x.broadcastToEntity,Eo.toBinary(i))}async broadcastToPeers(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(x.broadcastToEntity,Eo.toBinary(i))}leaveRoom(t){this.socket.joinAttempted=!1;const e={peer:{peerId:t.peerId,userId:t.userId,displayName:t.name,waitlisted:t.waitlistStatus==="waiting"}};return this.socket.sendMessage(x.leaveRoom,y0.toBinary(e))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(x.kick,uv.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(x.kickAll,Qf.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(x.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(x.acceptWaitingRoomRequests,lA.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(x.denyWaitingRoomRequests,hA.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(ml.updateUserPreset,FA.toBinary(r))}handleSocketEvents(){this.socket.on(x.broadcastMessage,({payload:t})=>{try{const e=Eo.fromBinary(t);a(this,Xt).getValue("peerSessionStore").emit(P.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode broadcast message:",e)}}),this.socket.on(x.broadcastToEntity,({payload:t})=>{try{const e=Eo.fromBinary(t);a(this,Xt).getValue("peerSessionStore").emit(P.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,i;switch(t){case x.joinRoom:case x.leaveRoom:case x.kick:case x.kickAll:{r=Gn.fromBinary.bind(Gn),i=Gn.create();break}case x.getWaitingRoomRequests:{r=(n,o)=>n?hv.fromBinary(n,o):{requests:[]},i=hv.create();break}case x.recordingPaused:case x.recordingStarted:case x.recordingStopped:{r=bv.fromBinary.bind(bv);break}case ml.updateUserPreset:{r=gv.fromBinary.bind(gv);break}case Es.peerJoinedBroadcast:case qr.peerJoinedBroadcast:{r=ev.fromBinary.bind(ev);break}case Es.selfJoinComplete:case qr.selfJoinComplete:{r=qh.fromBinary.bind(qh);break}case Es.globalPeerPinBroadcast:case qr.globalPeerPinBroadcast:{r=rv.fromBinary.bind(rv);break}case Es.selectedPeer:case qr.selectedPeer:{r=Hh.fromBinary.bind(Hh);break}case Es.selectedPeerDiff:case qr.selectedPeerDiff:{r=Zf.fromBinary.bind(Zf);break}case Es.leaveRoom:case qr.leaveRoom:{r=jh.fromBinary.bind(jh);break}case x.updateRoomInfo:{r=ll.fromBinary.bind(ll);break}}this.socket.on(t,({payload:n})=>{let o=i;if(!r)return e(void 0);try{o=r(n)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}async getUserPermissions(t){const e={userIds:[t]};try{const r=await this.socket.sendMessagePromise(ml.getUserPresets,NA.toBinary(e)),i=$A.fromBinary(r.payload).peerPresets[0],n=new TextDecoder().decode(i.preset),o=JSON.parse(n).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(r){throw this.logger.error("Error in getting user preset",{error:r}),r}}}Xt=new WeakMap,AN([E.trace("RoomSocketHandler.joinRoom")],lS.prototype,"joinRoom",1);class MN{constructor(t){m(this,$t,void 0);f(this,$t,t)}async getStageRequests(){const{payload:t}=await a(this,$t).sendMessagePromise(x.getStageRequests);return t?sp.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,$t).sendMessage(x.requestStageAccess)}cancelRequestAccess(){a(this,$t).sendMessage(x.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,$t).sendMessage(x.grantStageAccess,lO.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,$t).sendMessage(x.denyStageAccess,hO.toBinary(e))}joinStage(){return a(this,$t).sendMessagePromise(x.joinStage,void 0,void 0,x.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,$t).sendMessagePromise(x.leaveStage,yv.toBinary(e),void 0,x.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,$t).sendMessagePromise(x.leaveStage,yv.toBinary(e))}on(t,e){let r;switch(t){case x.grantStageAccess:case x.denyStageAccess:{r=void 0;break}case x.getStagePeers:{r=Tv.fromBinary.bind(Tv);break}case x.getStageRequests:case x.requestStageAccess:case x.cancelStageRequest:{r=sp.fromBinary.bind(sp);break}case x.peerStageStatusUpdate:{r=iv.fromBinary.bind(iv);break}}a(this,$t).on(t,({payload:i,id:n})=>{if(!i||!r)return e(void 0,n);const o=r(i);return e(o,n)})}async getPeerInfo(t){const e=await a(this,$t).sendMessagePromise(x.getPeerInfo,cv.toBinary({peerId:t}));return Gn.fromBinary(e.payload)}}$t=new WeakMap;class ON{constructor(t,e){m(this,vi,void 0);m(this,eo,void 0);f(this,vi,e),f(this,eo,t)}get logger(){return a(this,eo).getValue("logger")}get peerId(){return a(this,eo).getValue("peerId")}storeInsertKeys(t,e,r,i){const n={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,vi).sendMessage(or.storeInsertKeys,jM.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,vi).sendMessage(or.storeGetKeys,WM.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,vi).sendMessage(or.storeDeleteKeys,KM.toBinary(n),i)}on(t,e){const r=vv.fromBinary.bind(vv);a(this,vi).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}vi=new WeakMap,eo=new WeakMap;var DN=Object.defineProperty,NN=(s,t,e)=>t in s?DN(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,LN=(s,t,e)=>(NN(s,typeof t!="symbol"?t+"":t,e),e),Op=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},M=(s,t,e)=>(Op(s,t,"read from private field"),e?e.call(s):t.get(s)),pe=(s,t,e)=>{if(t.has(s))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(s):t.set(s,e)},ae=(s,t,e,r)=>(Op(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),oe=(s,t,e)=>(Op(s,t,"access private method"),e),Ll={},VN={get exports(){return Ll},set exports(s){Ll=s}},Xn=typeof Reflect=="object"?Reflect:null,uS=Xn&&typeof Xn.apply=="function"?Xn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},Vl;Xn&&typeof Xn.ownKeys=="function"?Vl=Xn.ownKeys:Object.getOwnPropertySymbols?Vl=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:Vl=function(s){return Object.getOwnPropertyNames(s)};function xN(s){console&&console.warn&&console.warn(s)}var hS=Number.isNaN||function(s){return s!==s};function me(){me.init.call(this)}VN.exports=me,Ll.once=FN,me.EventEmitter=me,me.prototype._events=void 0,me.prototype._eventsCount=0,me.prototype._maxListeners=void 0;var pS=10;function xl(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(me,"defaultMaxListeners",{enumerable:!0,get:function(){return pS},set:function(s){if(typeof s!="number"||s<0||hS(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");pS=s}}),me.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},me.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||hS(s))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+s+".");return this._maxListeners=s,this};function mS(s){return s._maxListeners===void 0?me.defaultMaxListeners:s._maxListeners}me.prototype.getMaxListeners=function(){return mS(this)},me.prototype.emit=function(s){for(var t=[],e=1;e<arguments.length;e++)t.push(arguments[e]);var r=s==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var n;if(t.length>0&&(n=t[0]),n instanceof Error)throw n;var o=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw o.context=n,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")uS(c,this,t);else for(var d=c.length,l=TS(c,d),e=0;e<d;++e)uS(l[e],this,t);return!0};function gS(s,t,e,r){var i,n,o;if(xl(e),n=s._events,n===void 0?(n=s._events=Object.create(null),s._eventsCount=0):(n.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),n=s._events),o=n[t]),o===void 0)o=n[t]=e,++s._eventsCount;else if(typeof o=="function"?o=n[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=mS(s),i>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=s,c.type=t,c.count=o.length,xN(c)}return s}me.prototype.addListener=function(s,t){return gS(this,s,t,!1)},me.prototype.on=me.prototype.addListener,me.prototype.prependListener=function(s,t){return gS(this,s,t,!0)};function $N(){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 fS(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=$N.bind(r);return i.listener=e,r.wrapFn=i,i}me.prototype.once=function(s,t){return xl(t),this.on(s,fS(this,s,t)),this},me.prototype.prependOnceListener=function(s,t){return xl(t),this.prependListener(s,fS(this,s,t)),this},me.prototype.removeListener=function(s,t){var e,r,i,n,o;if(xl(t),r=this._events,r===void 0)return this;if(e=r[s],e===void 0)return this;if(e===t||e.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[s],r.removeListener&&this.emit("removeListener",s,e.listener||t));else if(typeof e!="function"){for(i=-1,n=e.length-1;n>=0;n--)if(e[n]===t||e[n].listener===t){o=e[n].listener,i=n;break}if(i<0)return this;i===0?e.shift():UN(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this},me.prototype.off=me.prototype.removeListener,me.prototype.removeAllListeners=function(s){var t,e,r;if(e=this._events,e===void 0)return this;if(e.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):e[s]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete e[s]),this;if(arguments.length===0){var i=Object.keys(e),n;for(r=0;r<i.length;++r)n=i[r],n!=="removeListener"&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=e[s],typeof t=="function")this.removeListener(s,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(s,t[r]);return this};function vS(s,t,e){var r=s._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?BN(i):TS(i,i.length)}me.prototype.listeners=function(s){return vS(this,s,!0)},me.prototype.rawListeners=function(s){return vS(this,s,!1)},me.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):SS.call(s,t)},me.prototype.listenerCount=SS;function SS(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}me.prototype.eventNames=function(){return this._eventsCount>0?Vl(this._events):[]};function TS(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function UN(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function BN(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function FN(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,n),r(o)}function n(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}yS(s,t,n,{once:!0}),t!=="error"&&HN(s,i,{once:!0})})}function HN(s,t,e){typeof s.on=="function"&&yS(s,"error",t,e)}function yS(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(n){r.once&&s.removeEventListener(t,i),e(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class qN extends T{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 ES=new qN;class bS{static encode(t){return ES.toBinary(t)}static decode(t){return ES.fromBinary(new Uint8Array(t))}}function jN(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var zr;class GN{constructor(t={}){LN(this,"opts"),pe(this,zr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ae(this,zr,0)}async wait(){ae(this,zr,M(this,zr)+1);const t=jN(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**M(this,zr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return M(this,zr)}reset(){ae(this,zr,0)}}zr=new WeakMap;const Yr={debug:0,info:1,warn:2,error:3};var Gi,Wi;class WN{constructor(t){pe(this,Gi,void 0),pe(this,Wi,void 0),ae(this,Gi,console),ae(this,Wi,t)}debug(...t){Yr[M(this,Wi)]>Yr.debug||M(this,Gi).debug("[Sockrates]:",...t)}info(...t){Yr[M(this,Wi)]>Yr.info||M(this,Gi).info("[Sockrates]:",...t)}warn(...t){Yr[M(this,Wi)]>Yr.warn||M(this,Gi).warn("[Sockrates]:",...t)}error(...t){Yr[M(this,Wi)]>Yr.error||M(this,Gi).error("[Sockrates]:",...t)}}Gi=new WeakMap,Wi=new WeakMap;var wS=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(wS||{});const PS="2",kS="3";var Ne,Zn,ge,Oe,Qr,Ye,mr,Xr,ws,ea,ta,gr,Dp,_S,No,$l,Np,CS,Ul,Lp,Bl,Vp,xp,RS,Lo,Fl,sa,Vo,Hl,$p,ra,xo,Up,IS,$o,ql,Uo,jl;class JN{constructor(t,e){var y,k,I,D,N,B,U,j,Z,re,F,ee;pe(this,Dp),pe(this,No),pe(this,Np),pe(this,Ul),pe(this,Bl),pe(this,xp),pe(this,Lo),pe(this,sa),pe(this,Hl),pe(this,ra),pe(this,Up),pe(this,$o),pe(this,Uo),pe(this,Ne,void 0),pe(this,Zn,void 0),pe(this,ge,void 0),pe(this,Oe,void 0),pe(this,Qr,void 0),pe(this,Ye,void 0),pe(this,mr,void 0),pe(this,Xr,void 0),pe(this,ws,void 0),pe(this,ea,void 0),pe(this,ta,void 0),pe(this,gr,void 0);var r,i,n,o,c,d,l,u,h,g,v;ae(this,Zn,t),ae(this,Qr,[]),ae(this,Ye,new Ll),ae(this,mr,!0),ae(this,ws,!1),ae(this,ge,e!=null?e:{}),(y=(r=M(this,ge)).autoReconnect)!=null||(r.autoReconnect=!0),(k=(i=M(this,ge)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(I=(n=M(this,ge)).pingTimeout)!=null||(n.pingTimeout=3e4),(D=(o=M(this,ge)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(N=(c=M(this,ge)).debug)!=null||(c.debug=!0),(B=(d=M(this,ge)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(U=(l=M(this,ge)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(j=(u=M(this,ge)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(Z=(h=M(this,ge)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),(re=(g=M(this,ge)).clientInitiatedPings)!=null||(g.clientInitiatedPings=!1),(F=(v=M(this,ge)).clientInitiatedPingInterval)!=null||(v.clientInitiatedPingInterval=3e4),ae(this,Xr,{code:void 0,reason:void 0}),ae(this,Oe,(ee=M(this,ge).logger)!=null?ee:new WN(M(this,ge).debug?"debug":"info")),ae(this,gr,new GN)}get readyState(){var t;return(t=M(this,Ne))==null?void 0:t.readyState}get url(){return M(this,Zn)}updateURL(t){ae(this,Zn,t),oe(this,xp,RS).call(this)}get config(){return M(this,ge)}get sendQueue(){return M(this,Qr)}flush(){if(!M(this,ge).queueOnDisconnect)return!1;const t=[];return M(this,Qr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ae(this,Qr,t),M(this,Qr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){M(this,Oe).debug("Websocket was already connecting or connected.");return}if(M(this,mr)!==!1)return new Promise((e,r)=>{oe(this,ra,xo).call(this),oe(this,Uo,jl).call(this);try{ae(this,Ne,new WebSocket(oe(this,Dp,_S).call(this,M(this,Zn)))),M(this,Ne).binaryType="arraybuffer",M(this,Oe).debug("Connecting");const i=setTimeout(()=>{M(this,Oe).debug("Connection timeout. Closing socket"),ae(this,mr,!0),oe(this,Uo,jl).call(this),M(this,Ne).close(3001,"Connection Timeout"),M(this,ge).autoReconnect&&!M(this,ws)&&(M(this,Ye).emit("reconnecting"),oe(this,Lo,Fl).call(this)),r(new Error("Connection timed out!"))},M(this,ge).connectionTimeout);M(this,Ne).onopen=()=>{M(this,Oe).debug(`Ready State: ${wS[M(this,Ne).readyState]}`),i&&clearTimeout(i),oe(this,Hl,$p).call(this),oe(this,Up,IS).call(this),ae(this,Xr,{code:void 0,reason:void 0}),M(this,Ye).emit("connected"),M(this,ge).flushOnReconnect&&this.flush(),e()},M(this,Ne).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),M(this,Oe).debug("Socket closed. Close event:",{event:n}),M(this,Oe).debug(`Connection closed code: ${o}`),M(this,Oe).debug(`Connection closed reason: ${c}`),M(this,ws)||oe(this,Bl,Vp).call(this,o,c)}catch(o){oe(this,No,$l).call(this,o)}},M(this,Ne).onerror=n=>{oe(this,No,$l).call(this,n)},M(this,Ne).onmessage=n=>oe(this,Np,CS).call(this,n)}catch(i){oe(this,No,$l).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(M(this,ge).queueOnDisconnect&&(!M(this,Ne)||M(this,Ne).readyState!==1))return M(this,Oe).debug("Queuing message since socket is not connected!",n),M(this,Qr).push(n),!1;const o=bS.encode(n);return oe(this,sa,Vo).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return oe(this,sa,Vo).call(this,t)}receive(t,e){return M(this,Ye).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){M(this,Ye).on(t,e);return}this.receive(t,e)}removeAllListeners(){M(this,Ye).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){M(this,Ye).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){M(this,Ye).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ae(this,mr,!1),oe(this,ra,xo).call(this),oe(this,$o,ql).call(this),this.removeAllListeners(),ae(this,Xr,{code:1e3,reason:"Sockrates disconnect method called"}),M(this,Ne).close(1e3,"Sockrates disconnect method called.")}}Ne=new WeakMap,Zn=new WeakMap,ge=new WeakMap,Oe=new WeakMap,Qr=new WeakMap,Ye=new WeakMap,mr=new WeakMap,Xr=new WeakMap,ws=new WeakMap,ea=new WeakMap,ta=new WeakMap,gr=new WeakMap,Dp=new WeakSet,_S=function(s){if(s.startsWith("ws://")||s.startsWith("wss://"))return s;if(s.startsWith("https://"))return`wss://${s.substring(8)}`;if(s.startsWith("http://"))return`ws://${s.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},No=new WeakSet,$l=function(s,t){M(this,Oe).error("Error:",{error:s}),M(this,Ye).emit("errored",{error:s}),t==null||t(s)},Np=new WeakSet,CS=function(s){if(oe(this,Hl,$p).call(this),s.data===PS){M(this,Oe).debug("Received ping from server"),oe(this,sa,Vo).call(this,kS);return}if(s.data===kS){M(this,Oe).debug("Received pong from server");return}const t=bS.decode(s.data),{id:e,payload:r}=t;M(this,Oe).debug("Received message",{event:t.event,messageID:e}),M(this,Ye).emit(t.event.toString(),{id:e,payload:r})},Ul=new WeakSet,Lp=function(){return M(this,Ne).readyState===1},Bl=new WeakSet,Vp=function(s,t){ae(this,Xr,{reason:t,code:s}),M(this,Ye).emit("disconnected",{code:s,reason:t})},xp=new WeakSet,RS=function(){const{reason:s,code:t}=M(this,Xr);t&&t!==1e3&&M(this,mr)&&M(this,ge).autoReconnect&&!M(this,ws)&&(M(this,Oe).debug(`Triggering reconnection due to ${s}.`),M(this,Ye).emit("reconnecting"),oe(this,Lo,Fl).call(this))},Lo=new WeakSet,Fl=async function(s=!0){if(s&&M(this,ws)){M(this,Oe).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(M(this,ws)||M(this,gr).reset(),M(this,ge).maxReconnectionAttempts!==null&&M(this,gr).getAttempts()>=M(this,ge).maxReconnectionAttempts){M(this,Ye).emit("failed"),ae(this,ws,!1);return}ae(this,ws,!0),oe(this,Uo,jl).call(this),oe(this,ra,xo).call(this);try{if(await M(this,gr).wait(),M(this,mr)===!1)return;if(M(this,Oe).debug(`Reconnection attempt ${M(this,gr).getAttempts()}`),M(this,Ye).emit("reconnectAttempt",{attempt:M(this,gr).getAttempts()}),await this.connect(),!oe(this,Ul,Lp).call(this))throw Error("Reconnect Failed");ae(this,ws,!1),ae(this,Xr,{code:void 0,reason:void 0}),M(this,Ye).emit("reconnected")}catch(t){M(this,Oe).debug("Failed to reconnect."),M(this,Ye).emit("reconnectFailure",{attempt:M(this,gr).getAttempts()}),oe(this,Lo,Fl).call(this,!1)}},sa=new WeakSet,Vo=function(s){try{return M(this,Ne).send(s),!0}catch(t){return M(this,Oe).error(t.message),!1}},Hl=new WeakSet,$p=function(){this.config.disconnectOnPingTimeout&&(M(this,Oe).debug("Resetting ping timeout"),oe(this,ra,xo).call(this),ae(this,ea,setTimeout(()=>{var s;M(this,Oe).debug("Disconnecting the socket due to ping timeout"),ae(this,mr,!0);const t=3002,e="Ping timeout";(s=M(this,Ne))==null||s.close(t,e),oe(this,Bl,Vp).call(this,t,e)},M(this,ge).pingTimeout)))},ra=new WeakSet,xo=function(){M(this,ea)&&(clearTimeout(M(this,ea)),ae(this,ea,void 0))},Up=new WeakSet,IS=function(){oe(this,$o,ql).call(this),M(this,ge).clientInitiatedPings&&ae(this,ta,setInterval(()=>{oe(this,Ul,Lp).call(this)&&(M(this,Oe).debug("Sending client-initiated ping"),oe(this,sa,Vo).call(this,PS))},M(this,ge).clientInitiatedPingInterval))},$o=new WeakSet,ql=function(){M(this,ta)&&(clearInterval(M(this,ta)),ae(this,ta,void 0))},Uo=new WeakSet,jl=function(){oe(this,$o,ql).call(this),M(this,Ne)&&(M(this,Ne).onopen=void 0,M(this,Ne).onerror=void 0,M(this,Ne).onmessage=void 0,M(this,Ne).onclose=void 0)};function AS(s){return`${s.slice(0,10)}...${s.slice(-10)}`}function KN(s,t){s.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c — not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://developers.cloudflare.com/api/resources/realtime_kit/subresources/meetings/methods/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:e,orgId:r,participantId:i}=JSON.parse(atob(s.split(".")[1]));if(!e)throw Error(`Received V1 auth token ${s}`);let n=Di.baseURI.prod;t&&(n=t);const o=`https://${vf({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new C("Invalid auth token","0004")}}var zN=Object.defineProperty,YN=Object.getOwnPropertyDescriptor,Gl=(s,t,e,r)=>{for(var i=r>1?void 0:r?YN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&zN(t,e,i),i};const MS=65535,QN=3,XN=15e3,ZN=8e3,eL=50,tL=1e3,sL=1e4,OS=(qp=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){m(this,ut);m(this,Yc);m(this,Ju);m(this,Ku);m(this,zu);m(this,Qc);m(this,Xc);m(this,On);m(this,Qu);m(this,Zc);m(this,ed);m(this,td);m(this,Xu);m(this,sd);m(this,rd);m(this,Ys,void 0);m(this,to,void 0);m(this,Ie,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");m(this,Si,[]);m(this,Ti,void 0);m(this,In,!1);m(this,An,void 0);m(this,yi,void 0);m(this,Qs,void 0);m(this,Xs,void 0);m(this,Ei,void 0);m(this,Mn,void 0);m(this,It,0);m(this,bi,void 0);m(this,At,!0);m(this,We,void 0);if(!t||!e||!r)throw new C("peerId, meetingId, or authToken can not be empty","0404");f(this,We,s),f(this,Xs,navigator.isReactNative?oS:mp),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,Ys,R(this,Yc,mm).call(this,t)),f(this,to,t);const n=i.includes("PING");f(this,Ie,new JN(a(this,Ys),{autoReconnect:!1,disconnectOnPingTimeout:n,queueOnDisconnect:!1,flushOnReconnect:!1,logger:this.logger,clientInitiatedPings:!n,clientInitiatedPingInterval:15e3})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,ut,Ot).socketJoinAttempted}set joinAttempted(s){a(this,ut,Ot).socketJoinAttempted=s}get telemetry(){return a(this,We).getValue("telemetry")}get logger(){return a(this,We).getValue("logger")}get peerId(){return a(this,We).getValue("peerId")}get supersededLocalPeerIds(){return a(this,Si).filter(s=>s!==this.peerId)}updateCallstatsPeerId(s){const t=a(this,We).getValue("callstats");t.peerId=s,t.backend&&(t.backend.peerId=s,t.backend.eventHandler&&Object.assign(t.backend.eventHandler,{peerId:s}))}updateURL(s){var t;f(this,Ys,R(this,Yc,mm).call(this,s)),f(this,to,s),a(this,We).getValue("telemetry").resetPeerId(s),(t=a(this,We).getValue("apiClient"))==null||t.setHeader("tracing-id",s),this.updateCallstatsPeerId(s),Br.remapContext(s,a(this,We)),this.logger.info(`Attempting websocket connection with URL: ${a(this,On,Cd)}`),a(this,Ie).updateURL(a(this,Ys))}get url(){return a(this,Ys)}async connect(){var t;const s=a(this,It)+1;f(this,It,s),R(this,Zc,vm).call(this),f(this,At,!0),R(this,zu,qT).call(this);try{if(await a(this,Ie).connect(),!a(this,At)||s!==a(this,It))throw new Error("Socket connection was canceled");R(this,Xc,fm).call(this,this.peerId),(t=a(this,Qs))!=null||f(this,Qs,this.peerId),a(this,ut,Ot).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}catch(e){throw this.logger.error(`Websocket connection failed with URL: ${a(this,On,Cd)}`,{error:e}),a(this,At)&&s===a(this,It)&&R(this,td,Tm).call(this,s),e}}disconnect(){f(this,It,a(this,It)+1),f(this,At,!1),R(this,Zc,vm).call(this),R(this,Qc,gm).call(this),f(this,Qs,void 0),a(this,Ie).disconnect(),a(this,ut,Ot).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Ie).readyState===1}catch(s){return!1}}sendMessage(s,t,e){if(!a(this,sd,ym))return!1;const r={};return a(this,We).getValue("telemetry").injectContext(r),a(this,Ie).send(s,e!=null?e:R(this,rd,Em).call(this),t,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(s,t,e,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:s,timeout:i,protobuf:t,messageId:e,resp:r})}sendMessagePromiseWithTimeout({event:s,timeout:t,protobuf:e,messageId:r,resp:i}){if(!a(this,sd,ym))return Promise.reject(new Error("Socket is not connected for the current peer ID"));const n=i!=null?i:s;return new Promise((o,c)=>{let d;const l=(I,D)=>{d&&clearTimeout(d),a(this,Ie).removeListener(n,I),a(this,Ie).removeListener(MS,D),a(this,Ie).removeListener(qr.errorResponse,D),a(this,Ie).removeListener(Es.errorResponse,D)},u=r!=null?r:R(this,rd,Em).call(this),h={};a(this,We).getValue("telemetry").injectContext(h);const v=({id:I,payload:D})=>{if(u===I){let N;try{const B=ZR.fromBinary(D);N=new Error(B.errorMessage)}catch(B){N=new Error("failed to parse error message",{cause:B});try{const U=t0.fromBinary(D);N=new Error(U.message)}catch(U){N=new Error("failed to parse error message",{cause:U})}}c(N),l(y,v)}},y=({id:I,payload:D})=>{u===I&&(o({id:I,payload:D}),l(y,v))};a(this,Ie).on(n,y),a(this,Ie).on(MS,v),a(this,Ie).on(qr.errorResponse,v),a(this,Ie).on(Es.errorResponse,v),d=setTimeout(()=>{l(y,v),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Ie).send(s,u,e,new TextEncoder().encode(JSON.stringify(h)))||(l(y,v),c(new Error("Socket message could not be sent for the current peer ID")))})}on(s,t){a(this,Ie).on(s,t)}onStateEvent(s,t){a(this,Ie).on(s,t)}removeListener(s,t){a(this,Ie).removeListener(s,t)}removeListeners(s){a(this,Ie).removeListeners(s)}flush(){return a(this,Ie).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{var s;this.logger.info(`Websocket connected with URL: ${a(this,On,Cd)}`),(s=a(this,Qs))!=null||f(this,Qs,this.peerId),a(this,ut,Ot).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{!a(this,At)||a(this,bi)===a(this,It)||(this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t}}),a(this,ut,Ot).updateSocketConnectionState("disconnected"),a(this,We).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,ut,Ot).joinAttempted}),R(this,td,Tm).call(this,a(this,It)))})}},Ys=new WeakMap,to=new WeakMap,Ie=new WeakMap,ut=new WeakSet,Ot=function(){return a(this,We).getValue("connectionHandler")},Si=new WeakMap,Ti=new WeakMap,In=new WeakMap,An=new WeakMap,yi=new WeakMap,Qs=new WeakMap,Xs=new WeakMap,Ei=new WeakMap,Mn=new WeakMap,It=new WeakMap,bi=new WeakMap,At=new WeakMap,We=new WeakMap,Yc=new WeakSet,mm=function(s){let t=Oh({servicePrefix:"ws",baseURI:a(this,We).getValue("baseURI")});const e=So(a(this,We),"socket_server_base");if(typeof e=="string"){const n=/^(http|ws):\/\//i.test(e),o=e.replace(/^(https?|wss?):\/\//i,"").replace(/\/+$/,"");t=`${n?"ws":"wss"}://${o}/ws`}const r=new URL(t),i={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...a(this,Si).length>0&&{oldPeerIds:a(this,Si).join(",")},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(n=>cl[n]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0,apiVersion:"23-09-2026"};return Object.entries(i).forEach(([n,o])=>{r.searchParams.append(n,o.toString())}),r.href},Ju=new WeakSet,FT=function(){if(!a(this,Qs))return;const s=new URL(a(this,Ys));return s.protocol=s.protocol==="ws:"?"http:":"https:",s.pathname=`${s.pathname.replace(/\/+$/,"")}/ping`,s.search="",s.searchParams.set("peerId",a(this,Qs)),s.href},Ku=new WeakSet,HT=async function(){const s=R(this,Ju,FT).call(this);if(!s||a(this,In))return;const t={},e=typeof AbortController=="function"?new AbortController:void 0;let r;f(this,In,!0),f(this,yi,t),f(this,An,e);try{e&&(r=a(this,Xs).setTimeout(()=>e.abort(),ZN));const i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${this.authToken}`},...e&&{signal:e.signal}});i.ok||this.logger.warn("SocketService::API ping request failed",{networkCall:{status:i.status,url:s}})}catch(i){a(this,yi)===t&&this.logger.warn("SocketService::API ping request failed",{error:i,networkCall:{url:s}})}finally{r!==void 0&&a(this,Xs).clearTimeout(r),a(this,yi)===t&&(f(this,In,!1),f(this,yi,void 0),f(this,An,void 0))}},zu=new WeakSet,qT=function(){a(this,Ti)===void 0&&f(this,Ti,a(this,Xs).setInterval(()=>R(this,Ku,HT).call(this),XN))},Qc=new WeakSet,gm=function(){var s;a(this,Ti)!==void 0&&a(this,Xs).clearInterval(a(this,Ti)),(s=a(this,An))==null||s.abort(),f(this,Ti,void 0),f(this,In,!1),f(this,yi,void 0),f(this,An,void 0)},Xc=new WeakSet,fm=function(s){f(this,Si,[s,...a(this,Si).filter(t=>t!==s)].slice(0,QN))},On=new WeakSet,Cd=function(){const s=new URL(a(this,Ys)),t=s.searchParams.get("authToken");return t&&s.searchParams.set("authToken",AS(t)),s.href},Yu=new WeakSet,jT=function(s){const t=Math.min(sL,tL*2**(s-1));return Math.floor(Math.random()*(t+1))},Qu=new WeakSet,GT=function(s){return new Promise(t=>{var e;f(this,Mn,t),f(this,Ei,a(this,Xs).setTimeout(()=>{f(this,Ei,void 0),f(this,Mn,void 0),t()},R(e=OS,Yu,jT).call(e,s)))})},Zc=new WeakSet,vm=function(){var s;a(this,Ei)!==void 0&&(a(this,Xs).clearTimeout(a(this,Ei)),f(this,Ei,void 0)),(s=a(this,Mn))==null||s.call(this),f(this,Mn,void 0)},ed=new WeakSet,Sm=function(s,t){!a(this,At)||s!==a(this,It)||(t&&this.logger.error("SocketService::Reconnect loop failed",{error:t}),f(this,At,!1),R(this,Qc,gm).call(this),f(this,Qs,void 0),a(this,ut,Ot).updateSocketConnectionState("failed"),a(this,We).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_FAILED))},td=new WeakSet,Tm=function(s){!a(this,At)||a(this,bi)===s||(f(this,bi,s),a(this,ut,Ot).updateSocketConnectionState("reconnecting"),R(this,Xu,WT).call(this,s).catch(t=>R(this,ed,Sm).call(this,s,t)))},Xu=new WeakSet,WT=async function(s){try{for(let t=1;t<=eL;t+=1){if(!a(this,At)||s!==a(this,It)||(await R(this,Qu,GT).call(this,t),!a(this,At)||s!==a(this,It)))return;this.updateURL(Ci()),this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:t}}),a(this,ut,Ot).updateSocketConnectionState("reconnectAttempt",t);try{if(await a(this,Ie).connect(!0),!a(this,At)||s!==a(this,It))return;if(!this.isConnected)throw new Error("Reconnect failed");R(this,Xc,fm).call(this,this.peerId),f(this,Qs,this.peerId),a(this,ut,Ot).updateSocketConnectionState("reconnected"),a(this,We).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_RECONNECTED,{wasSocketJoinAttempted:a(this,ut,Ot).socketJoinAttempted,wasMediaJoinAttempted:a(this,ut,Ot).mediaJoinAttempted});return}catch(e){if(!a(this,At)||s!==a(this,It))return;this.logger.error(`Websocket connection retry attempt ${t} failed with URL: ${a(this,On,Cd)}`,{error:e,socket:{retryAttempt:t}}),a(this,ut,Ot).updateSocketConnectionState("reconnectFailure",t)}}R(this,ed,Sm).call(this,s)}finally{a(this,bi)===s&&f(this,bi,void 0)}},sd=new WeakSet,ym=function(){return this.isConnected&&a(this,to)===this.peerId},rd=new WeakSet,Em=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},m(qp,Yu),qp);let Bo=OS;Gl([E.trace("SocketService.connect")],Bo.prototype,"connect",1),Gl([E.trace("SocketService.disconnect")],Bo.prototype,"disconnect",1),Gl([E.trace("SocketService.sendMessagePromise")],Bo.prototype,"sendMessagePromise",1),Gl([E.trace("SocketService.sendMessagePromiseWithTimeout")],Bo.prototype,"sendMessagePromiseWithTimeout",1);class rL{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=R0.fromBinary(t),r=e.meetings.map(o=>{var c;return{id:o.id,title:o.title,participants:(c=o.participants)!=null?c:[]}});return{parentMeeting:{id:e.parentMeeting.id,title:e.parentMeeting.title,participants:(n=e.parentMeeting.participants)!=null?n:[]},meetings:r}}handleTransferPeerRaw({payload:t}){const e=sA.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=lv.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return V0.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title,error:r.error}))}handleConnectedRoomsDeletedRaw({payload:t}){return W0.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(x.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const e=await this.socketService.sendMessagePromise(x.createConnectedRooms,O0.toBinary({payloads:t}));return this.handleConnectedRoomsUpdatedRaw(e)}async updateConnectedRooms(t){const e=await this.socketService.sendMessagePromise(x.updateConnectedRooms,B0.toBinary({payloads:t}));return this.handleConnectedRoomsUpdatedRaw(e)}async disableConnectedRooms(t){const e=t.map(i=>({id:i})),r=await this.socketService.sendMessagePromise(x.deleteConnectedRooms,j0.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(x.movePeers,X0.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}}}}var iL=Object.defineProperty,nL=Object.getOwnPropertyDescriptor,aL=(s,t,e,r)=>{for(var i=r>1?void 0:r?nL(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&iL(t,e,i),i};class DS extends Bt{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);m(this,Zt,void 0);f(this,Zt,e)}get isActive(){return this.meetings.length!==0}validateAlterAction(){const e=a(this,Zt).getValue("self").permissions.connectedMeetings;if(!(e!=null&&e.canAlterConnectedMeetings))throw new Error("You are not allowed to perform this action. Please enable canAlterConnectedMeetings permission in your preset.")}validateMoveAction(e,r){var d;if(!(r!=null&&r.length))throw new Error("You're trying to move participants with an empty list.");const i=a(this,Zt).getValue("self").permissions.connectedMeetings;if(!i)throw new Error("You are not allowed to perform this action. Please enable connected meetings permissions in your preset.");if(i.canAlterConnectedMeetings)return;const n=a(this,Zt).getValue("userId");if(!(r.length===1&&r[0]===n))throw new Error("You are not allowed to move other participants. Please enable canAlterConnectedMeetings permission in your preset.");if(e===((d=this.parentMeeting)==null?void 0:d.id)){if(!i.canSwitchToParentMeeting)throw new Error("You are not allowed to move to the parent meeting. Please enable canSwitchToParentMeeting permission in your preset.");return}if(!i.canSwitchConnectedMeetings)throw new Error("You are not allowed to move to a connected meeting. Please enable canSwitchConnectedMeetings permission in your preset.")}async getConnectedMeetings(){this.logger.info("Getting connected meetings dump");const e=await a(this,Zt).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateAlterAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await a(this,Zt).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e);return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`),r.map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateAlterAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`);const r=await a(this,Zt).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(o=>({meetingId:o.id,title:o.title})));this.logger.info(`Updated connected meetings ${JSON.stringify(r)}`);const i=new Set(r.filter(o=>!o.error).map(o=>o.id)),n=[...new Set(e.map(o=>o.id))].filter(o=>!i.has(o));if(n.length>0)throw new Error(`Could not update connected meetings: ${n.join(", ")}`)}async deleteMeetings(e){this.validateAlterAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.participants.map(o=>o.id)):Promise.resolve());this.logger.info(`Moved participants before deleting connected meetings ${JSON.stringify(e)}. Deleting now.`),await Promise.all(r);const i=await a(this,Zt).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateMoveAction(r,i),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,Zt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return n.success?(this.logger.info(`Moved connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i)):this.logger.error(`Failed to move connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),n}async moveParticipantsWithCustomPreset(e,r,i){this.validateMoveAction(r,i.map(o=>o.id)),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,Zt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return n.success?(this.logger.info(`Moved connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i.map(o=>o.id))):this.logger.error(`Failed to move connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),n}moveSuccessHandler(e,r,i){const n=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>n.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>n.get(o)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(o=>!i.includes(o.id))),this.meetings=this.meetings.map(o=>{if(r===o.id){const c=o.participants.concat(i.map(d=>n.get(d)));return{...o,participants:c}}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return{...o,participants:c}}return o})}}Zt=new WeakMap,aL([qt({maxInvocations:60,period:60})],DS.prototype,"getConnectedMeetings",1);var oL=Object.defineProperty,cL=Object.getOwnPropertyDescriptor,Bp=(s,t,e,r)=>{for(var i=r>1?void 0:r?cL(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&oL(t,e,i),i};const NS=(eT=class{constructor(s){p(this,"connectedMeetings");m(this,Se,void 0);f(this,Se,s),this.connectedMeetings=new DS(s)}get telemetry(){return a(this,Se).getValue("telemetry")}get logger(){return a(this,Se).getValue("logger")}static init(s){const t=new NS(s);return s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings()),t.setupEvents(),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(x.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(x.transferPeer,this.handleTransferPeer.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(x.movedPeer,this.handleMovedPeer.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(x.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(x.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.logger.info(`Honoring request to switch connected meetings. Going to ${t==null?void 0:t.meetingId}`),this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){var i,n,o,c;this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:a(this,Se).getValue("self").videoEnabled,audio:a(this,Se).getValue("self").audioEnabled};try{a(this,Se).getValue("self").cleanupEvents(),await a(this,Se).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,Se).getValue("meeting"))==null?void 0:i.meta)==null?void 0:n.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await VS.init({...a(this,Se).getValue("options"),cachedUserDetails:null,defaults:{...a(this,Se).getValue("options").defaults,...e,mediaHandler:a(this,Se).getValue("self")},authToken:s});this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(o=r==null?void 0:r.meta)==null?void 0:o.meetingId}`);try{const{hidden:d}=a(this,Se).getValue("self");r.self.setName(a(this,Se).getValue("self").name),await r.join(),d&&r.self.hide()}catch(d){this.logger.error("ConnectedMeetingsController.joinRoom",{error:d})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(c=r==null?void 0:r.meta)==null?void 0:c.meetingId}`),this.connectedMeetings.emit("meetingChanged",r),r}handleConnectedRoomsDump(s){const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(s);this.connectedMeetings.meetings=t.meetings.map(e=>({id:e.id,title:e.title,participants:e.participants||[]})),this.connectedMeetings.parentMeeting={id:t.parentMeeting.id,title:t.parentMeeting.title,participants:t.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(s){return a(this,Se).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){var n;const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(s).filter(o=>!o.error),e=new Map(this.connectedMeetings.meetings.map(o=>[o.id,o]));t.forEach(o=>{var l;const{parentMeeting:c}=this.connectedMeetings;if(o.id===(c==null?void 0:c.id)){this.connectedMeetings.parentMeeting={...c,title:o.title};return}const d=e.get(o.id);e.set(o.id,{...d,id:o.id,title:o.title,participants:(l=d==null?void 0:d.participants)!=null?l:[]})}),this.connectedMeetings.meetings=Array.from(e.values());const r=(n=a(this,Se).getValue("meeting"))==null?void 0:n.meta,i=t.find(o=>o.id===(r==null?void 0:r.meetingId));r&&i&&i.title!==r.meetingTitle&&r[vl](i.title),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(s).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})}},Se=new WeakMap,eT);let Wl=NS;Bp([E.trace("ConnectedMeetingsController.getConnectedMeetings")],Wl.prototype,"getConnectedMeetings",1),Bp([E.trace("ConnectedMeetingsController.setupEvents")],Wl.prototype,"setupEvents",1),Bp([E.trace("ConnectedMeetingsController.switchMeeting")],Wl.prototype,"switchMeeting",1);var dL=Object.defineProperty,lL=Object.getOwnPropertyDescriptor,Fp=(s,t,e,r)=>{for(var i=r>1?void 0:r?lL(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&dL(t,e,i),i};function uL(s){switch(s){case"participant_token_not_yet_valid":return"The participant authentication token is not valid yet.";case"participant_token_expired":return"The participant authentication token has expired.";case"participant_token_revoked":return"The participant authentication token has been revoked.";case"participant_token_invalid":return"The participant authentication token is invalid.";case"meeting_inactive":return"The meeting is inactive and is not accepting participants.";default:return"The participant authentication token may be invalid, expired, or not yet valid. Verify the token and its validity window."}}const Fo=class{constructor(s,t,e){p(this,"apiBase");p(this,"selfController");p(this,"pollController");p(this,"chatController");p(this,"metaController");p(this,"storesManager");p(this,"stageController");p(this,"pluginController");p(this,"internalsController");p(this,"recordingController");p(this,"livestreamController");p(this,"participantController");p(this,"connectedMeetingsController");p(this,"telemetry");p(this,"logger");this.apiBase=s,this.storesManager=t.storesManager,this.metaController=t.metaController,this.selfController=t.selfController,this.chatController=t.chatController,this.pollController=t.pollController,this.stageController=t.stageController,this.pluginController=t.pluginController,this.recordingController=t.recordingController,this.internalsController=t.internalsController,this.participantController=t.participantController,this.livestreamController=t.livestreamController,this.connectedMeetingsController=t.connectedMeetingsController,this.telemetry=e.getValue("telemetry"),this.logger=e.getValue("logger")}static async init(s){var B,U,j,Z,re;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(EN(s),Pe.isSupported()===!1)throw new C("Browser not supported","0010",c,!0);const d=QO(s,{authToken:r,baseURL:e,cachedUserDetails:o});d.setRoomName(i),d.setRoomUUID(i),d.setOrganizationId(n),d.setHeader("tracing-id",t),s.setValue("apiClient",d);const l=new DD(s);s.setValue("connectionHandler",l);let u="",h=null;c.info("CF SFU is being used.");const g=Fo.createSocketService(s),v=g.connect();v.catch(()=>{});const y=d.getUserDetails();try{h=await y,u=((B=h.meeting)==null?void 0:B.title)||"",s.setValue("presetName",h.preset.name)}catch(F){if(c.error("Failed to get user details",{error:F}),g.disconnect(),F instanceof gl){if(F.status===401||F.status===403){const ee=(Z=(j=(U=F.response)==null?void 0:U.data)==null?void 0:j.error)==null?void 0:Z.reason;throw new C(uL(ee),"0004",void 0,!1,ee)}throw F.status===404?(c.error("[ERROR:0004] participant-details returned 404."),new C("The auth token is not associated with an active participant in this meeting. The meeting may have ended, or the participant may no longer exist. (404)","0004")):F.status>=500?new C(`The server encountered an error. Try again. (${F.status})`,"0001"):F.isHttpError?new C(`Request rejected by the server. (${F.status})`,"0001"):F.isTimeout?new C("Connection timed out. Check the network and try again.","0001"):new C("Unable to connect to the server. Check the internet connection.","0001")}throw new C((F==null?void 0:F.message)||"Failed to initialize.","0001")}try{await v}catch(F){c.error("[Controller]: Failed to connect to socket server:",{error:F})}const k=Tp.init(h.preset,!s.getValue("modules").theme);s.setValue("theme",k);const I=Ep.init(s,k.viewType,h.preset.permissions),D=Fo.setupControllers(g,s,h,u,k,I);ED(k)&&((re=Fo.createRoomNodeClient(s,g).initializeConnection(h.participant.name,i,!1,I))==null||re.catch(ee=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:ee})}));const{controllers:N}=await D;return oC(),new Fo(e,N,s)}static async setupControllers(s,t,e,r,i,n){var fe,V,_;const o=t.getValue("modules"),{participant:c}=e,d=t.getValue("defaults"),l=t.getValue("logger"),{viewType:u,mediaConstraints:{audio:h}}=i;t.setValue("viewType",u),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(fe=h.enableHighBitrate)!=null?fe:!1,enableStereo:(V=h.enableStereo)!=null?V:!1}},...d}),t.setValue("maxPreferredStreams",Pe.isMobile()?i.maxVideoStreams.mobile:i.maxVideoStreams.desktop);let g,v,y,k,I,D,N,B,U;const j=new kN(t,s),Z=new rL(s);t.setValue("connectedMeetingsSocketHandler",Z);const re=new Nl(t,s),F=new dr(t,s),ee=new MN(s),we=new lS(t,s),vt=new ON(t,s),A=new PN(s),S=await Kr.init(t,we,c,n,i);t.setValue("selfController",S);const w=await Av.init(t,S.self,we,j,r);o.participant&&(B=await pr.init(t,S.self,we)),(_=o.e2ee)!=null&&_.enabled&&o.e2ee.manager.init(l,t.getValue("peerSessionStore")),o.chat&&(v=await wo.init(t,F,S.self,B.participants)),o.internals&&(I=await pp.init(t)),o.livestream&&i.viewType===Ss.Livestream&&(N=new Qv(t,S.self,A)),o.poll&&(g=await Cv.init(t,S.self,re)),o.recording&&(D=new xv(t,S.self,we)),o.stage&&(y=new Mv(t,ee,we,S.self,B.participants));const $=new M1(t,vt);if(o.plugin){if(!B)throw new C("The plugin module cannot be initialized without the `participant` module","0102");const He=d.plugins||[];k=await Lv.init(t,He,S.self,$)}if(o.connectedMeetings&&(U=await Wl.init(t)),o.pip){const He=await Lh._init(t,S.self);t.setValue("pip",He)}return{theme:i,permissions:n,controllers:{storesManager:$,pollController:g,selfController:S,metaController:w,chatController:v,stageController:y,pluginController:k,recordingController:D,internalsController:I,livestreamController:N,participantController:B,connectedMeetingsController:U}}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return cS(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=[];return new Bo(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Jl=Fo;Fp([E.trace("Controller.init")],Jl,"init",1),Fp([E.trace("Controller.createRoomNodeClient")],Jl,"createRoomNodeClient",1),Fp([E.trace("Controller.createSocketService")],Jl,"createSocketService",1);class hL{constructor(){p(this,"battery");p(this,"logger");p(this,"init",async t=>{this.logger=t;try{"getBattery"in navigator&&(this.battery=await navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){t.error("Error getting battery",e)}});p(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});p(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});p(this,"cleanup",()=>{var t,e;"getBattery"in navigator&&((t=this.battery)==null||t.removeEventListener("chargingchange",this.updateChargeInfo),(e=this.battery)==null||e.removeEventListener("levelchange",this.updateLevelInfo))})}}const LS=new hL;class pL{constructor(){m(this,Zu);m(this,wi,new Audio);m(this,Dn,new MediaStream);m(this,Nn,new Map);m(this,id,void 0);a(this,wi).srcObject=a(this,Dn),a(this,wi).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,Nn).has(e.id)||(a(this,Dn).addTrack(e),a(this,Nn).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,wi).setSinkId(t)}removeTrack(t){const e=a(this,Nn).get(t);e&&(a(this,Dn).removeTrack(e),a(this,Nn).delete(t))}async play(){return a(this,wi).srcObject=a(this,Dn),a(this,wi).play().catch(t=>{R(this,Zu,JT).call(this,t)})}onError(t){f(this,id,t)}}wi=new WeakMap,Dn=new WeakMap,Nn=new WeakMap,id=new WeakMap,Zu=new WeakSet,JT=function(t){var e;(e=a(this,id))==null||e.call(this,t)};class mL extends pL{constructor(){super();m(this,Zs,void 0);f(this,Zs,new Map)}addParticipantTrack(e,r){a(this,Zs).set(e,r.id),this.playTracks([r])}reassignParticipantTrack(e,r){const i=a(this,Zs).get(e);i&&(a(this,Zs).delete(e),a(this,Zs).set(r,i))}removeParticipantTrack(e){const r=a(this,Zs).get(e);r&&this.removeTrack(r),a(this,Zs).delete(e)}}Zs=new WeakMap;var gL=Object.defineProperty,fL=Object.getOwnPropertyDescriptor,Kl=(s,t,e,r)=>{for(var i=r>1?void 0:r?fL(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&gL(t,e,i),i};let Zr=(tT=class{constructor(t,e){m(this,qe,void 0);m(this,Ln,void 0);f(this,Ln,t),f(this,qe,e)}get peerId(){return a(this,Ln).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:Ci(),n=Br.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new eS(n,o);return await c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var v,y,k,I,D,N,B,U;Pe.init();const e=(y=(v=t==null?void 0:t.cachedUserDetails)==null?void 0:v.peerId)!=null?y:Ci(),{authToken:r,baseURI:i}=t,{meetingId:n,...o}=KN(r,i);if((k=o.baseURI)!=null&&k.includes("dyte.io"))throw new C("Dyte Base URIs are no longer supported. Use RealtimeKit Base URIs.","0001");const c=K1((I=t.defaults)==null?void 0:I.mediaProducerConfiguration);if(c.valid!==!0)throw new C(c.message,"0001");window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const d=Zr.setupContext(e,t,n,o);d.setValue("mediaProducerCodecs",c.codecs);const l=d.getValue("telemetry"),u=d.getValue("logger");QT(u),LS.init(u),l.init(d,{roomName:n,userId:o.participantId,organizationId:o.orgId,peerId:e},(N=(D=t.modules)==null?void 0:D.tracing)!=null?N:!0,(U=(B=t==null?void 0:t.modules)==null?void 0:B.devTools)==null?void 0:U.logLevel),u.init(d),u.info("Client::init::options",{clientInitOptions:{...t,authToken:AS(t.authToken)}}),u.info(`Using producer codecs: ${JSON.stringify(c.codecs)}`);const h=await Jl.init(d),g=new Zr(d,h);return d.setValue("meeting",g),u.info(`Meeting view type: ${g.meta.viewType}`),g}static setupContext(t,e,r,i){var d,l;const n=Br.createContext(t,e),o={...$_,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return n.setValue("options",e),n.setValue("peerId",t),n.setValue("modules",o),n.setValue("sdkName","web-core"),n.setValue("meetingId",r),n.setValue("apiBase",i.apiBase),n.setValue("baseURI",i.baseURI),n.setValue("userId",i.participantId),n.setValue("organizationId",i.orgId),n.setValue("authToken",e.authToken),n.setValue("overrides",(d=e.overrides)!=null?d:{}),n.setValue("env",U_({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Ls(e.cachedUserDetails)),n.setValue("sdkVersion","2.2.0-staging.1"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new mL),n}async join(){const{selfController:t}=a(this,qe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){var r;LS.cleanup(),a(this,Ln).getValue("peerSessionStore").reset(),(r=a(this,qe).pluginController)==null||r.cleanup();const{selfController:e}=a(this,qe);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,qe).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,qe).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,qe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,qe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,qe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,qe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,qe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,qe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,qe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,qe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,qe).stageController)==null?void 0:t.stage}get stores(){return a(this,qe).storesManager}get audio(){return a(this,Ln).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,qe).internalsController)==null?void 0:t.internals}},qe=new WeakMap,Ln=new WeakMap,tT);Kl([pt("0002"),ur.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Zr.prototype,"join",1),Kl([pt("0003")],Zr.prototype,"leave",1),Kl([pt("0001"),ur.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Zr,"init",1),Zr=Kl([pt("0000")],Zr);const VS=Zr;return VS}();
|
|
16
|
+
`},Hi=nS,aN=nN,Ml=aN,qi=Hi.parse;Hi.parseParams,Hi.parseFmtpConfig,Hi.parsePayloads,Hi.parseRemoteCandidates,Hi.parseImageAttributes,Hi.parseSimulcastStreamList;class Ol extends Tt.EventEmitter{constructor(e){super();m(this,Sc,void 0);f(this,Sc,e),this.setMaxListeners(1/0)}get logger(){return a(this,Sc).getValue("logger")}safeEmit(e,...r){const i=this.listenerCount(e);try{return this.emit(e,...r)}catch(n){return this.logger.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:n}),Boolean(i)}}async safeEmitAsPromise(e,...r){const i={}.EVENT_PROMISE_TIMEOUT?parseInt({}.EVENT_PROMISE_TIMEOUT,10):1e4;return this.safeEmitAsPromiseWithTimeout(e,i,...r)}async safeEmitAsPromiseWithTimeout(e,r,...i){return new Promise((n,o)=>{setTimeout(o,r,"event request timeout");try{this.emit(e.toString(),...i,n,o)}catch(c){this.logger.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:c}),o(c)}})}}Sc=new WeakMap;function oN(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}class cN extends Ol{constructor(e,r){var i;super(e);m(this,qs);m(this,yc);m(this,vu);m(this,Su);p(this,"rtpReceiver");p(this,"id");p(this,"localId");p(this,"producerId");p(this,"producingTransportId");p(this,"mimeType");p(this,"track");p(this,"peerId");p(this,"appData");p(this,"transceiver");m(this,Tc,void 0);m(this,fn,void 0);m(this,Hs,void 0);m(this,fu,void 0);this.id=r.id,this.localId=r.localId,f(this,Tc,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,f(this,Hs,!1),this.producerId=r.producerId,this.track=r.track,f(this,fn,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,R(this,vu,vT).call(this),f(this,fu,e)}get closed(){return a(this,Hs)}get kind(){return this.track.kind}get paused(){return a(this,fn)}reassignPeer(e){this.peerId=e}close(e,r){a(this,Hs)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,a(this,qs,Pi)),f(this,Hs,!0),r&&(R(this,Su,ST).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(a(this,Hs))throw new Nt("closed");return a(this,Tc).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",a(this,qs,Pi)),a(this,Hs)){this.logger.error("consumer::pause() | Consumer closed",a(this,qs,Pi));return}f(this,fn,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",a(this,qs,Pi)),a(this,Hs)){this.logger.error("Consumer::resume() | Consumer closed",a(this,qs,Pi));return}f(this,fn,!1),this.track.enabled=!0,this.safeEmit("resume")}}Tc=new WeakMap,fn=new WeakMap,Hs=new WeakMap,fu=new WeakMap,qs=new WeakSet,Pi=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},yc=new WeakSet,nm=function(){this.logger.debug('Consumer::track "ended" event',a(this,qs,Pi)),this.safeEmit("trackended")},vu=new WeakSet,vT=function(){this.track.addEventListener("ended",R(this,yc,nm).bind(this))},Su=new WeakSet,ST=function(){try{this.track.removeEventListener("ended",R(this,yc,nm)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...a(this,qs,Pi),error:e})}};class dN extends Ol{constructor(e,r){var i,n;super(e);m(this,Yt);p(this,"id");p(this,"localId");m(this,Cs,void 0);p(this,"kind");p(this,"appData");p(this,"rtpSender");m(this,Va,void 0);m(this,xa,void 0);m(this,vn,void 0);m(this,ps,!1);m(this,dt,void 0);m(this,mi,void 0);m(this,$a,void 0);m(this,Tu,void 0);this.id=r.id,this.localId=r.localId,f(this,dt,r.track),this.kind=(i=r.track)==null?void 0:i.kind,f(this,mi,r.disableTrackOnPause?!((n=r.track)!=null&&n.enabled):!1),f(this,$a,void 0),f(this,Va,r.stopTracks),f(this,xa,r.disableTrackOnPause),f(this,vn,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),f(this,Cs,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),f(this,Tu,e)}get closed(){return a(this,ps)}get track(){return a(this,dt)}get paused(){return a(this,mi)}get maxSpatialLayer(){return a(this,$a)}async close(e){if(a(this,ps))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,a(this,Yt,As)),f(this,ps,!0),this._destroyTrack(),e===Dl){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await a(this,Cs).stopSending(this.localId),{answer:n}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(n)}async getStats(){if(a(this,ps))throw new Nt("closed");return a(this,Cs).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",a(this,Yt,As)),a(this,ps)&&this.logger.error("Producer::pause() | Producer closed",a(this,Yt,As)),f(this,mi,!0),a(this,dt)&&a(this,xa)&&(a(this,dt).enabled=!1),a(this,vn)&&a(this,Cs).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",a(this,Yt,As)),a(this,ps)){this.logger.error("Producer::resume() | Producer closed",a(this,Yt,As));return}f(this,mi,!1),a(this,dt)&&a(this,xa)&&(a(this,dt).enabled=!0),a(this,vn)&&a(this,Cs).replaceTrack(this.localId,a(this,dt)),this.emit("resume")}async replaceTrack({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,a(this,Yt,As)),a(this,ps)){if(e&&a(this,Va))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...a(this,Yt,As),error:r})}throw new Nt("closed")}else if(e&&e.readyState==="ended")throw new Nt("track ended");if(e===a(this,dt)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,a(this,Yt,As));return}(!a(this,vn)||!a(this,mi))&&await a(this,Cs).replaceTrack(this.localId,e),this._destroyTrack(),f(this,dt,e),this._handleTrack()}async setMaxSpatialLayer(e){if(a(this,ps))throw new Nt("closed");if(this.kind!=="video")throw new Ao("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await a(this,Cs).setMaxSpatialLayer(this.localId,e),f(this,$a,e)}async setRtpEncodingParameters(e){if(a(this,ps))throw new Nt("closed");if(typeof e!="object")throw new TypeError("invalid params");await a(this,Cs).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,a(this,Yt,As)),this.safeEmit("trackended",this.track.id)}_handleTrack(){a(this,dt)&&a(this,dt).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(a(this,dt))try{a(this,dt).removeEventListener("ended",this._onTrackEnded),a(this,Va)&&a(this,dt).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...a(this,Yt,As),error:r})}}}Cs=new WeakMap,Va=new WeakMap,xa=new WeakMap,vn=new WeakMap,ps=new WeakMap,dt=new WeakMap,mi=new WeakMap,$a=new WeakMap,Tu=new WeakMap,Yt=new WeakSet,As=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};const Dl="transport closed",lN=3e4,Ba=class extends Ol{constructor(e,{id:r,direction:i,handlerFactory:n,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:u,config:h}){var k,I,D;super(e);p(this,"awaitQueue");p(this,"observer");p(this,"id");p(this,"serverId");p(this,"direction");p(this,"maxSctpMessageSize");p(this,"handler");p(this,"connectionState","new");p(this,"producers");p(this,"consumers");p(this,"connected",!1);p(this,"transportConnectionPromise");p(this,"consumerTrackEvents");p(this,"unknownTracksMap");p(this,"appData");m(this,Ua,void 0);f(this,Ua,e);const g=e.getValue("logger");g.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const v=oN(l,{});delete v.iceServers,delete v.iceTransportPolicy,delete v.bundlePolicy,delete v.rtcpMuxPolicy,delete v.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new kp(g,!0),this.handler=n(),this.handler.enableHighBitrate=(k=h==null?void 0:h.enableHighBitrate)!=null?k:!1,this.handler.enableStereo=(I=h==null?void 0:h.enableStereo)!=null?I:!1,this.handler.enableDtx=(D=h==null?void 0:h.enableDtx)!=null?D:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:o,iceTransportPolicy:c,additionalSettings:l,proprietaryConstraints:d}),this.appData=u||{};const y=3e4;this.transportConnectionPromise=new Promise(N=>{const B=setTimeout(()=>{g.error("ICE connection timeout - possible firewall blocking WebRTC or TURN unreachable",{transport:{id:this.id,type:this.direction}}),N(!1)},y);this.once("connected",()=>{clearTimeout(B),N(!0)}),this.once("disconnect",()=>{clearTimeout(B),N(!1)}),this.once("close",()=>{clearTimeout(B),N(!1)})}),this.handler.on("@connectionstatechange",N=>{N!==this.connectionState&&(this.connectionState=N,N==="connected"&&(this.connected=!0,this.emit("connected")),N==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(N==="failed"||N==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",N))}),this.handler.on("@icecandidate",({candidate:N})=>{this.closed||this.safeEmit("icecandidate",N)})}get closed(){return this.connectionState==="closed"}setServerId(e){this.serverId!==e&&(this.serverId=e,this.emit("serveridchange",e))}close(){this.closed||(this.logger.debug("Transport close called"),this.connectionState="closed",this.awaitQueue.stop(),this.awaitQueue=void 0,this.connected=!1,this.handler.close(),Array.from(this.producers.values()).forEach(e=>{e.close(Dl).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(Dl)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new Nt("closed");return this.handler.getTransportStats()}async connect(e){try{if(await this.awaitQueue.push(async()=>{const{offerSdp:r,callback:i}=await this.handler.connect(),{transportId:n,answer:o}=await e(r);this.setServerId(n),await i(o)}),!await this.transportConnectionPromise)throw new Error("ice connection failed")}catch(r){throw this.logger.error("transport failed to connect:",{error:r}),r}}async restartIce(){if(this.logger.debug("restartIce()"),this.closed)throw new Nt("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new Ao("not a sending Transport");if(r.readyState==="ended")throw new Nt("track ended");if(i&&typeof i!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!await this.transportConnectionPromise)throw new Jr("transport not connected");return!0}async produce(e,r){if(!await this.canProduce(e))throw new Error("Cannot produce");const{track:n,encodings:o,codecOptions:c,stopTracks:d=!0,disableTrackOnPause:l=!0,zeroRtpOnPause:u=!1,appData:h={}}=e;this.logger.debug(`produce() [track:${n.id}]`);const{producerId:g,localId:v,rtpSender:y}=await this.awaitQueue.push(async()=>{const{offerSdp:k,callback:I,sender:D,mid:N}=await this.handler.send({track:n,encodings:o,codecOptions:c,screenShare:h==null?void 0:h.screenShare}),{answer:B,producerId:U}=await r({offer:k,kind:n.kind,paused:l?!n.enabled||Object.hasOwn(n,"fakeTracks"):!1,appData:{...h||{},mid:N},codecOptions:c,producingTransportId:this.serverId}),j=await I(B);return{producerId:U,localId:j,rtpSender:D}},"Transport.produce");return this.createProducerObject({id:g,localId:v,track:n,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:u,appData:h,handler:this.handler,rtpSender:y})}async createProducerObject(e){const r=new dN(a(this,Ua),e);return this.producers.set(r.id,r),r.once("close",()=>{this.producers.delete(r.id)}),this.emit("newproducer",r),r}async closeProducer(e){await this.awaitQueue.push(e.close.bind(e),"Transport.closeProducer")}async canConsume(){if(this.closed)throw new Nt("closed");if(this.direction!=="recv")throw new Ao("not a receiving transport");if(!await this.transportConnectionPromise)throw new Jr("transport not connected");return!0}async consume(e,r,i){return this.awaitQueue.push(async()=>{const n={},{consumerStates:o,sessionDescription:c,failedProducers:d}=await r(e);o.forEach((u,h)=>{n[h]=this.createConsumerObjectAndWaitForTrack({...u,producerId:h})}),c&&(this.logger.info("Session description found, sending negotiation request"),await i(c));const l=[];return await Promise.all(Object.entries(n).map(([u,h])=>h.then(g=>l.push(g)).catch(()=>{this.logger.error(`Failed to create consumer object, producer: ${u}`,{error:{message:"This should not happen"},transport:{serverId:this.serverId}})}))),{consumers:l,failedProducers:d}},"Transport.consume",{producersLength:e.length})}static parseCodecAndFmtpMappings(e,r){const i=qi(e.sdp),n={};return i.media.forEach(o=>{r.includes(o.mid.toString())&&(n[o.mid.toString()]={rtp:o.rtp,fmtp:o.fmtp,payloads:o.payloads,rtcpFb:o.rtcpFb})}),n}static setCodecAndFmtpMappings(e,r,i){const n=qi(e.sdp);return n.media=n.media.map(c=>{if(r.includes(c.mid.toString())){const d={...c};return d.rtp=i[c.mid.toString()].rtp,d.fmtp=i[c.mid.toString()].fmtp,d.payloads=i[c.mid.toString()].payloads,d.rtcpFb=i[c.mid.toString()].rtcpFb,d}return c}),{...e,sdp:Ml(n)}}static parseHeaderExtensionMappings(e){const r=qi(e.sdp),i={};return r.media.forEach(n=>{i[n.mid]=n.ext}),i}static setHeaderExtensionMappings(e,r){const i=qi(e.sdp);return i.media=i.media.map(o=>{const c={...o};return c.ext=r[o.mid],c}),{...e,sdp:Ml(i)}}async closeConsumers(e,r){try{const i=e.map(l=>l.transceiver.mid),n=Ba.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=Ba.parseHeaderExtensionMappings(this.handler.pc.remoteDescription);this.logger.info("Stopping transceivers",{consumerIds:e.map(({id:l})=>l)}),e.forEach(l=>l.close(void 0,!0));let c=await this.handler.pc.createOffer();this.logger.info("[SDP] Created offer for closing consumers",{sdp:c.sdp}),c=Ba.setCodecAndFmtpMappings(c,i,n),c=Ba.setHeaderExtensionMappings(c,o),this.logger.info("[SDP] Updated codec and fmtp mappings in close consumer offer",{sdp:c.sdp}),await this.setLocalDescription(c),this.logger.info("Successfully set local description in close consumers");const d=await r(e,c);this.logger.info("[SDP] Received answer in close consumers",{sdp:d.sdp}),await this.setRemoteDescription(d),this.logger.info("[SDP] Remote description was set successfully in close consumers",{sdp:d.sdp})}catch(i){this.logger.error("Failed to close consumers",{error:i})}}async setRemoteOffer(e){try{this.logger.info("[SDP] Received offer from SFU",{sdp:e.sdp}),await this.setRemoteDescription(e);const r=await this.handler.pc.createAnswer();this.logger.info("[SDP] Created answer corresponding to received offer",{sdp:r.sdp});const i=qi(r.sdp);return i.media=i.media.map(n=>{if(n.type==="audio"){const o={...n},c=o.fmtp.find(l=>l.payload===111);return c&&(c.config+=";stereo=1;sprop-stereo=1"),o.rtcpFb||(o.rtcpFb=[]),o.rtcpFb.some(l=>l.type==="nack")||o.rtcpFb.push({payload:parseInt(o.payloads,10),type:"nack"}),o}return n}),r.sdp=Ml(i),this.logger.info("[SDP] Setting munged SDP",{sdp:r.sdp}),await this.setLocalDescription(r),this.logger.info("[SDP] Successfully set local description",{sdp:r.sdp}),r}catch(r){throw this.logger.error("Set remote offer failed",{error:r}),r}}_ontrack(e){const{track:r,transceiver:i}=e;this.logger.info(`track event received [trackId: ${r.id}] [mid: ${i.mid}]`);const n=`${i.mid}:${r.kind}`;r.addEventListener("ended",()=>{this.logger.info(`rtc consumer track ended [trackId: ${r.id}]`),this.unknownTracksMap.delete(n)});const o=this.consumerTrackEvents.get(n);o?(o(r,i),this.consumerTrackEvents.delete(n)):(this.logger.warn(`track event handler not found ${n}`),this.unknownTracksMap.set(n,e))}async createConsumerObjectAndWaitForTrack(e){const{consumerId:r,producerId:i,producingPeerId:n,producingTransportId:o,streamId:c,paused:d,screenShare:l,appData:u,kind:h,mimeType:g}=e,v=`${c}:${h}`,y={...e,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(k,I)=>{const D=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${v} producingPeerId: ${n}`),this.consumerTrackEvents.delete(v),y.isTimedout=!0,I(y)},lN),N=(U,j)=>{try{if(U.readyState==="ended")clearTimeout(D),I(y);else{const Z=U;Z.enabled=!0,this.handler.midTransceiverMap.set(j.mid,j);const re=new cN(a(this,Ua),{id:r,localId:j.mid,transceiver:j,track:Z,paused:d,producerId:i,producingPeerId:n,producingTransportId:o,handler:this.handler,appData:{...u,screenShare:l,peerId:n},rtpReceiver:j.receiver,mimeType:g});this.consumers.set(r,re),re.once("close",()=>{this.consumers.delete(re.id),this.handler.midTransceiverMap.delete(j.mid)}),this.logger.info(`${l?"screenshare":"participant"} ${h} consumer ${r} created for producer ${i} of remote producing peer ${n} with track ${U.id} on mid ${j.mid}`),this.emit("newconsumer",re),clearTimeout(D),k(re)}}catch(Z){this.logger.error(`Error while creating ${l?"screenshare":"participant"} ${h} consumer for producerId ${i} of remote peer ${n}`,Z),clearTimeout(D),I(y)}},B=this.unknownTracksMap.get(v);B?(this.logger.info(`track event already received for ${l?"screenshare":"participant"} ${h} consumer ${r} of a remote peer ${n} with trackId ${B.track.id} on mid ${B.transceiver.mid} having key ${v}`),this.unknownTracksMap.delete(v),N(B.track,B.transceiver)):(this.logger.info(`Registering onTrack handler for ${l?"screenshare":"participant"} ${h} consumer ${r} of a remote peer ${n} with key ${v}`),this.consumerTrackEvents.set(v,N))})}async setRemoteDescription(e){await this.handler.pc.setRemoteDescription(e)}async setLocalDescription(e){this.logger.debug(`[SDP] ${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),await this.handler.pc.setLocalDescription(e)}};let Cp=Ba;Ua=new WeakMap;class uN{constructor(t){m(this,st,void 0);p(this,"events");f(this,st,t),this.events=Es}async joinRoom(t,e,r,i=!1){const n={roomUuid:t,displayName:e,prejoined:i,capabilities:r};return(await a(this,st).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:TR.toBinary(n),timeout:5e3})).payload}async connectTransport(t){const e=(await a(this,st).sendMessagePromise(this.events.createWebRTCTransport,JC.toBinary(t))).payload,{transportId:r,description:i,producerIds:n}=Jf.fromBinary(e),o={sdp:i==null?void 0:i.sdp,type:i.type};return{transportId:r,answer:o,producerIds:n}}async produce(t){var n,o;const e=(await a(this,st).sendMessagePromise(this.events.produce,NR.toBinary(t))).payload,r=gI.fromBinary(e);return{answer:{sdp:(n=r==null?void 0:r.description)==null?void 0:n.sdp,type:(o=r==null?void 0:r.description)==null?void 0:o.type},producerId:r.producerId}}async consume(t){const e=(await a(this,st).sendMessagePromise(this.events.consume,RR.toBinary(t))).payload,{consumerIdsMap:{map:r},description:i}=pI.fromBinary(e);return{consumerStateMap:r,sessionDescription:i}}async closeProducer(t){const e=(await a(this,st).sendMessagePromise(this.events.closeProducer,FR.toBinary(t))).payload,{description:r}=bI.fromBinary(e);return r}async closeConsumer(t){return(await a(this,st).sendMessagePromise(this.events.closeConsumer,qR.toBinary(t))).payload}async updateConsumersSimulcastConfig(t){return(await a(this,st).sendMessagePromise(this.events.updateConsumersSimulcastConfig,OR.toBinary(t))).payload}async hostControlForPeer(t,e){const r={audio:e==="audio",screeShare:!1,video:e==="video",participantId:t},i=(await a(this,st).sendMessagePromise(this.events.hostControlPeer,zR.toBinary(r))).payload;if(!i)return!1;const{status:n}=II.fromBinary(i);return n==="success"}async hostControlForAll(t){const e={audio:t==="audio",screenShare:!1,video:t==="video"},r=(await a(this,st).sendMessagePromise(this.events.hostControlAllPeers,QR.toBinary(e))).payload;if(!r)return!1;const{status:i}=MI.fromBinary(r);return i==="success"}async kickAll(){const t={propagateKickAcrossRooms:!1};a(this,st).sendMessagePromise(x.kickAll,Zf.toBinary(t))}async kickPeer(t){a(this,st).sendMessagePromise(x.kick,pv.toBinary(t))}async changeDisplayName(t){const e=(await a(this,st).sendMessagePromise(this.events.changeDisplayName,JR.toBinary(t))).payload;if(!e)return!1;const{status:r}=DI.fromBinary(e);return r==="success"}async notifySelfJoinComplete(){const t={},e=(await a(this,st).sendMessagePromise(this.events.selfJoinComplete,ER.toBinary(t))).payload;return jh.fromBinary(e)}async audioActivity(t){a(this,st).sendMessage(this.events.audioActivity,zC.toBinary(t))}}st=new WeakMap;var as=(s=>(s.NEW="new",s.CONNECTING="connecting",s.RECONNECTING="reconnecting",s.DISCONNECTED="disconnected",s.CONNECTED="connected",s.FAILED="failed",s.CLOSED="closed",s))(as||{});class Rp extends Ol{constructor(){super(...arguments);p(this,"_sendWebStream",new MediaStream);p(this,"_sendScreenShareStream",new MediaStream);p(this,"_direction");p(this,"pc");p(this,"_transportReady",!1);p(this,"_mapMidTransceiver",new Map);p(this,"enableHighBitrate",!1);p(this,"enableStereo",!1);p(this,"enableDtx",!0)}get midTransceiverMap(){return this._mapMidTransceiver}close(){if(this.logger.debug(`${this.name}::close()`),this.pc)try{this.pc.close()}catch(e){this.logger.error(`${this.name}::pc.close()`,{error:e})}}async restartIce(){this.logger.debug(`${this.name}::restartIce()`);const e=await this.pc.createOffer({iceRestart:!0});return this.logger.debug(`[SDP] ${this.name}::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:async i=>{this.logger.info(`[SDP] ${this.name}::restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),await this.pc.setRemoteDescription(i)}}}init({direction:e,iceServers:r,iceTransportPolicy:i,additionalSettings:n,proprietaryConstraints:o,onTrackHandler:c}){this.logger.debug("HandlerInterface::init()"),this._direction=e,this.pc=new RTCPeerConnection({iceServers:r||[],iceTransportPolicy:i||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...n},o),c&&this.pc.addEventListener("track",d=>{c(d)}),this._addEventListeners()}async connect(){this.pc.addTransceiver("audio",{direction:"sendonly"}),this.pc.addTransceiver("video",{direction:"sendonly",...this._direction==="send"?{sendEncodings:[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]}:{}});const e=await this.pc.createOffer();return await this.pc.setLocalDescription(e),this.logger.info(`[SDP] connect offer: ${JSON.stringify(e)}`),{offerSdp:e,callback:async i=>{this.logger.debug(`[SDP] ${this.name}::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),await this.pc.setRemoteDescription(i)}}}async getTransportStats(){return this.pc.getStats()}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}async getReceiverStats(e){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()}async stopSending(e){this._assertSendDirection(),this.logger.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 i=await this.pc.createOffer();return this.logger.debug(`[SDP] stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(i)}]`),await this.pc.setLocalDescription(i),{offerSdp:i,callback:async o=>{this.logger.debug(`[SDP] stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(o)}]`),await this.pc.setRemoteDescription(o),this.midTransceiverMap.delete(e)}}}async replaceTrack(e,r){this._assertSendDirection(),r?this.logger.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):this.logger.debug(`replaceTrack() [localId:${e}, no track]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");await i.sender.replaceTrack(r)}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters();n.encodings.forEach((o,c)=>{c<=r?o.active=!0:o.active=!1}),await i.sender.setParameters(n)}async setRtpEncodingParameters(e,r){this._assertSendDirection(),this.logger.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters();n.encodings.forEach((o,c)=>{n.encodings[c]={...o,...r}}),await i.sender.setParameters(n)}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}_addEventListeners(){this.pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this.pc.addEventListener("iceconnectionstatechange",()=>{switch(this.pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:this.logger.warn("unknown state");break}}),this.pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),this.logger.debug("negotiationneeded")}),this.pc.addEventListener("icegatheringstatechange",()=>{switch(this.pc.iceGatheringState){case"gathering":this.logger.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":this.logger.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:this.logger.warn("unknown state");break}}),this.pc.addEventListener("icecandidateerror",e=>{this.logger.warn("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})})}}class Ip extends Rp{static createFactory(t){return()=>new Ip(t)}get name(){return"Chrome74"}init({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:i,proprietaryConstraints:n,onTrackHandler:o}){this._direction=t,this.pc=new RTCPeerConnection({iceServers:e||[],iceTransportPolicy:r||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...i},n),o&&this.pc.addEventListener("track",c=>{o(c)}),this._addEventListeners()}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection();const n=typeof t=="string"?t:t.kind,o=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e});if(!navigator.isReactNative){this.logger.debug("creating new transceiver");const l=RTCRtpSender.getCapabilities(n);this.logger.info(`senders available params: ${JSON.stringify(l)}`);const u=[];r&&r.length&&r.forEach(h=>{var v;const g=l.codecs.find(y=>y.mimeType.toLowerCase()===h.mimeType.toLowerCase());if(h.parameters){this.logger.debug(`codecOption.parameters:${JSON.stringify(h.parameters)}`);const y=((v=g.sdpFmtpLine)==null?void 0:v.split(";"))||[];y.push(...h.parameters);const k=Array.from(new Set(y).values());g.sdpFmtpLine=k.join(";")}u.push(g)}),this.logger.info(`selected codecs: ${JSON.stringify(u)}`),o.setCodecPreferences(u)}const c=await this.pc.createOffer();if(await this.pc.setLocalDescription(c),r!=null&&r.some(({mimeType:l})=>l===Fi.OPUS)){const{enableDtx:l,enableStereo:u}=this,h=this.enableHighBitrate?u?128e3:64e3:u?64e3:32e3;c.sdp=c.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${l?"usedtx=1;":""}${u?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${h}`),c.sdp+=`a=rtcp-fb:111 nack\r
|
|
17
|
+
`}this.midTransceiverMap.set(o.mid,o);const d=async l=>(this.logger.debug(`[SDP] send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(l)}]`),await this.pc.setRemoteDescription(l),o.mid);return this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(c,void 0,2)}]`),{offerSdp:c,callback:d,sender:o.sender,mid:o.mid}}}class Nl extends Rp{constructor(e,r){super(e);p(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new Nl(e,r)}get name(){return"Firefox60"}async send({track:e,encodings:r,codecOptions:i,screenShare:n}){this._assertSendDirection();const o=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},c=this.pc.addTransceiver(e,{direction:"sendonly",streams:[n?this._sendScreenShareStream:this._sendWebStream],...o});if(!this.supportsSendEncodings&&r){r.reverse();const h=c.sender.getParameters();h.encodings=r,await c.sender.setParameters(h)}const d=(h,g)=>{var B;const v=qi(h),y=v.media[v.media.length-1],k=y.rtp.filter(U=>g.some(j=>j.mimeType.toLowerCase()===`${y.type}/${U.codec}`.toLowerCase())),I=y.fmtp.filter(U=>k.some(j=>j.payload===U.payload)),D=(B=y.rtcpFb)==null?void 0:B.filter(U=>k.some(j=>j.payload===U.payload)),N=k.map(U=>U.payload);return v.media[v.media.length-1].rtp=k,v.media[v.media.length-1].fmtp=I,v.media[v.media.length-1].rtcpFb=D,v.media[v.media.length-1].payloads=N.join(" "),Ml(v)},l=await this.pc.createOffer();if(l.sdp=d(l.sdp,i),this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer:${JSON.stringify(l)}]`),await this.pc.setLocalDescription(l),i!=null&&i.some(({mimeType:h})=>h===Fi.OPUS)){const{enableDtx:h,enableStereo:g}=this,v=this.enableHighBitrate?g?128e3:64e3:g?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${g?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${v}`)}return this.midTransceiverMap.set(c.mid,c),{offerSdp:l,callback:async h=>(this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),await this.pc.setRemoteDescription(h),c.mid),sender:c.sender,mid:c.mid}}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters(),o=n.encodings.length-1-r;n.encodings.forEach((c,d)=>{d>=o?c.active=!0:c.active=!1}),await i.sender.setParameters(n)}}class Ap extends Rp{static createFactory(t){return()=>new Ap(t)}get name(){return"Safari12"}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection();const n=typeof t=="string"?t:t.kind;this.logger.debug("Safari12::creating new transceiver");const o=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e}),c=RTCRtpSender.getCapabilities(n);this.logger.info(`Safari12::senders available params: ${JSON.stringify(c)}`);const d=[];r&&r.length>0&&r.forEach(h=>{var v;const g=c.codecs.find(y=>y.mimeType.toLowerCase()===h.mimeType.toLowerCase());if(h.parameters){this.logger.info(`Safari12::codecOption.parameters:, ${JSON.stringify(h.parameters)}`);const y=((v=g.sdpFmtpLine)==null?void 0:v.split(";"))||[];y.push(...h.parameters);const k=[...new Set(y).values()];g.sdpFmtpLine=k.join(";")}d.push(g)}),this.logger.info(`Safari12::selected codecs: ${JSON.stringify(d)}`),o.setCodecPreferences(d);const l=await this.pc.createOffer();if(await this.pc.setLocalDescription(l),r!=null&&r.some(({mimeType:h})=>h===Fi.OPUS)){const{enableStereo:h,enableDtx:g}=this,v=this.enableHighBitrate?h?128e3:64e3:h?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${g?"usedtx=1;":""}${h?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${v}`)}return this.midTransceiverMap.set(o.mid,o),{offerSdp:l,callback:async h=>(this.logger.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),await this.pc.setRemoteDescription(h),o.mid),sender:o.sender,mid:o.mid}}}function hN(s){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){s.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return s.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=_m.getParser(t),r=e.getEngine();if(e.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(e.satisfies({chrome:">=55",chromium:">=55"}))return;if(e.satisfies({firefox:">=110"}))return"Firefox110";if(e.satisfies({firefox:">=60"}))return"Firefox60";if(e.satisfies({ios:{OS:">=14.3",firefox:">=30.0"}})||e.satisfies({safari:">=12.0"})&&typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(e.satisfies({safari:">=11"})||e.satisfies({"microsoft edge":">=11"})&&e.satisfies({"microsoft edge":"<=18"}))return;if(r.name&&r.name.toLowerCase()==="blink"){const i=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);return i?Number(i[1])>=74?"Chrome74":void 0:"Chrome74"}if(r.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":void 0;s.warn("Device::this._detectDevice() | browser not supported");return}s.warn("Device::this._detectDevice() | unknown device")}class pN{constructor(t,{handlerName:e,handlerFactory:r}={}){p(this,"handlerFactory");m(this,Cr,void 0);m(this,Sn,void 0);const i=t.getValue("logger");if(i.debug("Device constructor() called."),f(this,Cr,t),f(this,Sn,i),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)a(this,Sn).debug(`Device::constructor() | handler given: ${e}`);else if(e=hN(a(this,Sn)),e)a(this,Sn).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=Ip.createFactory(a(this,Cr));break;case"Safari12":this.handlerFactory=Ap.createFactory(a(this,Cr));break;case"Firefox60":this.handlerFactory=Nl.createFactory(a(this,Cr),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=Nl.createFactory(a(this,Cr),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=Ci();return new Cp(a(this,Cr),{id:e,...t,handlerFactory:this.handlerFactory})}}Cr=new WeakMap,Sn=new WeakMap;const mN=2e3;class gN extends Tt.EventEmitter{constructor(e,r){super();m(this,Gs);m(this,Pc);m(this,yu);m(this,kc);m(this,Eu);m(this,bu);m(this,wu);m(this,Pu);m(this,ku);m(this,_c);m(this,Ws);p(this,"context");m(this,Fa,void 0);m(this,rt,void 0);m(this,it,void 0);m(this,Ec,void 0);m(this,bc,void 0);m(this,Tn,void 0);m(this,Ha,void 0);m(this,wc,void 0);m(this,qa,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});m(this,yn,void 0);m(this,js,"all");this.context=e,f(this,Tn,r),f(this,Fa,new pN(e)),f(this,Ha,new uN(r)),f(this,wc,Es),a(this,Gs,ki).mediaState={send:{state:as.NEW},recv:{state:as.NEW}},So(this.context,"forceRelay")&&f(this,js,"relay"),this.logger.info(`ICE Transport Policy initially set to ${a(this,js)}`),R(this,Pc,am).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return a(this,Tn)}get socketHandler(){return a(this,Ha)}get sendTransport(){return a(this,rt)}get recvTransport(){return a(this,it)}get events(){return a(this,wc)}set sendTransportConnectedCallback(e){f(this,Ec,e)}set recvTransportConnectedCallback(e){f(this,bc,e)}async setupTransports(e){await R(this,yu,TT).call(this,e);let r,i;e.send&&(r=R(this,kc,om).call(this,a(this,rt)).then(n=>{try{a(this,Ec).call(this,n)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=R(this,kc,om).call(this,a(this,it)).then(n=>{try{a(this,bc).call(this,n)}catch(o){this.logger.error("Failed to run recv transport callback")}})),await Promise.all([r,i])}stopTransports(e){var r,i;if(e.send&&this.sendTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,rt);this.logger.info("Closing send transport",{transport:{id:n,serverId:o,type:c}}),a(this,rt).close(),a(this,rt).removeAllListeners(),f(this,rt,void 0)}if(e.send&&(a(this,Gs,ki).mediaState.send.state!==as.CLOSED||a(this,Gs,ki).mediaState.send.sfuSessionId!==void 0)&&R(this,Ws,_i).call(this,{direction:"send",state:as.CLOSED}),e.recv&&this.recvTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,it);this.logger.info("Closing recv transport",{transport:{id:n,serverId:o,type:c}}),(r=a(this,it))==null||r.close(),(i=a(this,it))==null||i.removeAllListeners(),f(this,it,void 0)}e.recv&&(a(this,Gs,ki).mediaState.recv.state!==as.CLOSED||a(this,Gs,ki).mediaState.recv.sfuSessionId!==void 0)&&R(this,Ws,_i).call(this,{direction:"recv",state:as.CLOSED}),R(this,Pc,am).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}Fa=new WeakMap,rt=new WeakMap,it=new WeakMap,Ec=new WeakMap,bc=new WeakMap,Tn=new WeakMap,Ha=new WeakMap,wc=new WeakMap,qa=new WeakMap,yn=new WeakMap,js=new WeakMap,Gs=new WeakSet,ki=function(){return this.context.getValue("connectionHandler")},Pc=new WeakSet,am=function(){f(this,yn,{send:void 0,recv:void 0})},yu=new WeakSet,TT=async function(e){var o,c,d,l,u,h,g,v;So(this.context,"forceRelay")&&f(this,js,"relay"),this.logger.info(`ICE Transport Policy set to ${a(this,js)}`);const n=await Ht().getICEServers().catch(y=>(this.logger.warn(`failed to get iceservers from server: ${y.message}`),[]));e.send&&R(this,bu,ET).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(o=this.context.getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(l=(d=(c=this.context.getValue("defaults").mediaConfiguration)==null?void 0:c.audio)==null?void 0:d.enableHighBitrate)!=null?l:!1,enableStereo:(g=(h=(u=this.context.getValue("defaults").mediaConfiguration)==null?void 0:u.audio)==null?void 0:h.enableStereo)!=null?g:!1,enableDtx:!1},iceTransportPolicy:a(this,js)}),e.recv&&R(this,wu,bT).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(v=this.context.getValue("modules").e2ee)==null?void 0:v.enabled},iceTransportPolicy:a(this,js)})},kc=new WeakSet,om=async function(e){const{id:r,serverId:i,direction:n}=e;R(this,Pu,wT).call(this,e);try{return await _l(async(c,d)=>{c>0&&this.logger.info(`Retrying ${n} transport connect, count: ${c}`,{transport:{id:r,serverId:i,type:n}});try{if(e.closed)throw new Jr("Cannot reconnect closed transport");await R(this,Eu,yT).call(this,e)}catch(l){if(l instanceof Jr){this.logger.error(`Failed to connect ${n} transport. It will not be retried.`,{transport:e,error:l}),d(l);return}throw this.logger.error(`Failed to connect ${n} transport, retrying`,{transport:e,error:l}),l}},{delayTime:100,strategy:"exponential",maxRetryCount:15}),e}catch(o){throw this.logger.error(`Failed to connect ${n} transport after retries: ${e.id}. Transport reconnection will not be retried.`,{error:o,transport:{id:r,serverId:i,type:n}}),e.close(),e.removeAllListeners(),o}},Eu=new WeakSet,yT=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!a(this,Tn).isConnected)throw new Jr("Socket is not connected");if(e.connectionState==="closed")throw new Jr("Transport is closed");try{await e.connect(n=>R(this,ku,PT).call(this,i,n)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(n){throw a(this,qa).transportFailureCount[i]+=1,n.message==="ice connection failed"?new Jr(n.message):n}},bu=new WeakSet,ET=function(e){var r,i;if(a(this,rt)&&a(this,rt).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=a(this,rt))==null?void 0:r.id,serverId:(i=a(this,rt))==null?void 0:i.serverId,type:"send"}});return}f(this,rt,a(this,Fa).createTransport({...e,direction:"send"})),R(this,Ws,_i).call(this,{state:as.NEW,direction:"send",sfuSessionId:a(this,rt).serverId}),this.context.getValue("callstats").configureSendTransport(a(this,rt))},wu=new WeakSet,bT=function(e){var r,i;if(a(this,it)&&a(this,it).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=a(this,it))==null?void 0:r.id,serverId:(i=a(this,it))==null?void 0:i.serverId,type:"recv"}});return}f(this,it,a(this,Fa).createTransport({...e,direction:"recv"})),R(this,Ws,_i).call(this,{state:as.NEW,direction:"recv",sfuSessionId:a(this,it).serverId}),this.context.getValue("callstats").configureRecvTransport(a(this,it))},Pu=new WeakSet,wT=function(e){const{direction:r,id:i}=e;e.on("serveridchange",n=>{R(this,Ws,_i).call(this,{state:e.connectionState,direction:r,sfuSessionId:n})}),e.on("connectionstatechange",async n=>{R(this,Ws,_i).call(this,{state:n,direction:r,sfuSessionId:e.serverId}),this.logger.info(`Transport connection state changed to ${n} for ${r} transport`,{transport:{id:i,serverId:e.serverId,type:r,status:n}});const o=()=>{const c=a(this,yn)[r];c!==void 0&&(clearTimeout(c),a(this,yn)[r]=void 0)};switch(n){case"connected":o(),a(this,qa).lastConnectionTime=performance.now();break;case"disconnected":a(this,yn)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await R(this,_c,cm).call(this,e.direction)},mN);break;case"failed":if(e.closed)return;o(),this.logger.warn(`${r} transport is in failed state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await R(this,_c,cm).call(this,e.direction);break}}),e.on("icecandidate",async n=>{this.logger.debug("Sending iceCandidate:",{iceCandidate:n})})},ku=new WeakSet,PT=async function(e,r){const i=e==="recv";try{const{sdp:n,type:o}=r,c={consuming:i,description:{sdp:n,type:o,target:i?nr.SUBSCRIBER:nr.PUBLISHER},producers:[]};return a(this,Ha).connectTransport(c)}catch(n){throw this.logger.error(`Error in ${e} transport connection:`,{error:n}),n}},_c=new WeakSet,cm=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),a(this,Tn).isConnected&&a(this,qa).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),f(this,js,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:a(this,rt)}),this.context.getValue("peerSessionStore").emit(P.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:a(this,it)}),this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE);break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}const r=e==="send"?a(this,rt):a(this,it);R(this,Ws,_i).call(this,{state:as.CONNECTED,direction:e,sfuSessionId:r.serverId})},Ws=new WeakSet,_i=function(e){const{state:r,direction:i,sfuSessionId:n}=e;a(this,Gs,ki).mediaState[i]={state:r,sfuSessionId:n},this.context.getValue("peerSessionStore").emit(P.TRANSPORT_STATE_UPDATE,{transport:i,...a(this,Gs,ki).mediaState[i]})};class fN{constructor(t,e,r,i,n){m(this,_u,void 0);m(this,ms,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=n,f(this,_u,t),f(this,ms,t.getValue("logger"))}async create(t){if(!t||t&&t.length===0)throw new Error("List of producers is required");const e=new Map,r=[];t.forEach(d=>{const{producingPeerId:l,producerId:u,producingTransportId:h}=d,g={simulcast:{preferredRid:"f",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}};e.set(u,l),r.push({producingPeerId:l,producerId:u,producingTransportId:h,...g})});const i=await this.socketHandler.consume({requests:r,consumingTransportId:this.recvTransport.serverId}),n=new Map;t.forEach(d=>n.set(d.producerId,d));const o=new Map,c=[];return Object.entries(i.consumerStateMap).forEach(([d,l])=>{const u=n.get(d);if(!u)return;if(l.errorCode){a(this,ms).warn(`Consumer request failed for producer ${d}`,{error:{message:l.errorCode}}),c.push({...u,errorCode:l.errorCode});return}let h={};try{h=JSON.parse(l.producerState.appData)}catch(g){}try{const g=u.appData?JSON.parse(u.appData):{};g!=null&&g.e2ee&&Object.assign(h,{e2ee:g.e2ee})}catch(g){}o.set(d,{consumerId:l.consumerId,producingTransportId:u.producingTransportId,producingPeerId:u.producingPeerId,kind:u.kind,paused:u.pause,streamId:l.producerTrack.streamId,trackId:l.producerTrack.trackId,screenShare:u.screenShare,mimeType:u.mimeType,appData:h})}),{consumerStates:o,sessionDescription:i.sessionDescription,failedProducers:c}}async negotiate(t){try{a(this,ms).info("Negotiating socket consumer",{transport:this.recvTransport}),a(this,ms).debug(`[SDP] setting remote offer: ${JSON.stringify(t)} on recvTransport`,{transport:this.recvTransport});const e=await this.recvTransport.setRemoteOffer(t),r={transportId:this.recvTransport.serverId,description:{sdp:e.sdp,type:e.type,target:nr.SUBSCRIBER}};return a(this,ms).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,XC.toBinary(r)),a(this,ms).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){a(this,ms).error("Failed to renegotiate",{error:e});return}}async close(t){if(!t.length)return;const e=async(r,i)=>{const n=r.map(l=>l.localId);a(this,ms).info(`Closing consumers: ${JSON.stringify(n)}`);const o={description:{sdp:i.sdp,type:i.type,target:nr.SUBSCRIBER},consumerIds:n,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=PI.fromBinary(c).description;return{sdp:d.sdp,type:d.type}};await this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(t,e),"SocketConsumerStrategy.close",{consumersLength:t.length})}async switchConsumersToLayer(t,e){const r={requests:[],consumingTransportId:this.recvTransport.serverId},i=t.filter(n=>n&&n.id);i.forEach(({id:n,producingTransportId:o,localId:c})=>{r.requests.push({producerId:n,producingTransportId:o,mid:c,simulcast:{preferredRid:e===0?"q":"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}})}),await this.socketHandler.updateConsumersSimulcastConfig(r),a(this,ms).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:n})=>n)})}}_u=new WeakMap,ms=new WeakMap;class Mp{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return qi(t).media.filter(n=>e==="video"?n.type==="video":n.type==="audio").at(-1).msid}async create({offer:t,kind:e,paused:r,appData:i,codecOptions:n,producingTransportId:o}){var h,g;const c=Mp.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:nr.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(h=i.screenShare)!=null?h:!1,mimeType:(g=n==null?void 0:n[0])==null?void 0:g.mimeType,producingTransportId:o},{answer:l,producerId:u}=await this.socketHandler.produce(d);return{answer:l,producerId:u}}}function vN(s){try{const t=JSON.parse(s.message);if(typeof t!="object"||t===null)return{};const{errorCode:e,errorDescription:r}=t;return{...typeof e=="string"&&{errorCode:e},...typeof r=="string"&&{errorDescription:r}}}catch(t){return{}}}class SN extends gN{constructor(e,r){super(e,r);m(this,Rc);m(this,Ru);m(this,Iu);m(this,Au);m(this,Mu);m(this,En,void 0);m(this,Js,void 0);m(this,Cc,void 0);m(this,Ks,void 0);m(this,Cu,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});m(this,Rr,[]);m(this,ja,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{f(this,Cc,new Mp(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{f(this,Ks,new fN(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return a(this,En)}get consumers(){return a(this,Js)}get logger(){return this.context.getValue("logger")}reset(){f(this,En,new Map),f(this,Js,new Map)}async createProducer(e,r){var i,n,o,c,d;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const l=(n=(i=e.codecOptions)==null?void 0:i[0])==null?void 0:n.mimeType,u=await this.sendTransport.produce(e,R(this,Ru,kT).bind(this));return(o=e.appData)!=null&&o.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_PRODUCER,u),R(this,Iu,_T).call(this,u,r),this.logger.info(`Created ${(c=u.appData)!=null&&c.screenShare?"screenshare":"participant"} ${u.kind} producer ${u.id} for local peer on mid ${u.localId} with codec ${l}.`),u}catch(l){throw this.logger.error(`Failed to create ${((d=e==null?void 0:e.track)==null?void 0:d.kind)||"unknown"} producer`,{error:l}),a(this,Cu).producerCreationFailureCount+=1,l}}async closeProducer(e,r){var n,o;const i=this.producers.get(e);if(!i){this.logger.warn(`Producer with ID ${e} was not found`);return}r!=null&&r.stopTrack&&i.track.stop();try{await this.sendTransport.closeProducer(i),this.logger.info(`Closed ${(n=i.appData)!=null&&n.screenShare?"screenshare":"participant"} ${i.kind} producer ${e} of local peer on mid ${i.localId}. `),(o=this.context.getValue("modules").e2ee)!=null&&o.enabled&&this.context.getValue("peerSessionStore").emit(P.E2EE_INACTIVE_PRODUCER,i)}catch(c){this.logger.error("Failed to close producer on server",{error:c,producer:i})}}closeAllProducers(){return Promise.all(Array.from(a(this,En).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){a(this,ja)||clearTimeout(a(this,ja)),f(this,Rr,a(this,Rr).concat(e)),await R(this,Rc,dm).call(this)}removeClosedConsumers(e){return e.filter(r=>{const i=a(this,Js).get(r);return i!=null&&i.closed?(a(this,Js).delete(r),!0):!1})}async closeConsumers(e){if(!a(this,Ks))return;const r=e.map(i=>this.consumers.get(i)).filter(i=>i!==void 0);r.length!==0&&await a(this,Ks).close(r)}closeAllConsumers(){return this.closeConsumers(Array.from(a(this,Js).keys()))}async switchConsumersToLayer(e,r){a(this,Ks).switchConsumersToLayer(e,r)}}En=new WeakMap,Js=new WeakMap,Cc=new WeakMap,Ks=new WeakMap,Cu=new WeakMap,Rr=new WeakMap,ja=new WeakMap,Rc=new WeakSet,dm=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=a(this,Rr).splice(0,a(this,Rr).length);try{const i=new Set(Array.from(this.consumers.values()).map(({producerId:d})=>d)),n=r.filter(({producerId:d})=>!this.producers.get(d)&&!i.has(d));if(n.length===0)return;const{consumers:o,failedProducers:c}=await this.recvTransport.consume(n,R(this,Au,CT).bind(this),a(this,Ks).negotiate.bind(a(this,Ks)));if(o.forEach(R(this,Mu,RT).bind(this)),c!=null&&c.length){this.logger.error("Failed to create consumers for producers",{producers:c});const d=c.filter(({errorCode:l,producerId:u})=>l==="not_found_track_error"?(this.logger.error(`Track not found for producer: ${u}. This will not be retried.`),!1):l==="backend_error"?(this.logger.error("Unrecoverable error: backend error"),!1):!0);f(this,Rr,a(this,Rr).concat(d)),f(this,ja,setTimeout(R(this,Rc,dm).bind(this),e))}}catch(i){const n=i instanceof Error?i:new Error(String(i));this.logger.error("failed to consume on transport",{error:n});const{errorCode:o,errorDescription:c}=vN(n);if(o==="internal_error"&&c==="Backend error"||o==="invalid_session_description"){this.logger.error("Irrecoverable error, closing current recvTransport to create a new one",{transport:this.recvTransport,error:{code:o,message:c}});try{this.stopTransports({recv:!0})}catch(d){}await this.setupTransports({recv:!0})}}},Ru=new WeakSet,kT=function(e){return a(this,Cc).create(e)},Iu=new WeakSet,_T=function(e,r){e.on("close",async(i,n)=>{const{reason:o}=i,{offer:c}=i;if(this.logger.info("producer::closing",{debuggingHint:o,producer:{...e,status:"closing"}}),o!==Dl){const d={producerId:e.id,description:{sdp:c.sdp,type:c.type,target:nr.PUBLISHER}};try{const l=await this.socketHandler.closeProducer(d),u={sdp:l==null?void 0:l.sdp,type:l==null?void 0:l.type};this.logger.info("producer::closed",{producer:{...e,status:"closed"}}),n({answer:u})}catch(l){this.logger.error("producer close error",l)}}this.producers.delete(e.id),r()}),e.on("trackended",()=>{this.logger.info("producer::trackended",{producer:{...e,status:"UNKNOWN"}})}),a(this,En).set(e.id,e)},Au=new WeakSet,CT=async function(e){try{return await this.recvTransport.canConsume(),await a(this,Ks).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},Mu=new WeakSet,RT=function(e){e.on("close",async r=>{this.logger.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),a(this,Js).delete(e.id),this.context.getValue("peerSessionStore").emit(P.CONSUMER_CLOSED,{id:e.id})}),a(this,Js).set(e.id,e),this.context.getValue("peerSessionStore").emit(P.NEW_CONSUMER_CREATED,{id:e.id,appData:e.appData,peerId:e.peerId})};const Vu=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:r=3,hangoverFrames:i=5,noiseAdaptationRate:n=.95,voiceAdaptationRate:o=.99,minEnergyThreshold:c=.005,maxEnergyThreshold:d=.2,energyRatioThreshold:l=1.5,noiseHistorySize:u=50}={}){m(this,Ou);m(this,Du);m(this,Ic,void 0);m(this,Ac,void 0);m(this,Mc,void 0);m(this,Ga,void 0);m(this,Wa,void 0);m(this,Ja,void 0);m(this,Oc,void 0);m(this,Dc,void 0);m(this,Ka,void 0);m(this,xt,void 0);m(this,Rs,void 0);m(this,Is,!1);m(this,bn,0);m(this,wn,0);m(this,Ir,[]);m(this,Nc,void 0);f(this,Ga,t),f(this,xt,t),f(this,Ic,e),f(this,Ac,r),f(this,Mc,i),f(this,Wa,n),f(this,Ja,o),f(this,Oc,c),f(this,Dc,d),f(this,Ka,l),f(this,Nc,u),f(this,Rs,t/2)}get voiceDetected(){return a(this,Is)}processAudioChunk(t){var o,c;const e=R(o=Vu,Nu,MT).call(o,t),r=R(c=Vu,Lu,OT).call(c,t);return R(this,Ou,IT).call(this,e),e/a(this,Rs)>a(this,Ka)&&e>a(this,xt)&&r>a(this,Ic)?(f(this,bn,a(this,bn)+1),f(this,wn,a(this,Mc)),a(this,bn)>=a(this,Ac)&&f(this,Is,!0)):(f(this,bn,0),a(this,wn)>0?f(this,wn,a(this,wn)-1):a(this,Is)&&f(this,Is,!1),a(this,Is)||R(this,Du,AT).call(this,e)),{energy:e,isVoice:a(this,Is)}}reset(){f(this,Is,!1),f(this,bn,0),f(this,wn,0),f(this,xt,a(this,Ga)),f(this,Rs,a(this,Ga)/2),f(this,Ir,[])}getThresholdInfo(){return{currentEnergyThreshold:a(this,xt),backgroundNoiseEnergy:a(this,Rs),energyRatioThreshold:a(this,Ka)}}};let Oo=Vu;Ic=new WeakMap,Ac=new WeakMap,Mc=new WeakMap,Ga=new WeakMap,Wa=new WeakMap,Ja=new WeakMap,Oc=new WeakMap,Dc=new WeakMap,Ka=new WeakMap,xt=new WeakMap,Rs=new WeakMap,Is=new WeakMap,bn=new WeakMap,wn=new WeakMap,Ir=new WeakMap,Nc=new WeakMap,Ou=new WeakSet,IT=function(t){a(this,Is)?f(this,xt,a(this,Ja)*a(this,xt)+(1-a(this,Ja))*t):f(this,xt,a(this,Wa)*a(this,xt)+(1-a(this,Wa))*a(this,Rs)),f(this,xt,Math.max(a(this,Oc),Math.min(a(this,Dc),a(this,xt))))},Du=new WeakSet,AT=function(t){if(t<a(this,xt)*1.2)if(a(this,Ir).push(t),a(this,Ir).length>a(this,Nc)&&a(this,Ir).shift(),a(this,Ir).length>=10){const e=[...a(this,Ir)].sort((i,n)=>i-n),r=Math.floor(e.length/2);f(this,Rs,e[r])}else f(this,Rs,.95*a(this,Rs)+.05*t)},Nu=new WeakSet,MT=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Lu=new WeakSet,OT=function(t){let e=0;for(let r=1;r<t.length;r+=1)(t[r]>=0&&t[r-1]<0||t[r]<0&&t[r-1]>=0)&&(e+=1);return e},m(Oo,Nu),m(Oo,Lu);class oS{constructor(t){p(this,"RNAudioSampleHandler");m(this,Lc,void 0);f(this,Lc,t);const{RNAudioSampleHandlerImpl:e}=navigator;e==null||e.init().then(r=>{this.RNAudioSampleHandler=r}).catch(r=>{this.logger.error("ReactNativeAudioSampler: Failed to initialize audio sampler",r)})}get logger(){return a(this,Lc).getValue("logger")}get samples(){var e;const t=new Float32Array(1024);return(e=this.RNAudioSampleHandler)==null||e.getFloatTimeDomainData(t),t}stop(){var t;(t=this.RNAudioSampleHandler)==null||t.destructor()}}Lc=new WeakMap;class cS{constructor(t){p(this,"audioContext");p(this,"analyser");m(this,Vc,void 0);f(this,Vc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return a(this,Vc).getValue("logger")}get samples(){if(this.audioContext.state==="suspended")try{this.audioContext.resume()}catch(e){this.logger.error("AudioContextSampler: Failed to resume audio context",e)}const t=new Float32Array(this.analyser.frequencyBinCount);return this.analyser.getFloatTimeDomainData(t),t}set audioTrack(t){const e=new MediaStream;e.addTrack(t),this.audioContext.createMediaStreamSource(e).connect(this.analyser)}}Vc=new WeakMap;class dS{static setInterval(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setInterval(t,e,...r):global.setInterval(t,e,...r)}static clearInterval(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearInterval(t):global.clearInterval(t)}static setTimeout(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setTimeout(t,e,...r):global.setTimeout(t,e,...r)}static clearTimeout(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearTimeout(t):global.clearTimeout(t)}}const TN=60,yN=400,Fc=class{constructor(t,e){m(this,$c);m(this,xu);m(this,Bc);m(this,Ar,void 0);m(this,Mr,void 0);m(this,Or,void 0);m(this,xc,void 0);m(this,za,void 0);m(this,Ya,void 0);m(this,gi,void 0);m(this,Pn,void 0);m(this,Qa,void 0);m(this,kn,void 0);m(this,Dr,void 0);m(this,zs,void 0);this.reportRequest=e,f(this,kn,t),f(this,Ya,new Oo);const{isReactNative:r}=navigator;f(this,Dr,r?new oS(a(this,kn)):new cS(a(this,kn))),f(this,zs,r?dS:gp)}get logger(){return a(this,kn).getValue("logger")}set producerId(t){f(this,Or,t)}set audioTrack(t){f(this,xc,t),a(this,Dr)instanceof cS&&(a(this,Dr).audioTrack=t)}start(t=!1){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter of audio producer ${a(this,Or)}.`),a(this,Ar)&&a(this,zs).clearInterval(a(this,Ar)),f(this,Ar,a(this,zs).setInterval(R(this,$c,lm).bind(this),TN)),a(this,Mr)&&a(this,zs).clearInterval(a(this,Mr)),f(this,Mr,a(this,zs).setInterval(R(this,Bc,hm).bind(this),yN)),t&&(R(this,$c,lm).call(this),R(this,Bc,hm).call(this))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter of audio producer ${a(this,Or)}`),a(this,Ar)&&(a(this,zs).clearInterval(a(this,Ar)),f(this,Ar,void 0)),a(this,Mr)&&(a(this,zs).clearInterval(a(this,Mr)),f(this,Mr,void 0))}catch(t){}a(this,Ya).reset(),a(this,Dr)instanceof oS&&a(this,Dr).stop()}};let Do=Fc;Ar=new WeakMap,Mr=new WeakMap,Or=new WeakMap,xc=new WeakMap,za=new WeakMap,Ya=new WeakMap,gi=new WeakMap,Pn=new WeakMap,Qa=new WeakMap,kn=new WeakMap,Dr=new WeakMap,zs=new WeakMap,$c=new WeakSet,lm=function(){var i;if(!a(this,xc)||!a(this,Or))return;const{energy:t}=R(this,xu,DT).call(this),e=R(i=Fc,Uc,um).call(i,t);let r=.9;a(this,Qa)!==e&&a(this,Qa)?r=.9:e?r=.3:r=.5,f(this,za,(a(this,za)||0)*(1-r)+t*r)},xu=new WeakSet,DT=function(){var o;const{samples:t}=a(this,Dr),{energy:e,isVoice:r}=a(this,Ya).processAudioChunk(t),i=R(o=Fc,$u,NT).call(o,e);return i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,gi)||i<a(this,gi))&&f(this,gi,i),(!a(this,Pn)||i>a(this,Pn))&&f(this,Pn,i),{energy:(i-a(this,gi))/(a(this,Pn)-a(this,gi))*10||0,isVoice:r})},Uc=new WeakSet,um=function(t){return t<5},Bc=new WeakSet,hm=function(t=a(this,za)){var r;if(!a(this,Or)||!t)return;const e={producerId:a(this,Or),energy:Math.round(t),silent:R(r=Fc,Uc,um).call(r,t)};f(this,Qa,e.silent),this.reportRequest(e)},$u=new WeakSet,NT=function(t){const e=Math.log10(t);return Math.round(e)},m(Do,Uc),m(Do,$u);var EN=Object.defineProperty,bN=Object.getOwnPropertyDescriptor,he=(s,t,e,r)=>{for(var i=r>1?void 0:r?bN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&EN(t,e,i),i};class de{constructor(t,e){m(this,Vr);m(this,fi);m(this,Gc);m(this,Bu);m(this,Fu);m(this,Hu);m(this,Wc);m(this,qu);m(this,ju);m(this,lt);m(this,Rn);m(this,Jc);m(this,Gu);m(this,Wu);m(this,Ju);p(this,"context");p(this,"authToken");p(this,"e2ee");m(this,Hc,void 0);m(this,qc,void 0);m(this,nt,void 0);m(this,H,void 0);m(this,Uu,void 0);m(this,_t,void 0);m(this,Nr,void 0);m(this,_n,void 0);m(this,Cn,void 0);m(this,jc,void 0);m(this,Qt,null);m(this,Lr,void 0);m(this,Ct,void 0);m(this,Rt,void 0);var i,n;this.context=t;const{socket:r}=e;this.mediaJoined=!1,f(this,nt,r),f(this,Nr,!1),f(this,H,new SN(t,r)),f(this,_t,a(this,H).events),f(this,Lr,new Set),f(this,Ct,new Map),f(this,_n,!1),f(this,Cn,new kp(t.getValue("logger"))),f(this,Rt,new Do(this.context,a(this,H).socketHandler.audioActivity.bind(a(this,H).socketHandler))),this.e2ee=(n=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,jc,Ah(async()=>{if(!a(this,Vr,xn).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(a(this,qc),a(this,Hc),!0);o&&(this.context.getValue("peerSessionStore").emit(P.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_RECONNECTED))},5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get mediaJoined(){return a(this,Vr,xn).mediaJoined}set mediaJoined(t){a(this,Vr,xn).mediaJoined=t}reset({resetTransportQueue:t}){this.logger.info(`Resetting media node client: closing all transports, producers, consumers, and queues(resetTransportQueue: ${t}).`),a(this,H).closeAllProducers(),a(this,H).closeAllConsumers(),a(this,Ct).clear(),a(this,Lr).clear(),f(this,Qt,null),t&&a(this,Cn).stop(),a(this,H).stopAllTransports(),a(this,H).reset(),t&&f(this,Cn,new kp)}async joinRoom(t,e,r=!1,i={}){a(this,Vr,xn).mediaJoinAttempted=!0,f(this,Nr,!0);const n=this.peerId;try{const o=await a(this,Cn).push(()=>R(this,Bu,LT).call(this,t,e,r,i),"joinRoom");return o.roomJoined||R(this,Gc,pm).call(this,n),o}catch(o){return this.logger.error("Error in room joining process",{error:o}),R(this,Gc,pm).call(this,n),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_FAILED),{roomJoined:!1,error:o}}}async initializeConnection(t,e,r=!1,i={}){return a(this,Qt)?a(this,Qt):(f(this,Qt,(async()=>{try{await R(this,Wc,mm).call(this,t,e,r,i)}catch(n){throw f(this,Qt,null),n}})()),a(this,Qt))}getConsumers(){return a(this,H).consumers}getProducers(){return a(this,H).producers}handoverPeerProducers(t,e){const r=new Set(e);return Array.from(a(this,H).consumers.values()).filter(i=>r.has(i.producerId)?(i.reassignPeer(t),!0):!1)}async leaveRoom(){var r;(r=a(this,Rt))==null||r.stop(),a(this,H).stopAllTransports(),f(this,_n,!1),a(this,Vr,xn).mediaJoinAttempted=!1;const t={closeRoom:!1};try{a(this,nt).sendMessage(a(this,_t).leaveRoom,wR.toBinary(t))||this.logger.warn("MediaNodeClient.leaveRoom: media leave was not sent")}catch(i){this.logger.error("MediaNodeClient.leaveRoom: media leave failed",{error:i})}this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct().catch(i=>{this.logger.error("leaveRoom::telemetry_destruct_failed",{error:i})})}async activatePeers(t){return this.createConsumers(t)}async createConsumers(t){return t.length===0?Promise.resolve():a(this,H).createConsumers(t)}removeClosedConsumers(t){return a(this,H).removeClosedConsumers(t)}async closeConsumersById(t){t.length&&await a(this,H).closeConsumers(t)}async _shareWebcam(t){var u,h,g,v;const e=_e.WEBCAM,r=R(this,lt,Mt).call(this,e);if(r){const y=await r;if(a(this,H).producers.has(y)){const k=a(this,H).producers.get(y);if(!k.closed)return await k.replaceTrack({track:t}),await this.resumeWebcam(e),t;await this.disableWebcam()}return this._shareWebcam(t)}const i=R(this,Ju,HT).call(this,t),n=So(this.context,"disableSimulcast"),o=(h=(u=this.context)==null?void 0:u.getValue("overrides"))==null?void 0:h.simulcastConfig;n||o&&o.disable||!((v=(g=this.context)==null?void 0:g.getValue("theme"))!=null&&v.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),i.encodings=t1(this.context,t),this.logger.info(`Simulcast encodings: ${JSON.stringify(i.encodings)}`));const d=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,Ct).delete(e)},l=a(this,H).createProducer(i,d);return R(this,Rn,Cd).call(this,e,l.then(y=>y.id)),l.then(y=>y.track)}async shareWebcam(t){return t===void 0?null:this._shareWebcam(t)}async shareScreen(t){const{video:e,audio:r}=t;if(e===void 0)return;const i=await R(this,lt,Mt).call(this,_e.SCREENSHARE_VIDEO),n=await R(this,lt,Mt).call(this,_e.SCREENSHARE_AUDIO),o=a(this,H).producers.get(i),c=a(this,H).producers.get(n),d=[];if(o&&!o.closed)d.push(o.replaceTrack({track:e}));else{const l={track:e,codecOptions:[{mimeType:a(this,fi,ro).screenshareVideo}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Pe.isElectron()},stopTracks:!1},u=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,Ct).delete(_e.SCREENSHARE_VIDEO),a(this,Ct).delete(_e.SCREENSHARE_AUDIO)},h=a(this,H).createProducer(l,u);R(this,Rn,Cd).call(this,_e.SCREENSHARE_VIDEO,h.then(g=>g.id)),d.push(h)}if(r)if(c&&!c.closed)d.push(c.replaceTrack({track:r}));else{const l={track:r,codecOptions:[{mimeType:a(this,fi,ro).screenshareAudio}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Pe.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},u=()=>{},h=a(this,H).createProducer(l,u);R(this,Rn,Cd).call(this,_e.SCREENSHARE_AUDIO,h.then(g=>g.id)),d.push(h)}else n&&(R(this,Jc,gm).call(this,_e.SCREENSHARE_AUDIO),d.push(a(this,H).closeProducer(n)));await Promise.all(d),this.context.getValue("callstats").screenShareStart()}async shareMic(t){try{if(t===void 0)throw new Nt("track undefined");const e=R(this,lt,Mt).call(this,_e.MIC);if(e){const o=await e;if(a(this,H).producers.has(o)){const c=a(this,H).producers.get(o);if(!c.closed){await c.replaceTrack({track:t}),await this.resumeMic(),a(this,Rt)&&(a(this,Rt).audioTrack=t,a(this,Rt).producerId=o,a(this,Rt).start(!0));return}await a(this,H).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=R(this,Wu,FT).call(this,t),i=()=>{a(this,Ct).delete(_e.MIC)},n=a(this,H).createProducer(r,i);R(this,Rn,Cd).call(this,_e.MIC,n.then(o=>o.id)),await n.then(o=>{a(this,Rt)&&(a(this,Rt).audioTrack=o.track,a(this,Rt).producerId=o.id,a(this,Rt).start())})}catch(e){throw new C(e)}}async pauseMic(){var i;const t=await R(this,lt,Mt).call(this,_e.MIC),e=a(this,H).producers.get(t);if(!e){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(e.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}e.pause(),(i=a(this,Rt))==null||i.stop();const r={producerId:e.id,pause:!0};a(this,nt).sendMessage(a(this,_t).toggleProducer,cl.toBinary(r)),this.logger.info(`Paused mic producer ${e.id} of local peer ${this.peerId}. Remote peers will stop hearing this peer.`)}async pauseWebcam(){const t=await R(this,lt,Mt).call(this,_e.WEBCAM),e=a(this,H).producers.get(t);if(!e){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}e.pause();const r={producerId:e.id,pause:!0};a(this,nt).sendMessage(a(this,_t).toggleProducer,cl.toBinary(r)),this.logger.info(`Paused webcam producer ${e.id} of local peer ${this.peerId}. Remote peers will stop seeing this peer.`)}async resumeMic(){const t=await R(this,lt,Mt).call(this,_e.MIC),e=a(this,H).producers.get(t);if(!e){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,nt).sendMessage(a(this,_t).toggleProducer,cl.toBinary(r)),this.logger.info(`Resumed mic producer ${e.id} of local peer ${this.peerId}. Remote peers will start hearing this peer.`)}async resumeWebcam(t=_e.WEBCAM){const e=await R(this,lt,Mt).call(this,t),r=a(this,H).producers.get(e);if(!r){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!r.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}r.resume(),r.appData.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};a(this,nt).sendMessage(a(this,_t).toggleProducer,cl.toBinary(i)),this.logger.info(`Resumed webcam producer ${r.id} of local peer ${this.peerId}. Remote peers will start seeing this peer.`)}async disableWebcam(){const t=_e.WEBCAM,e=await R(this,lt,Mt).call(this,t);R(this,Jc,gm).call(this,t),e&&await a(this,H).closeProducer(e)}async disableMic(){var e;const t=await R(this,lt,Mt).call(this,_e.MIC);t&&await a(this,H).closeProducer(t),(e=a(this,Rt))==null||e.stop(),a(this,Ct).delete(_e.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await R(this,lt,Mt).call(this,_e.SCREENSHARE_VIDEO),e=await R(this,lt,Mt).call(this,_e.SCREENSHARE_AUDIO);t&&await a(this,H).closeProducer(t),e&&await a(this,H).closeProducer(e),a(this,Lr).clear(),a(this,Ct).delete(_e.SCREENSHARE_VIDEO),a(this,Ct).delete(_e.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await R(this,lt,Mt).call(this,_e.WEBCAM);await a(this,H).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await R(this,lt,Mt).call(this,_e.SCREENSHARE_VIDEO);await a(this,H).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:e})}}async changeDisplayName(t,e){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!await a(this,H).socketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}kick(t){const e={peerIds:[t]};a(this,H).socketHandler.kickPeer(e)}kickAll(){a(this,H).socketHandler.kickAll()}async muteAll(t){if(!await a(this,H).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await a(this,H).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await a(this,H).socketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await a(this,H).socketHandler.hostControlForPeer(t,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(t){const e={participantId:t!=null?t:""};try{await a(this,nt).sendMessagePromise(a(this,_t).globalPinPeer,xR.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&a(this,H).producers.get(t.producerId)&&a(this,Lr).add(t.consumerPeerId),a(this,Lr).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));a(this,H).switchConsumersToLayer(r,e)}async handleSocketEvents(){a(this,nt).on(a(this,_t).peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{R(this,Gu,BT).call(this,BI.fromBinary(t))}catch(e){this.logger.error("error in peer-producer-create-broadcast",{error:e})}}),a(this,nt).on(a(this,_t).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const e=iv.fromBinary(t),{participantId:r,initiatorParticipantId:i,producerState:{kind:n,pause:o,producerId:c,screenShare:d}}=e;if(d)return;const l=n===Ns.AUDIO?"audio":"video";if(this.logger.info(`Received participant ${l} producer ${o?"paused":"resumed"} broadcast for ${r===this.peerId?"local":"remote"} producer ${c} of peer ${r}. payload: ${iv.toJsonString(e)}`),r===this.peerId&&i!==this.peerId&&o&&(this.logger.info(`${i?`Remote peer ${i}`:"Kick/Kick-all api"} has paused the ${l==="audio"?"audio":"video"} feed of local peer ${this.peerId}. Reconciling the local state.`),this.context.getValue("peerSessionStore").emit(l==="audio"?P.MUTE_SELF:P.MUTE_SELF_VIDEO)),r===this.peerId)return;this.context.getValue("peerSessionStore").emit(P.PRODUCER_TOGGLE,{peerId:r,producerId:c,paused:o,kind:l}),Array.from(this.getConsumers().values()).filter(h=>h.producerId===c).forEach(h=>{h.kind==="video"&&o||h.paused!==o&&(this.logger.debug(`consumer state mismatched for ${h.id}. updating consumer pause state ${h.paused} to ${o}`),o?(h.pause(),this.context.getValue("peerSessionStore").emit(P.CONSUMER_PAUSED,{id:h.id})):(h.resume(),this.context.getValue("peerSessionStore").emit(P.CONSUMER_RESUMED,{id:h.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),a(this,nt).on(a(this,_t).peerLeaveBroadcast,async({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=Gh.fromBinary(t);if(e===this.peerId)return;this.logger.info(`Received peer left broadcast of remote peer ${e}`),a(this,Lr).delete(e),this.context.getValue("peerSessionStore").emit(P.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast of remote peer",{error:e})}}),a(this,nt).on(a(this,_t).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=qI.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(P.PRODUCER_CLOSED,{peerId:e,producerId:r})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),a(this,nt).on(a(this,_t).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,Nr)&&!a(this,_n)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_DISCONNECTED),a(this,jc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=a(this,H).consumers.get(r);i&&this.context.getValue("peerSessionStore").emit(P.CONSUMER_SCORE_UPDATE,{id:r,kind:i.kind,peerId:i.peerId,score:e.score,scoreStats:e})})}),this.context.getValue("callstats").onProducerScore(t=>{t.forEach((e,r)=>{const i=Array.from(a(this,H).producers.values()).find(n=>n.id===r);i&&this.context.getValue("peerSessionStore").emit(P.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:e.score,scoreStats:e})})})}}Hc=new WeakMap,qc=new WeakMap,nt=new WeakMap,H=new WeakMap,Uu=new WeakMap,_t=new WeakMap,Nr=new WeakMap,_n=new WeakMap,Cn=new WeakMap,jc=new WeakMap,Qt=new WeakMap,Lr=new WeakMap,Ct=new WeakMap,Rt=new WeakMap,Vr=new WeakSet,xn=function(){return this.context.getValue("connectionHandler")},fi=new WeakSet,ro=function(){var t;return(t=this.context.getValue("mediaProducerCodecs"))!=null?t:iS},Gc=new WeakSet,pm=function(t){this.mediaJoined=!1,f(this,Nr,!1),a(this,nt).isConnected&&this.peerId===t&&this.context.getValue("peerSessionStore").emit(P.MEDIA_ROOM_JOIN_FAILED)},Bu=new WeakSet,LT=async function(t,e,r,i){var o;f(this,qc,t);let n=!1;if(r){const{recv:c,send:d}=(o=a(this,Vr,xn).mediaState)!=null?o:{};(d==null?void 0:d.state)===as.CONNECTED&&(c==null?void 0:c.state)===as.CONNECTED?(this.logger.info("MediaNodeClient.joinRoom: transports healthy — preserving all producers for ownership handover"),f(this,Qt,null),n=!0):(this.logger.info("MediaNodeClient.joinRoom: transports unhealthy — full reset"),this.reset({resetTransportQueue:!1}))}try{a(this,Qt)?await a(this,Qt):await R(this,Wc,mm).call(this,t,e,r,i,n),R(this,Hu,xT).call(this,e);const{joined:c,error:d}=await R(this,Fu,VT).call(this);return{roomJoined:c,error:d}}catch(c){return this.logger.error("Failed to complete room join",{error:c}),{roomJoined:!1,error:c}}finally{f(this,Qt,null)}},Fu=new WeakSet,VT=async function(){const t=this.peerId;try{this.mediaJoined=!0;const{roomState:e}=await _l(async(r,i)=>{if(!a(this,nt).isConnected||this.peerId!==t){const n=new Error("Media room join completion superseded by a newer connection");throw i(n),n}return r>0&&this.logger.warn(`Retrying media room join completion for peer ${t}: attempt=${r+1}`),a(this,H).socketHandler.notifySelfJoinComplete()},{strategy:"exponential",maxRetryCount:3,delayTime:1e3});return f(this,Hc,e.roomUuid),f(this,_n,!0),f(this,Nr,!1),{joined:!0}}catch(e){return this.logger.error("Error completing room join",{error:e}),this.mediaJoined=!1,f(this,Nr,!1),{joined:!1,error:e}}},Hu=new WeakSet,xT=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const r={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:{...Pe.getDeviceInfo(),userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency},sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};this.context.getValue("callstats").roomJoined(r)}catch(e){this.logger.error("Error reporting room joined analytics",{error:e})}},0)},Wc=new WeakSet,mm=async function(t,e,r,i,n=!1){try{const o=R(this,qu,$T).call(this);await R(this,ju,UT).call(this,t,e,r,o),n?this.logger.info("MediaNodeClient: reusing existing transports on rejoin"):await a(this,H).setupTransports({send:!0,recv:!0})}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},qu=new WeakSet,$T=function(){const t=Z1(a(this,fi,ro));return f(this,Uu,t),t},ju=new WeakSet,UT=async function(t,e,r,i){await _l(async(n,o)=>{if(!a(this,nt).isConnected){o(new Error("Socket is not connected"));return}n>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${n}`});try{await a(this,H).socketHandler.joinRoom(e,t,i,r)}catch(c){throw this.logger.error("Failed to send joinRoom message after retries",{error:c}),c}},{delayTime:1e3,strategy:"exponential",maxRetryCount:15})},lt=new WeakSet,Mt=function(t){return a(this,Ct).get(t)},Rn=new WeakSet,Cd=function(t,e){return a(this,Ct).set(t,e)},Jc=new WeakSet,gm=function(t){return a(this,Ct).delete(t)},Gu=new WeakSet,BT=function({participantId:t,producerState:e}){var i;if(t===this.peerId||!e)return;this.logger.info(`Received remote ${e.screenShare?"screenshare":"participant"} ${e.kind===Ns.AUDIO?"audio":"video"} producer created broadcast for peer ${t} with producer state ${JSON.stringify(e)}.`);const r=(i=e.mimeType)!=null?i:e.kind===Ns.AUDIO?"audio/opus":"video/VP8";this.context.getValue("peerSessionStore").emit(P.NEW_PRODUCER,{peerId:t,producer:{...e,mimeType:r,kind:e.kind===Ns.AUDIO?"audio":"video",producingPeerId:t}})},Wu=new WeakSet,FT=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{mimeType:a(this,fi,ro).audio}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},Ju=new WeakSet,HT=function(t){return{track:t,codecOptions:[{mimeType:a(this,fi,ro).video}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},he([E.trace("MediaNodeClient.reset")],de.prototype,"reset",1),he([E.trace("MediaNodeClient.joinRoom")],de.prototype,"joinRoom",1),he([E.trace("MediaNodeClient.leaveRoom")],de.prototype,"leaveRoom",1),he([E.trace("MediaNodeClient.activatePeers")],de.prototype,"activatePeers",1),he([E.trace("MediaNodeClient.createConsumers")],de.prototype,"createConsumers",1),he([E.trace("MediaNodeClient.closeConsumersById")],de.prototype,"closeConsumersById",1),he([E.trace("MediaNodeClient._shareWebcam")],de.prototype,"_shareWebcam",1),he([E.trace("MediaNodeClient.shareWebcam")],de.prototype,"shareWebcam",1),he([E.trace("MediaNodeClient.shareScreen")],de.prototype,"shareScreen",1),he([E.trace("MediaNodeClient.shareMic")],de.prototype,"shareMic",1),he([E.trace("MediaNodeClient.pauseMic")],de.prototype,"pauseMic",1),he([E.trace("MediaNodeClient.pauseWebcam")],de.prototype,"pauseWebcam",1),he([E.trace("MediaNodeClient.resumeMic")],de.prototype,"resumeMic",1),he([E.trace("MediaNodeClient.resumeWebcam")],de.prototype,"resumeWebcam",1),he([E.trace("MediaNodeClient.disableWebcam")],de.prototype,"disableWebcam",1),he([E.trace("MediaNodeClient.disableMic")],de.prototype,"disableMic",1),he([E.trace("MediaNodeClient.disableScreenShare")],de.prototype,"disableScreenShare",1),he([E.trace("MediaNodeClient.muteSelf")],de.prototype,"muteSelf",1),he([E.trace("MediaNodeClient.resetVideoProducers")],de.prototype,"resetVideoProducers",1),he([E.trace("MediaNodeClient.changeDisplayName")],de.prototype,"changeDisplayName",1),he([E.trace("MediaNodeClient.kickPeer")],de.prototype,"kick",1),he([E.trace("MediaNodeClient.kickAllPeers")],de.prototype,"kickAll",1),he([E.trace("MediaNodeClient.muteAll")],de.prototype,"muteAll",1),he([E.trace("MediaNodeClient.muteAllVideo")],de.prototype,"muteAllVideo",1),he([E.trace("MediaNodeClient.disableAudio")],de.prototype,"disableAudio",1),he([E.trace("MediaNodeClient.disableVideo")],de.prototype,"disableVideo",1),he([E.trace("MediaNodeClient.pinPeer")],de.prototype,"pinPeer",1),he([E.trace("MediaNodeClient.validateScreenShare")],de.prototype,"validateScreenShare",1);function lS(s,t){const e=s.getValue("roomNodeClient");if(e){if(e)return e;throw new Error("Room node client already set up.")}const r=new de(s,t);return s.setValue("roomNodeClient",r),r}function wN(s){const t=s.getValue("roomNodeClient");try{t==null||t.leaveRoom()}catch(e){s.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}s.setValue("roomNodeClient",void 0)}var PN=Object.defineProperty,kN=Object.getOwnPropertyDescriptor,ji=(s,t,e,r)=>{for(var i=r>1?void 0:r?kN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&PN(t,e,i),i};const uS=(tT=class{constructor(s,t,e,r){m(this,ft);p(this,"self");p(this,"authToken");m(this,Xa,void 0);p(this,"viewType");m(this,gs,void 0);m(this,te,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,f(this,te,s),this.viewType=r,this.authToken=n,f(this,Xa,i),f(this,gs,e),this.setupEvents()}get peerId(){return a(this,te).getValue("peerId")}get telemetry(){return a(this,te).getValue("telemetry")}get logger(){return a(this,te).getValue("logger")}get mediaJoined(){return a(this,te).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const n=Ht(),o=!!s.getValue("cachedUserDetails"),c=await ze.__init__(s,e,r,i,i.name,o);s.setValue("self",c);const d=s.getValue("logger");return navigator.product!=="ReactNative"?setTimeout(async()=>{const u=await c.getAllDevices();d.info("populated_full_device_list",{devices:JSON.stringify(u)}),s.getValue("callstats").devices("AUDIO",u==null?void 0:u.filter(h=>h.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",u==null?void 0:u.filter(h=>h.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",u==null?void 0:u.filter(h=>h.kind==="audiooutput")),d.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:s.getValue("peerId"),engineName:Pe.getDeviceInfo().engineName,env:s.getValue("env")==="prod"?"prod":"devel",iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:{},logger:d,apiHostnames:H_(s),skipConnectivityChecks:!0,authToken:s.getValue("authToken")}),t.socket.updateCallstatsPeerId(s.getValue("peerId")),d.info("Callstats:: initialized")}catch(h){d.error("Callstats:: initialization failed",{error:h})}},0):d.info("Callstats:: Skipped initialization due to navigator product being ReactNative."),new uS(s,c,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:n,screenShareTracks:o}=this.self;if(e.canProduceAudio===G.Allowed&&r)if((s==null?void 0:s.readyState)==="live")try{await a(this,ft,Ut).shareMic(s),this.self.audioEnabled||a(this,ft,Ut).pauseMic()}catch(d){this.self.disableAudio()}else this.logger.warn("shareMediaTracks: audio track is dead, disabling audio"),this.self.disableAudio();if(e.canProduceVideo===G.Allowed&&i)if((t==null?void 0:t.readyState)==="live")try{await a(this,ft,Ut).shareWebcam(t),this.self.videoEnabled||a(this,ft,Ut).pauseWebcam()}catch(d){this.self.disableVideo()}else this.logger.warn("shareMediaTracks: video track is dead, disabling video"),this.self.disableVideo();if(e.canProduceScreenshare===G.Allowed&&n){const d=o.video,l=o.audio;if((d==null?void 0:d.readyState)==="live")try{await((c=a(this,ft,Ut))==null?void 0:c.shareScreen({video:d,audio:(l==null?void 0:l.readyState)==="live"?l:void 0}))}catch(u){this.self.disableScreenShare()}else this.logger.warn("shareMediaTracks: screenshare video track is dead, disabling screenshare"),this.self.disableScreenShare()}}async kickHandler(s){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)}waitlistedHandler(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}async resetSelf(s){var r;const{wasSocketJoinAttempted:t,wasMediaJoinAttempted:e}=s;a(this,te).getValue("callstats").callEnded(),t||e?(this.logger.info(`Resetting Self post reconnect. Peer has earlier tried joining the ${e?"media room":"socket room only"}. Not closing transports.`),await this.joinRoom({reconnected:!0,joinAttempts:s})):(this.logger.info("Resetting Self post reconnect. User never joined the room so doing full reset."),(r=a(this,ft,Ut))==null||r.reset({resetTransportQueue:!0}))}setupEvents(){a(this,te).getValue("peerSessionStore").on(P.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&await this.shareMediaTracks()}),a(this,te).getValue("peerSessionStore").on(P.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,te).getValue("peerSessionStore").on(P.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,te).getValue("peerSessionStore").on(P.ROOM_NODE_FAILED,()=>{this.logger.error("Room node failed. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,te).getValue("peerSessionStore").on(P.SOCKET_SERVICE_RECONNECTED,s=>{!s.wasSocketJoinAttempted&&!s.wasMediaJoinAttempted&&(this.self.roomState="init"),this.resetSelf(s).catch(t=>{this.logger.error("Failed to reset self after socket reconnection",{error:t})})}),a(this,te).getValue("peerSessionStore").on(P.SOCKET_SERVICE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,te).getValue("peerSessionStore").on(P.SOCKET_SERVICE_FAILED,()=>{this.logger.error("Socket reconnection failed after exhausting all attempts. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,gs).on(x.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,gs).on(gl.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,te).getValue("peerSessionStore").emit(P.UPDATE_PERMISSIONS,t.patch)})}),a(this,gs).on(x.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,gs).on(x.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,gs).on(x.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,te).getValue("peerSessionStore").onAsync(P.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,te).getValue("peerSessionStore").on(P.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var n;const i=(n=e==null?void 0:e.screenShare)!=null?n:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),a(this,te).getValue("peerSessionStore").on(P.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,te).getValue("callstats").audioOff())}),a(this,te).getValue("peerSessionStore").on(P.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,te).getValue("callstats").videoOff())}),a(this,te).getValue("peerSessionStore").onAsync(P.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,te).getValue("peerSessionStore").on(P.PIP_HANGUP,this.leaveRoom.bind(this))}async joinSocketRoomWithRetry(){const s=this.self.id;return _l(async(t,e)=>{if(!a(this,Xa).isConnected||this.self.id!==s){const i=new Error("Socket room join superseded by a newer connection");throw e(i),i}t>0&&this.logger.warn(`Retrying socket room join for peer ${s}: attempt=${t+1}`);const r=await a(this,gs).joinRoom(this.self);if(this.self.id!==s){const i=new Error("Socket room join completed for a superseded peer ID");throw e(i),i}return r},{strategy:"exponential",maxRetryCount:3,delayTime:1e3})}async joinRoom({reconnected:s=!1,joinAttempts:t}={}){var e,r;try{this.logger.info("Local peer is joining socket room.");const{peer:i}=await this.joinSocketRoomWithRetry();this.logger.info("Local peer has joined socket room."),a(this,gs).socket.flush();const n=lp(i.stageType);if(a(this,te).setValue("stageStatus",n,!1),i.waitlisted){this.logger.info("Peer was waitlisted. Skipped joining media room."),s&&(this.logger.info("Peer reconnected while waitlisted. Resetting media node client."),(e=a(this,ft,Ut))==null||e.reset({resetTransportQueue:!0})),this.waitlistedHandler();return}}catch(i){throw this.logger.error("SelfController.joinRoom: socket join failed",{error:i}),new C("Check the network and try again.","0002")}if(this.viewType===Ss.Livestream&&(t!=null&&t.wasSocketJoinAttempted)&&!t.wasMediaJoinAttempted&&a(this,te).getValue("stageStatus")!=="ON_STAGE"){this.logger.info("Local livestream peer that only joined the socket room is not ON_STAGE. Closing transports, if any."),(r=a(this,ft,Ut))==null||r.reset({resetTransportQueue:!0}),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s}),a(this,te).notify("stageStatus");return}try{this.logger.info("Local peer is joining media room."),await this.joinMediaRoom(s),this.logger.info("Local peer has joined media room."),a(this,te).notify("stageStatus")}catch(i){throw this.logger.error("SelfController.joinRoom: media room join failed",{error:i}),i instanceof Jr&&i.message==="ice connection failed"?new C("A firewall or network restriction may be blocking the connection.","0014"):new C("Check the network and try again.","0014")}}async leaveRoom(s="left"){var e;if(this.logger.info(`Leaving room with state: ${s}`),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}if(this.self.setIsPinned(!1),a(this,te).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,te).setValue("roomNodeClient",void 0),a(this,te).notify("stageStatus"),a(this,te).getValue("connectionHandler").socketJoined)try{a(this,gs).leaveRoom(this.self)||this.logger.warn("SelfController.leaveRoom: socket leave was not sent")}catch(r){this.logger.error("SelfController.leaveRoom: socket leave failed",{error:r})}(e=a(this,te).getValue("roomSocketHandler"))==null||e.cleanup(),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var n,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=a(this,te).getAllValues();try{if(e===Ss.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}lS(a(this,te),{socket:a(this,Xa),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u,error:h}=(o=await((n=a(this,ft,Ut))==null?void 0:n.joinRoom(this.self.name,r,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)throw h!=null?h:new Error("Could not connect to media server");this.logger.info(i==="ON_STAGE"?"Peer is on stage. Sharing media tracks":"Peer is not on stage. Not sharing media tracks"),i==="ON_STAGE"&&await this.shareMediaTracks(),this.logger.info(i==="ON_STAGE"?"Peer is on stage. Shared media tracks":"Peer is not on stage. Did not share media tracks"),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("SelfController.mediaRoomJoin",{error:c}),c}}async leaveMediaRoom(s){const t=a(this,te).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===Ss.Webinar)&&a(this,ft,Ut)&&(a(this,ft,Ut).mediaJoined&&s!=="disconnected"&&await a(this,ft,Ut).leaveRoom(),!(s==="stageLeft"&&t===Ss.Livestream)&&(a(this,ft,Ut).mediaJoined=!1))}async cleanupSelf(){await this.self.disableAudio(),await this.self.disableVideo(),await this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()}},Xa=new WeakMap,gs=new WeakMap,te=new WeakMap,ft=new WeakSet,Ut=function(){return a(this,te).getValue("roomNodeClient")},tT);let Kr=uS;ji([E.trace("SelfController.resetSelf")],Kr.prototype,"resetSelf",1),ji([E.trace("SelfController.setupEvents")],Kr.prototype,"setupEvents",1),ji([E.trace("SelfController.joinRoom")],Kr.prototype,"joinRoom",1),ji([E.trace("SelfController.leaveRoom")],Kr.prototype,"leaveRoom",1),ji([E.trace("SelfController.joinMediaRoom")],Kr.prototype,"joinMediaRoom",1),ji([E.trace("SelfController.leaveMediaRoom")],Kr.prototype,"leaveMediaRoom",1),ji([E.trace("SelfController.init")],Kr,"init",1);class _N{constructor(t){m(this,Kc,void 0);f(this,Kc,t)}on(t,e){let r;t===x.roomPeerCount?r=ov.fromBinary.bind(ov):r=yv.fromBinary.bind(yv),a(this,Kc).on(t,({payload:i})=>{if(t===x.roomPeerCount&&!i)return;const n=r(i);e(n)})}}Kc=new WeakMap;class CN{constructor(t,e){m(this,zc,void 0);m(this,Yc,void 0);f(this,zc,e),f(this,Yc,t)}get logger(){return a(this,Yc).getValue("logger")}on(t,e){let r,i;switch(t){case x.transcript:{r=Wh.fromBinary.bind(Wh),i=Wh.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,zc).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("aiSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}zc=new WeakMap,Yc=new WeakMap;var RN=Object.defineProperty,IN=Object.getOwnPropertyDescriptor,Op=(s,t,e,r)=>{for(var i=r>1?void 0:r?IN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&RN(t,e,i),i};class Ll{constructor(t,e){m(this,xr,void 0);m(this,Za,void 0);f(this,xr,e),f(this,Za,t)}get logger(){return a(this,Za).getValue("logger")}get telemetry(){return a(this,Za).getValue("telemetry")}getPolls(){return a(this,xr).sendMessagePromise(cr.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,xr).sendMessage(cr.createPoll,bO.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,xr).sendMessage(cr.votePoll,PO.toBinary(r))}on(t,e){let r,i;switch(t){case cr.updatePoll:case cr.createPoll:case cr.votePoll:{r=ip.fromBinary.bind(ip),i=ip.create();break}}a(this,xr).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}removeListeners(t){a(this,xr).removeListeners(t)}}xr=new WeakMap,Za=new WeakMap,Op([E.trace("PollSocketHandler.getPolls")],Ll.prototype,"getPolls",1),Op([E.trace("PollSocketHandler.createPoll")],Ll.prototype,"createPoll",1),Op([E.trace("PollSocketHandler.votePoll")],Ll.prototype,"votePoll",1);var AN=Object.defineProperty,MN=Object.getOwnPropertyDescriptor,ON=(s,t,e,r)=>{for(var i=r>1?void 0:r?MN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&AN(t,e,i),i};class hS{constructor(t,e){p(this,"socket");m(this,Xt,void 0);f(this,Xt,t),this.socket=e,this.handleSocketEvents(),a(this,Xt).setValue("roomSocketHandler",this)}get telemetry(){return a(this,Xt).getValue("telemetry")}get logger(){return a(this,Xt).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}async joinRoom(t){var i;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(i=t.name)!=null?i:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise(x.joinRoom,y0.toBinary(e));try{const{peer:n}=Gn.fromBinary((await r).payload);a(this,Xt).getValue("connectionHandler").socketJoined=!0,a(this,Xt).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_ROOM_JOINED,{peer:n});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=await Promise.all([o,c]);return a(this,Xt).getValue("peerSessionStore").emit(P.ROOM_STATE,d),a(this,Xt).getValue("peerSessionStore").emit(P.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),n}}async getAllAddedParticipants(){try{return aA.fromBinary((await this.socket.sendMessagePromise(x.getAllAddedParticipants)).payload).participants.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}async getRoomPeers(t,e,r){let i;try{const n={seachQuery:t,limit:e,offset:r},o=await this.socket.sendMessagePromise(x.getRoomPeersInfo,l0.toBinary(n));i=zh.fromBinary(o.payload)}catch(n){this.logger.error("getRoomPeers::binary_decode_error",{error:n})}return i}async getRoomPeersNonPaginated(){let t;try{const e=await this.socket.sendMessagePromise(x.getRoomPeersInfo);t=zh.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getStagePeers(){let t;try{const e=await this.socket.sendMessagePromise(x.getRoomPeersInfo);t=zh.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getPeerInfo(t){let e;try{const r=await this.socket.sendMessagePromise(x.getPeerInfo,lv.toBinary({peerId:t}));e=Gn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=dv.create();try{const e=await this.socket.sendMessagePromise(x.getRoomInfo);t=dv.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=gv.create();try{const e=await this.socket.sendMessagePromise(x.getRoomStageState);t=gv.fromBinary(e.payload)}catch(e){this.logger.error("getRoomStageState::binary_decode_error",{error:e})}return t}updateRoomTitle(t){return this.socket.sendMessagePromise(x.updateRoomInfo,ul.toBinary(ul.create({room:{title:t}})))}async broadcastMessage(t,e){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(x.broadcastMessage,Eo.toBinary(r))}async broadcastToMeetings(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(x.broadcastToEntity,Eo.toBinary(i))}async broadcastToPeers(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(x.broadcastToEntity,Eo.toBinary(i))}leaveRoom(t){this.socket.joinAttempted=!1;const e={peer:{peerId:t.peerId,userId:t.userId,displayName:t.name,waitlisted:t.waitlistStatus==="waiting"}};return this.socket.sendMessage(x.leaveRoom,b0.toBinary(e))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(x.kick,pv.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(x.kickAll,Zf.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(x.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(x.acceptWaitingRoomRequests,hA.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(x.denyWaitingRoomRequests,mA.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(gl.updateUserPreset,qA.toBinary(r))}handleSocketEvents(){this.socket.on(x.broadcastMessage,({payload:t})=>{try{const e=Eo.fromBinary(t);a(this,Xt).getValue("peerSessionStore").emit(P.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode broadcast message:",e)}}),this.socket.on(x.broadcastToEntity,({payload:t})=>{try{const e=Eo.fromBinary(t);a(this,Xt).getValue("peerSessionStore").emit(P.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,i;switch(t){case x.joinRoom:case x.leaveRoom:case x.kick:case x.kickAll:{r=Gn.fromBinary.bind(Gn),i=Gn.create();break}case x.getWaitingRoomRequests:{r=(n,o)=>n?mv.fromBinary(n,o):{requests:[]},i=mv.create();break}case x.recordingPaused:case x.recordingStarted:case x.recordingStopped:{r=Pv.fromBinary.bind(Pv);break}case gl.updateUserPreset:{r=vv.fromBinary.bind(vv);break}case Es.peerJoinedBroadcast:case qr.peerJoinedBroadcast:{r=sv.fromBinary.bind(sv);break}case Es.selfJoinComplete:case qr.selfJoinComplete:{r=jh.fromBinary.bind(jh);break}case Es.globalPeerPinBroadcast:case qr.globalPeerPinBroadcast:{r=nv.fromBinary.bind(nv);break}case Es.selectedPeer:case qr.selectedPeer:{r=qh.fromBinary.bind(qh);break}case Es.selectedPeerDiff:case qr.selectedPeerDiff:{r=tv.fromBinary.bind(tv);break}case Es.leaveRoom:case qr.leaveRoom:{r=Gh.fromBinary.bind(Gh);break}case x.updateRoomInfo:{r=ul.fromBinary.bind(ul);break}}this.socket.on(t,({payload:n})=>{let o=i;if(!r)return e(void 0);try{o=r(n)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}async getUserPermissions(t){const e={userIds:[t]};try{const r=await this.socket.sendMessagePromise(gl.getUserPresets,VA.toBinary(e)),i=BA.fromBinary(r.payload).peerPresets[0],n=new TextDecoder().decode(i.preset),o=JSON.parse(n).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(r){throw this.logger.error("Error in getting user preset",{error:r}),r}}}Xt=new WeakMap,ON([E.trace("RoomSocketHandler.joinRoom")],hS.prototype,"joinRoom",1);class DN{constructor(t){m(this,$t,void 0);f(this,$t,t)}async getStageRequests(){const{payload:t}=await a(this,$t).sendMessagePromise(x.getStageRequests);return t?rp.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,$t).sendMessage(x.requestStageAccess)}cancelRequestAccess(){a(this,$t).sendMessage(x.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,$t).sendMessage(x.grantStageAccess,hO.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,$t).sendMessage(x.denyStageAccess,mO.toBinary(e))}joinStage(){return a(this,$t).sendMessagePromise(x.joinStage,void 0,void 0,x.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,$t).sendMessagePromise(x.leaveStage,bv.toBinary(e),void 0,x.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,$t).sendMessagePromise(x.leaveStage,bv.toBinary(e))}on(t,e){let r;switch(t){case x.grantStageAccess:case x.denyStageAccess:{r=void 0;break}case x.getStagePeers:{r=Ev.fromBinary.bind(Ev);break}case x.getStageRequests:case x.requestStageAccess:case x.cancelStageRequest:{r=rp.fromBinary.bind(rp);break}case x.peerStageStatusUpdate:{r=av.fromBinary.bind(av);break}}a(this,$t).on(t,({payload:i,id:n})=>{if(!i||!r)return e(void 0,n);const o=r(i);return e(o,n)})}async getPeerInfo(t){const e=await a(this,$t).sendMessagePromise(x.getPeerInfo,lv.toBinary({peerId:t}));return Gn.fromBinary(e.payload)}}$t=new WeakMap;class NN{constructor(t,e){m(this,vi,void 0);m(this,eo,void 0);f(this,vi,e),f(this,eo,t)}get logger(){return a(this,eo).getValue("logger")}get peerId(){return a(this,eo).getValue("peerId")}storeInsertKeys(t,e,r,i){const n={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,vi).sendMessage(or.storeInsertKeys,WM.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,vi).sendMessage(or.storeGetKeys,KM.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,vi).sendMessage(or.storeDeleteKeys,YM.toBinary(n),i)}on(t,e){const r=Tv.fromBinary.bind(Tv);a(this,vi).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}vi=new WeakMap,eo=new WeakMap;var LN=Object.defineProperty,VN=(s,t,e)=>t in s?LN(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,xN=(s,t,e)=>(VN(s,typeof t!="symbol"?t+"":t,e),e),Dp=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},M=(s,t,e)=>(Dp(s,t,"read from private field"),e?e.call(s):t.get(s)),pe=(s,t,e)=>{if(t.has(s))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(s):t.set(s,e)},ae=(s,t,e,r)=>(Dp(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),oe=(s,t,e)=>(Dp(s,t,"access private method"),e),Vl={},$N={get exports(){return Vl},set exports(s){Vl=s}},Xn=typeof Reflect=="object"?Reflect:null,pS=Xn&&typeof Xn.apply=="function"?Xn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},xl;Xn&&typeof Xn.ownKeys=="function"?xl=Xn.ownKeys:Object.getOwnPropertySymbols?xl=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:xl=function(s){return Object.getOwnPropertyNames(s)};function UN(s){console&&console.warn&&console.warn(s)}var mS=Number.isNaN||function(s){return s!==s};function me(){me.init.call(this)}$N.exports=me,Vl.once=qN,me.EventEmitter=me,me.prototype._events=void 0,me.prototype._eventsCount=0,me.prototype._maxListeners=void 0;var gS=10;function $l(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(me,"defaultMaxListeners",{enumerable:!0,get:function(){return gS},set:function(s){if(typeof s!="number"||s<0||mS(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");gS=s}}),me.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},me.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||mS(s))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+s+".");return this._maxListeners=s,this};function fS(s){return s._maxListeners===void 0?me.defaultMaxListeners:s._maxListeners}me.prototype.getMaxListeners=function(){return fS(this)},me.prototype.emit=function(s){for(var t=[],e=1;e<arguments.length;e++)t.push(arguments[e]);var r=s==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var n;if(t.length>0&&(n=t[0]),n instanceof Error)throw n;var o=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw o.context=n,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")pS(c,this,t);else for(var d=c.length,l=ES(c,d),e=0;e<d;++e)pS(l[e],this,t);return!0};function vS(s,t,e,r){var i,n,o;if($l(e),n=s._events,n===void 0?(n=s._events=Object.create(null),s._eventsCount=0):(n.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),n=s._events),o=n[t]),o===void 0)o=n[t]=e,++s._eventsCount;else if(typeof o=="function"?o=n[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=fS(s),i>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=s,c.type=t,c.count=o.length,UN(c)}return s}me.prototype.addListener=function(s,t){return vS(this,s,t,!1)},me.prototype.on=me.prototype.addListener,me.prototype.prependListener=function(s,t){return vS(this,s,t,!0)};function BN(){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 SS(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=BN.bind(r);return i.listener=e,r.wrapFn=i,i}me.prototype.once=function(s,t){return $l(t),this.on(s,SS(this,s,t)),this},me.prototype.prependOnceListener=function(s,t){return $l(t),this.prependListener(s,SS(this,s,t)),this},me.prototype.removeListener=function(s,t){var e,r,i,n,o;if($l(t),r=this._events,r===void 0)return this;if(e=r[s],e===void 0)return this;if(e===t||e.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[s],r.removeListener&&this.emit("removeListener",s,e.listener||t));else if(typeof e!="function"){for(i=-1,n=e.length-1;n>=0;n--)if(e[n]===t||e[n].listener===t){o=e[n].listener,i=n;break}if(i<0)return this;i===0?e.shift():FN(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this},me.prototype.off=me.prototype.removeListener,me.prototype.removeAllListeners=function(s){var t,e,r;if(e=this._events,e===void 0)return this;if(e.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):e[s]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete e[s]),this;if(arguments.length===0){var i=Object.keys(e),n;for(r=0;r<i.length;++r)n=i[r],n!=="removeListener"&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=e[s],typeof t=="function")this.removeListener(s,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(s,t[r]);return this};function TS(s,t,e){var r=s._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?HN(i):ES(i,i.length)}me.prototype.listeners=function(s){return TS(this,s,!0)},me.prototype.rawListeners=function(s){return TS(this,s,!1)},me.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):yS.call(s,t)},me.prototype.listenerCount=yS;function yS(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}me.prototype.eventNames=function(){return this._eventsCount>0?xl(this._events):[]};function ES(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function FN(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function HN(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function qN(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,n),r(o)}function n(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}bS(s,t,n,{once:!0}),t!=="error"&&jN(s,i,{once:!0})})}function jN(s,t,e){typeof s.on=="function"&&bS(s,"error",t,e)}function bS(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(n){r.once&&s.removeEventListener(t,i),e(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class GN extends T{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 wS=new GN;class PS{static encode(t){return wS.toBinary(t)}static decode(t){return wS.fromBinary(new Uint8Array(t))}}function WN(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var zr;class JN{constructor(t={}){xN(this,"opts"),pe(this,zr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ae(this,zr,0)}async wait(){ae(this,zr,M(this,zr)+1);const t=WN(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**M(this,zr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return M(this,zr)}reset(){ae(this,zr,0)}}zr=new WeakMap;const Yr={debug:0,info:1,warn:2,error:3};var Gi,Wi;class KN{constructor(t){pe(this,Gi,void 0),pe(this,Wi,void 0),ae(this,Gi,console),ae(this,Wi,t)}debug(...t){Yr[M(this,Wi)]>Yr.debug||M(this,Gi).debug("[Sockrates]:",...t)}info(...t){Yr[M(this,Wi)]>Yr.info||M(this,Gi).info("[Sockrates]:",...t)}warn(...t){Yr[M(this,Wi)]>Yr.warn||M(this,Gi).warn("[Sockrates]:",...t)}error(...t){Yr[M(this,Wi)]>Yr.error||M(this,Gi).error("[Sockrates]:",...t)}}Gi=new WeakMap,Wi=new WeakMap;var kS=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(kS||{});const _S="2",CS="3";var Ne,Zn,ge,Oe,Qr,Ye,mr,Xr,ws,ea,ta,gr,Np,RS,No,Ul,Lp,IS,Bl,Vp,Fl,xp,$p,AS,Lo,Hl,sa,Vo,ql,Up,ra,xo,Bp,MS,$o,jl,Uo,Gl;class zN{constructor(t,e){var y,k,I,D,N,B,U,j,Z,re,F,ee;pe(this,Np),pe(this,No),pe(this,Lp),pe(this,Bl),pe(this,Fl),pe(this,$p),pe(this,Lo),pe(this,sa),pe(this,ql),pe(this,ra),pe(this,Bp),pe(this,$o),pe(this,Uo),pe(this,Ne,void 0),pe(this,Zn,void 0),pe(this,ge,void 0),pe(this,Oe,void 0),pe(this,Qr,void 0),pe(this,Ye,void 0),pe(this,mr,void 0),pe(this,Xr,void 0),pe(this,ws,void 0),pe(this,ea,void 0),pe(this,ta,void 0),pe(this,gr,void 0);var r,i,n,o,c,d,l,u,h,g,v;ae(this,Zn,t),ae(this,Qr,[]),ae(this,Ye,new Vl),ae(this,mr,!0),ae(this,ws,!1),ae(this,ge,e!=null?e:{}),(y=(r=M(this,ge)).autoReconnect)!=null||(r.autoReconnect=!0),(k=(i=M(this,ge)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(I=(n=M(this,ge)).pingTimeout)!=null||(n.pingTimeout=3e4),(D=(o=M(this,ge)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(N=(c=M(this,ge)).debug)!=null||(c.debug=!0),(B=(d=M(this,ge)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(U=(l=M(this,ge)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(j=(u=M(this,ge)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(Z=(h=M(this,ge)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),(re=(g=M(this,ge)).clientInitiatedPings)!=null||(g.clientInitiatedPings=!1),(F=(v=M(this,ge)).clientInitiatedPingInterval)!=null||(v.clientInitiatedPingInterval=3e4),ae(this,Xr,{code:void 0,reason:void 0}),ae(this,Oe,(ee=M(this,ge).logger)!=null?ee:new KN(M(this,ge).debug?"debug":"info")),ae(this,gr,new JN)}get readyState(){var t;return(t=M(this,Ne))==null?void 0:t.readyState}get url(){return M(this,Zn)}updateURL(t){ae(this,Zn,t),oe(this,$p,AS).call(this)}get config(){return M(this,ge)}get sendQueue(){return M(this,Qr)}flush(){if(!M(this,ge).queueOnDisconnect)return!1;const t=[];return M(this,Qr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ae(this,Qr,t),M(this,Qr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){M(this,Oe).debug("Websocket was already connecting or connected.");return}if(M(this,mr)!==!1)return new Promise((e,r)=>{oe(this,ra,xo).call(this),oe(this,Uo,Gl).call(this);try{ae(this,Ne,new WebSocket(oe(this,Np,RS).call(this,M(this,Zn)))),M(this,Ne).binaryType="arraybuffer",M(this,Oe).debug("Connecting");const i=setTimeout(()=>{M(this,Oe).debug("Connection timeout. Closing socket"),ae(this,mr,!0),oe(this,Uo,Gl).call(this),M(this,Ne).close(3001,"Connection Timeout"),M(this,ge).autoReconnect&&!M(this,ws)&&(M(this,Ye).emit("reconnecting"),oe(this,Lo,Hl).call(this)),r(new Error("Connection timed out!"))},M(this,ge).connectionTimeout);M(this,Ne).onopen=()=>{M(this,Oe).debug(`Ready State: ${kS[M(this,Ne).readyState]}`),i&&clearTimeout(i),oe(this,ql,Up).call(this),oe(this,Bp,MS).call(this),ae(this,Xr,{code:void 0,reason:void 0}),M(this,Ye).emit("connected"),M(this,ge).flushOnReconnect&&this.flush(),e()},M(this,Ne).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),M(this,Oe).debug("Socket closed. Close event:",{event:n}),M(this,Oe).debug(`Connection closed code: ${o}`),M(this,Oe).debug(`Connection closed reason: ${c}`),M(this,ws)||oe(this,Fl,xp).call(this,o,c)}catch(o){oe(this,No,Ul).call(this,o)}},M(this,Ne).onerror=n=>{oe(this,No,Ul).call(this,n)},M(this,Ne).onmessage=n=>oe(this,Lp,IS).call(this,n)}catch(i){oe(this,No,Ul).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(M(this,ge).queueOnDisconnect&&(!M(this,Ne)||M(this,Ne).readyState!==1))return M(this,Oe).debug("Queuing message since socket is not connected!",n),M(this,Qr).push(n),!1;const o=PS.encode(n);return oe(this,sa,Vo).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return oe(this,sa,Vo).call(this,t)}receive(t,e){return M(this,Ye).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){M(this,Ye).on(t,e);return}this.receive(t,e)}removeAllListeners(){M(this,Ye).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){M(this,Ye).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){M(this,Ye).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ae(this,mr,!1),oe(this,ra,xo).call(this),oe(this,$o,jl).call(this),this.removeAllListeners(),ae(this,Xr,{code:1e3,reason:"Sockrates disconnect method called"}),M(this,Ne).close(1e3,"Sockrates disconnect method called.")}}Ne=new WeakMap,Zn=new WeakMap,ge=new WeakMap,Oe=new WeakMap,Qr=new WeakMap,Ye=new WeakMap,mr=new WeakMap,Xr=new WeakMap,ws=new WeakMap,ea=new WeakMap,ta=new WeakMap,gr=new WeakMap,Np=new WeakSet,RS=function(s){if(s.startsWith("ws://")||s.startsWith("wss://"))return s;if(s.startsWith("https://"))return`wss://${s.substring(8)}`;if(s.startsWith("http://"))return`ws://${s.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},No=new WeakSet,Ul=function(s,t){M(this,Oe).error("Error:",{error:s}),M(this,Ye).emit("errored",{error:s}),t==null||t(s)},Lp=new WeakSet,IS=function(s){if(oe(this,ql,Up).call(this),s.data===_S){M(this,Oe).debug("Received ping from server"),oe(this,sa,Vo).call(this,CS);return}if(s.data===CS){M(this,Oe).debug("Received pong from server");return}const t=PS.decode(s.data),{id:e,payload:r}=t;M(this,Oe).debug("Received message",{event:t.event,messageID:e}),M(this,Ye).emit(t.event.toString(),{id:e,payload:r})},Bl=new WeakSet,Vp=function(){return M(this,Ne).readyState===1},Fl=new WeakSet,xp=function(s,t){ae(this,Xr,{reason:t,code:s}),M(this,Ye).emit("disconnected",{code:s,reason:t})},$p=new WeakSet,AS=function(){const{reason:s,code:t}=M(this,Xr);t&&t!==1e3&&M(this,mr)&&M(this,ge).autoReconnect&&!M(this,ws)&&(M(this,Oe).debug(`Triggering reconnection due to ${s}.`),M(this,Ye).emit("reconnecting"),oe(this,Lo,Hl).call(this))},Lo=new WeakSet,Hl=async function(s=!0){if(s&&M(this,ws)){M(this,Oe).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(M(this,ws)||M(this,gr).reset(),M(this,ge).maxReconnectionAttempts!==null&&M(this,gr).getAttempts()>=M(this,ge).maxReconnectionAttempts){M(this,Ye).emit("failed"),ae(this,ws,!1);return}ae(this,ws,!0),oe(this,Uo,Gl).call(this),oe(this,ra,xo).call(this);try{if(await M(this,gr).wait(),M(this,mr)===!1)return;if(M(this,Oe).debug(`Reconnection attempt ${M(this,gr).getAttempts()}`),M(this,Ye).emit("reconnectAttempt",{attempt:M(this,gr).getAttempts()}),await this.connect(),!oe(this,Bl,Vp).call(this))throw Error("Reconnect Failed");ae(this,ws,!1),ae(this,Xr,{code:void 0,reason:void 0}),M(this,Ye).emit("reconnected")}catch(t){M(this,Oe).debug("Failed to reconnect."),M(this,Ye).emit("reconnectFailure",{attempt:M(this,gr).getAttempts()}),oe(this,Lo,Hl).call(this,!1)}},sa=new WeakSet,Vo=function(s){try{return M(this,Ne).send(s),!0}catch(t){return M(this,Oe).error(t.message),!1}},ql=new WeakSet,Up=function(){this.config.disconnectOnPingTimeout&&(M(this,Oe).debug("Resetting ping timeout"),oe(this,ra,xo).call(this),ae(this,ea,setTimeout(()=>{var s;M(this,Oe).debug("Disconnecting the socket due to ping timeout"),ae(this,mr,!0);const t=3002,e="Ping timeout";(s=M(this,Ne))==null||s.close(t,e),oe(this,Fl,xp).call(this,t,e)},M(this,ge).pingTimeout)))},ra=new WeakSet,xo=function(){M(this,ea)&&(clearTimeout(M(this,ea)),ae(this,ea,void 0))},Bp=new WeakSet,MS=function(){oe(this,$o,jl).call(this),M(this,ge).clientInitiatedPings&&ae(this,ta,setInterval(()=>{oe(this,Bl,Vp).call(this)&&(M(this,Oe).debug("Sending client-initiated ping"),oe(this,sa,Vo).call(this,_S))},M(this,ge).clientInitiatedPingInterval))},$o=new WeakSet,jl=function(){M(this,ta)&&(clearInterval(M(this,ta)),ae(this,ta,void 0))},Uo=new WeakSet,Gl=function(){oe(this,$o,jl).call(this),M(this,Ne)&&(M(this,Ne).onopen=void 0,M(this,Ne).onerror=void 0,M(this,Ne).onmessage=void 0,M(this,Ne).onclose=void 0)};function OS(s){return`${s.slice(0,10)}...${s.slice(-10)}`}function YN(s,t){s.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c — not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://developers.cloudflare.com/api/resources/realtime_kit/subresources/meetings/methods/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:e,orgId:r,participantId:i}=JSON.parse(atob(s.split(".")[1]));if(!e)throw Error(`Received V1 auth token ${s}`);let n=Di.baseURI.prod;t&&(n=t);const o=`https://${Tf({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new C("Invalid auth token","0004")}}var QN=Object.defineProperty,XN=Object.getOwnPropertyDescriptor,Wl=(s,t,e,r)=>{for(var i=r>1?void 0:r?XN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&QN(t,e,i),i};const DS=65535,ZN=3,eL=15e3,tL=8e3,sL=50,rL=1e3,iL=1e4,NS=(Gp=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){m(this,ut);m(this,Qc);m(this,Ku);m(this,zu);m(this,Yu);m(this,Xc);m(this,Zc);m(this,On);m(this,Xu);m(this,ed);m(this,td);m(this,sd);m(this,Zu);m(this,rd);m(this,id);m(this,Ys,void 0);m(this,to,void 0);m(this,Ie,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");m(this,Si,[]);m(this,Ti,void 0);m(this,In,!1);m(this,An,void 0);m(this,yi,void 0);m(this,Qs,void 0);m(this,Xs,void 0);m(this,Ei,void 0);m(this,Mn,void 0);m(this,It,0);m(this,bi,void 0);m(this,At,!0);m(this,We,void 0);if(!t||!e||!r)throw new C("peerId, meetingId, or authToken can not be empty","0404");f(this,We,s),f(this,Xs,navigator.isReactNative?dS:gp),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,Ys,R(this,Qc,fm).call(this,t)),f(this,to,t);const n=i.includes("PING");f(this,Ie,new zN(a(this,Ys),{autoReconnect:!1,disconnectOnPingTimeout:n,queueOnDisconnect:!1,flushOnReconnect:!1,logger:this.logger,clientInitiatedPings:!n,clientInitiatedPingInterval:15e3})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,ut,Ot).socketJoinAttempted}set joinAttempted(s){a(this,ut,Ot).socketJoinAttempted=s}get telemetry(){return a(this,We).getValue("telemetry")}get logger(){return a(this,We).getValue("logger")}get peerId(){return a(this,We).getValue("peerId")}get supersededLocalPeerIds(){return a(this,Si).filter(s=>s!==this.peerId)}updateCallstatsPeerId(s){const t=a(this,We).getValue("callstats");t.peerId=s,t.backend&&(t.backend.peerId=s,t.backend.eventHandler&&Object.assign(t.backend.eventHandler,{peerId:s}))}updateURL(s){var t;f(this,Ys,R(this,Qc,fm).call(this,s)),f(this,to,s),a(this,We).getValue("telemetry").resetPeerId(s),(t=a(this,We).getValue("apiClient"))==null||t.setHeader("tracing-id",s),this.updateCallstatsPeerId(s),Br.remapContext(s,a(this,We)),this.logger.info(`Attempting websocket connection with URL: ${a(this,On,Rd)}`),a(this,Ie).updateURL(a(this,Ys))}get url(){return a(this,Ys)}async connect(){var t;const s=a(this,It)+1;f(this,It,s),R(this,ed,Tm).call(this),f(this,At,!0),R(this,Yu,GT).call(this);try{if(await a(this,Ie).connect(),!a(this,At)||s!==a(this,It))throw new Error("Socket connection was canceled");R(this,Zc,Sm).call(this,this.peerId),(t=a(this,Qs))!=null||f(this,Qs,this.peerId),a(this,ut,Ot).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}catch(e){throw this.logger.error(`Websocket connection failed with URL: ${a(this,On,Rd)}`,{error:e}),a(this,At)&&s===a(this,It)&&R(this,sd,Em).call(this,s),e}}disconnect(){f(this,It,a(this,It)+1),f(this,At,!1),R(this,ed,Tm).call(this),R(this,Xc,vm).call(this),f(this,Qs,void 0),a(this,Ie).disconnect(),a(this,ut,Ot).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Ie).readyState===1}catch(s){return!1}}sendMessage(s,t,e){if(!a(this,rd,bm))return!1;const r={};return a(this,We).getValue("telemetry").injectContext(r),a(this,Ie).send(s,e!=null?e:R(this,id,wm).call(this),t,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(s,t,e,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:s,timeout:i,protobuf:t,messageId:e,resp:r})}sendMessagePromiseWithTimeout({event:s,timeout:t,protobuf:e,messageId:r,resp:i}){if(!a(this,rd,bm))return Promise.reject(new Error("Socket is not connected for the current peer ID"));const n=i!=null?i:s;return new Promise((o,c)=>{let d;const l=(I,D)=>{d&&clearTimeout(d),a(this,Ie).removeListener(n,I),a(this,Ie).removeListener(DS,D),a(this,Ie).removeListener(qr.errorResponse,D),a(this,Ie).removeListener(Es.errorResponse,D)},u=r!=null?r:R(this,id,wm).call(this),h={};a(this,We).getValue("telemetry").injectContext(h);const v=({id:I,payload:D})=>{if(u===I){let N;try{const B=tI.fromBinary(D);N=new Error(B.errorMessage)}catch(B){N=new Error("failed to parse error message",{cause:B});try{const U=r0.fromBinary(D);N=new Error(U.message)}catch(U){N=new Error("failed to parse error message",{cause:U})}}c(N),l(y,v)}},y=({id:I,payload:D})=>{u===I&&(o({id:I,payload:D}),l(y,v))};a(this,Ie).on(n,y),a(this,Ie).on(DS,v),a(this,Ie).on(qr.errorResponse,v),a(this,Ie).on(Es.errorResponse,v),d=setTimeout(()=>{l(y,v),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Ie).send(s,u,e,new TextEncoder().encode(JSON.stringify(h)))||(l(y,v),c(new Error("Socket message could not be sent for the current peer ID")))})}on(s,t){a(this,Ie).on(s,t)}onStateEvent(s,t){a(this,Ie).on(s,t)}removeListener(s,t){a(this,Ie).removeListener(s,t)}removeListeners(s){a(this,Ie).removeListeners(s)}flush(){return a(this,Ie).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{var s;this.logger.info(`Websocket connected with URL: ${a(this,On,Rd)}`),(s=a(this,Qs))!=null||f(this,Qs,this.peerId),a(this,ut,Ot).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{!a(this,At)||a(this,bi)===a(this,It)||(this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t}}),a(this,ut,Ot).updateSocketConnectionState("disconnected"),a(this,We).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,ut,Ot).joinAttempted}),R(this,sd,Em).call(this,a(this,It)))})}},Ys=new WeakMap,to=new WeakMap,Ie=new WeakMap,ut=new WeakSet,Ot=function(){return a(this,We).getValue("connectionHandler")},Si=new WeakMap,Ti=new WeakMap,In=new WeakMap,An=new WeakMap,yi=new WeakMap,Qs=new WeakMap,Xs=new WeakMap,Ei=new WeakMap,Mn=new WeakMap,It=new WeakMap,bi=new WeakMap,At=new WeakMap,We=new WeakMap,Qc=new WeakSet,fm=function(s){let t=Dh({servicePrefix:"ws",baseURI:a(this,We).getValue("baseURI")});const e=So(a(this,We),"socket_server_base");if(typeof e=="string"){const n=/^(http|ws):\/\//i.test(e),o=e.replace(/^(https?|wss?):\/\//i,"").replace(/\/+$/,"");t=`${n?"ws":"wss"}://${o}/ws`}const r=new URL(t),i={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...a(this,Si).length>0&&{oldPeerIds:a(this,Si).join(",")},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(n=>dl[n]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0,apiVersion:"23-09-2026"};return Object.entries(i).forEach(([n,o])=>{r.searchParams.append(n,o.toString())}),r.href},Ku=new WeakSet,qT=function(){if(!a(this,Qs))return;const s=new URL(a(this,Ys));return s.protocol=s.protocol==="ws:"?"http:":"https:",s.pathname=`${s.pathname.replace(/\/+$/,"")}/ping`,s.search="",s.searchParams.set("peerId",a(this,Qs)),s.href},zu=new WeakSet,jT=async function(){const s=R(this,Ku,qT).call(this);if(!s||a(this,In))return;const t={},e=typeof AbortController=="function"?new AbortController:void 0;let r;f(this,In,!0),f(this,yi,t),f(this,An,e);try{e&&(r=a(this,Xs).setTimeout(()=>e.abort(),tL));const i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${this.authToken}`},...e&&{signal:e.signal}});i.ok||this.logger.warn("SocketService::API ping request failed",{networkCall:{status:i.status,url:s}})}catch(i){a(this,yi)===t&&this.logger.warn("SocketService::API ping request failed",{error:i,networkCall:{url:s}})}finally{r!==void 0&&a(this,Xs).clearTimeout(r),a(this,yi)===t&&(f(this,In,!1),f(this,yi,void 0),f(this,An,void 0))}},Yu=new WeakSet,GT=function(){a(this,Ti)===void 0&&f(this,Ti,a(this,Xs).setInterval(()=>R(this,zu,jT).call(this),eL))},Xc=new WeakSet,vm=function(){var s;a(this,Ti)!==void 0&&a(this,Xs).clearInterval(a(this,Ti)),(s=a(this,An))==null||s.abort(),f(this,Ti,void 0),f(this,In,!1),f(this,yi,void 0),f(this,An,void 0)},Zc=new WeakSet,Sm=function(s){f(this,Si,[s,...a(this,Si).filter(t=>t!==s)].slice(0,ZN))},On=new WeakSet,Rd=function(){const s=new URL(a(this,Ys)),t=s.searchParams.get("authToken");return t&&s.searchParams.set("authToken",OS(t)),s.href},Qu=new WeakSet,WT=function(s){const t=Math.min(iL,rL*2**(s-1));return Math.floor(Math.random()*(t+1))},Xu=new WeakSet,JT=function(s){return new Promise(t=>{var e;f(this,Mn,t),f(this,Ei,a(this,Xs).setTimeout(()=>{f(this,Ei,void 0),f(this,Mn,void 0),t()},R(e=NS,Qu,WT).call(e,s)))})},ed=new WeakSet,Tm=function(){var s;a(this,Ei)!==void 0&&(a(this,Xs).clearTimeout(a(this,Ei)),f(this,Ei,void 0)),(s=a(this,Mn))==null||s.call(this),f(this,Mn,void 0)},td=new WeakSet,ym=function(s,t){!a(this,At)||s!==a(this,It)||(t&&this.logger.error("SocketService::Reconnect loop failed",{error:t}),f(this,At,!1),R(this,Xc,vm).call(this),f(this,Qs,void 0),a(this,ut,Ot).updateSocketConnectionState("failed"),a(this,We).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_FAILED))},sd=new WeakSet,Em=function(s){!a(this,At)||a(this,bi)===s||(f(this,bi,s),a(this,ut,Ot).updateSocketConnectionState("reconnecting"),R(this,Zu,KT).call(this,s).catch(t=>R(this,td,ym).call(this,s,t)))},Zu=new WeakSet,KT=async function(s){try{for(let t=1;t<=sL;t+=1){if(!a(this,At)||s!==a(this,It)||(await R(this,Xu,JT).call(this,t),!a(this,At)||s!==a(this,It)))return;this.updateURL(Ci()),this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:t}}),a(this,ut,Ot).updateSocketConnectionState("reconnectAttempt",t);try{if(await a(this,Ie).connect(!0),!a(this,At)||s!==a(this,It))return;if(!this.isConnected)throw new Error("Reconnect failed");R(this,Zc,Sm).call(this,this.peerId),f(this,Qs,this.peerId),a(this,ut,Ot).updateSocketConnectionState("reconnected"),a(this,We).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_RECONNECTED,{wasSocketJoinAttempted:a(this,ut,Ot).socketJoinAttempted,wasMediaJoinAttempted:a(this,ut,Ot).mediaJoinAttempted});return}catch(e){if(!a(this,At)||s!==a(this,It))return;this.logger.error(`Websocket connection retry attempt ${t} failed with URL: ${a(this,On,Rd)}`,{error:e,socket:{retryAttempt:t}}),a(this,ut,Ot).updateSocketConnectionState("reconnectFailure",t)}}R(this,td,ym).call(this,s)}finally{a(this,bi)===s&&f(this,bi,void 0)}},rd=new WeakSet,bm=function(){return this.isConnected&&a(this,to)===this.peerId},id=new WeakSet,wm=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},m(Gp,Qu),Gp);let Bo=NS;Wl([E.trace("SocketService.connect")],Bo.prototype,"connect",1),Wl([E.trace("SocketService.disconnect")],Bo.prototype,"disconnect",1),Wl([E.trace("SocketService.sendMessagePromise")],Bo.prototype,"sendMessagePromise",1),Wl([E.trace("SocketService.sendMessagePromiseWithTimeout")],Bo.prototype,"sendMessagePromiseWithTimeout",1);class nL{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=A0.fromBinary(t),r=e.meetings.map(o=>{var c;return{id:o.id,title:o.title,participants:(c=o.participants)!=null?c:[]}});return{parentMeeting:{id:e.parentMeeting.id,title:e.parentMeeting.title,participants:(n=e.parentMeeting.participants)!=null?n:[]},meetings:r}}handleTransferPeerRaw({payload:t}){const e=iA.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=hv.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return $0.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title,error:r.error}))}handleConnectedRoomsDeletedRaw({payload:t}){return K0.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(x.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const e=await this.socketService.sendMessagePromise(x.createConnectedRooms,N0.toBinary({payloads:t}));return this.handleConnectedRoomsUpdatedRaw(e)}async updateConnectedRooms(t){const e=await this.socketService.sendMessagePromise(x.updateConnectedRooms,H0.toBinary({payloads:t}));return this.handleConnectedRoomsUpdatedRaw(e)}async disableConnectedRooms(t){const e=t.map(i=>({id:i})),r=await this.socketService.sendMessagePromise(x.deleteConnectedRooms,W0.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(x.movePeers,eA.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}}}}var aL=Object.defineProperty,oL=Object.getOwnPropertyDescriptor,cL=(s,t,e,r)=>{for(var i=r>1?void 0:r?oL(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&aL(t,e,i),i};class LS extends Bt{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);m(this,Zt,void 0);f(this,Zt,e)}get isActive(){return this.meetings.length!==0}validateAlterAction(){const e=a(this,Zt).getValue("self").permissions.connectedMeetings;if(!(e!=null&&e.canAlterConnectedMeetings))throw new Error("You are not allowed to perform this action. Please enable canAlterConnectedMeetings permission in your preset.")}validateMoveAction(e,r){var d;if(!(r!=null&&r.length))throw new Error("You're trying to move participants with an empty list.");const i=a(this,Zt).getValue("self").permissions.connectedMeetings;if(!i)throw new Error("You are not allowed to perform this action. Please enable connected meetings permissions in your preset.");if(i.canAlterConnectedMeetings)return;const n=a(this,Zt).getValue("userId");if(!(r.length===1&&r[0]===n))throw new Error("You are not allowed to move other participants. Please enable canAlterConnectedMeetings permission in your preset.");if(e===((d=this.parentMeeting)==null?void 0:d.id)){if(!i.canSwitchToParentMeeting)throw new Error("You are not allowed to move to the parent meeting. Please enable canSwitchToParentMeeting permission in your preset.");return}if(!i.canSwitchConnectedMeetings)throw new Error("You are not allowed to move to a connected meeting. Please enable canSwitchConnectedMeetings permission in your preset.")}async getConnectedMeetings(){this.logger.info("Getting connected meetings dump");const e=await a(this,Zt).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateAlterAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await a(this,Zt).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e);return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`),r.map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateAlterAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`);const r=await a(this,Zt).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(o=>({meetingId:o.id,title:o.title})));this.logger.info(`Updated connected meetings ${JSON.stringify(r)}`);const i=new Set(r.filter(o=>!o.error).map(o=>o.id)),n=[...new Set(e.map(o=>o.id))].filter(o=>!i.has(o));if(n.length>0)throw new Error(`Could not update connected meetings: ${n.join(", ")}`)}async deleteMeetings(e){this.validateAlterAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.participants.map(o=>o.id)):Promise.resolve());this.logger.info(`Moved participants before deleting connected meetings ${JSON.stringify(e)}. Deleting now.`),await Promise.all(r);const i=await a(this,Zt).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateMoveAction(r,i),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,Zt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return n.success?(this.logger.info(`Moved connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i)):this.logger.error(`Failed to move connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),n}async moveParticipantsWithCustomPreset(e,r,i){this.validateMoveAction(r,i.map(o=>o.id)),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,Zt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return n.success?(this.logger.info(`Moved connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i.map(o=>o.id))):this.logger.error(`Failed to move connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),n}moveSuccessHandler(e,r,i){const n=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>n.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>n.get(o)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(o=>!i.includes(o.id))),this.meetings=this.meetings.map(o=>{if(r===o.id){const c=o.participants.concat(i.map(d=>n.get(d)));return{...o,participants:c}}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return{...o,participants:c}}return o})}}Zt=new WeakMap,cL([qt({maxInvocations:60,period:60})],LS.prototype,"getConnectedMeetings",1);var dL=Object.defineProperty,lL=Object.getOwnPropertyDescriptor,Fp=(s,t,e,r)=>{for(var i=r>1?void 0:r?lL(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&dL(t,e,i),i};const VS=(sT=class{constructor(s){p(this,"connectedMeetings");m(this,Se,void 0);f(this,Se,s),this.connectedMeetings=new LS(s)}get telemetry(){return a(this,Se).getValue("telemetry")}get logger(){return a(this,Se).getValue("logger")}static init(s){const t=new VS(s);return s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings()),t.setupEvents(),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(x.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(x.transferPeer,this.handleTransferPeer.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(x.movedPeer,this.handleMovedPeer.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(x.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(x.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.logger.info(`Honoring request to switch connected meetings. Going to ${t==null?void 0:t.meetingId}`),this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){var i,n,o,c;this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:a(this,Se).getValue("self").videoEnabled,audio:a(this,Se).getValue("self").audioEnabled};try{a(this,Se).getValue("self").cleanupEvents(),await a(this,Se).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,Se).getValue("meeting"))==null?void 0:i.meta)==null?void 0:n.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await $S.init({...a(this,Se).getValue("options"),cachedUserDetails:null,defaults:{...a(this,Se).getValue("options").defaults,...e,mediaHandler:a(this,Se).getValue("self")},authToken:s});this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(o=r==null?void 0:r.meta)==null?void 0:o.meetingId}`);try{const{hidden:d}=a(this,Se).getValue("self");r.self.setName(a(this,Se).getValue("self").name),await r.join(),d&&r.self.hide()}catch(d){this.logger.error("ConnectedMeetingsController.joinRoom",{error:d})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(c=r==null?void 0:r.meta)==null?void 0:c.meetingId}`),this.connectedMeetings.emit("meetingChanged",r),r}handleConnectedRoomsDump(s){const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(s);this.connectedMeetings.meetings=t.meetings.map(e=>({id:e.id,title:e.title,participants:e.participants||[]})),this.connectedMeetings.parentMeeting={id:t.parentMeeting.id,title:t.parentMeeting.title,participants:t.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(s){return a(this,Se).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){var n;const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(s).filter(o=>!o.error),e=new Map(this.connectedMeetings.meetings.map(o=>[o.id,o]));t.forEach(o=>{var l;const{parentMeeting:c}=this.connectedMeetings;if(o.id===(c==null?void 0:c.id)){this.connectedMeetings.parentMeeting={...c,title:o.title};return}const d=e.get(o.id);e.set(o.id,{...d,id:o.id,title:o.title,participants:(l=d==null?void 0:d.participants)!=null?l:[]})}),this.connectedMeetings.meetings=Array.from(e.values());const r=(n=a(this,Se).getValue("meeting"))==null?void 0:n.meta,i=t.find(o=>o.id===(r==null?void 0:r.meetingId));r&&i&&i.title!==r.meetingTitle&&r[Sl](i.title),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(s).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})}},Se=new WeakMap,sT);let Jl=VS;Fp([E.trace("ConnectedMeetingsController.getConnectedMeetings")],Jl.prototype,"getConnectedMeetings",1),Fp([E.trace("ConnectedMeetingsController.setupEvents")],Jl.prototype,"setupEvents",1),Fp([E.trace("ConnectedMeetingsController.switchMeeting")],Jl.prototype,"switchMeeting",1);var uL=Object.defineProperty,hL=Object.getOwnPropertyDescriptor,Hp=(s,t,e,r)=>{for(var i=r>1?void 0:r?hL(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&uL(t,e,i),i};function pL(s){switch(s){case"participant_token_not_yet_valid":return"The participant authentication token is not valid yet.";case"participant_token_expired":return"The participant authentication token has expired.";case"participant_token_revoked":return"The participant authentication token has been revoked.";case"participant_token_invalid":return"The participant authentication token is invalid.";case"meeting_inactive":return"The meeting is inactive and is not accepting participants.";default:return"The participant authentication token may be invalid, expired, or not yet valid. Verify the token and its validity window."}}const Fo=class{constructor(s,t,e){p(this,"apiBase");p(this,"selfController");p(this,"pollController");p(this,"chatController");p(this,"metaController");p(this,"storesManager");p(this,"stageController");p(this,"pluginController");p(this,"internalsController");p(this,"recordingController");p(this,"livestreamController");p(this,"participantController");p(this,"connectedMeetingsController");p(this,"telemetry");p(this,"logger");this.apiBase=s,this.storesManager=t.storesManager,this.metaController=t.metaController,this.selfController=t.selfController,this.chatController=t.chatController,this.pollController=t.pollController,this.stageController=t.stageController,this.pluginController=t.pluginController,this.recordingController=t.recordingController,this.internalsController=t.internalsController,this.participantController=t.participantController,this.livestreamController=t.livestreamController,this.connectedMeetingsController=t.connectedMeetingsController,this.telemetry=e.getValue("telemetry"),this.logger=e.getValue("logger")}static async init(s){var B,U,j,Z,re;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(wN(s),Pe.isSupported()===!1)throw new C("Browser not supported","0010",c,!0);const d=ZO(s,{authToken:r,baseURL:e,cachedUserDetails:o});d.setRoomName(i),d.setRoomUUID(i),d.setOrganizationId(n),d.setHeader("tracing-id",t),s.setValue("apiClient",d);const l=new LD(s);s.setValue("connectionHandler",l);let u="",h=null;c.info("CF SFU is being used.");const g=Fo.createSocketService(s),v=g.connect();v.catch(()=>{});const y=d.getUserDetails();try{h=await y,u=((B=h.meeting)==null?void 0:B.title)||"",s.setValue("presetName",h.preset.name)}catch(F){if(c.error("Failed to get user details",{error:F}),g.disconnect(),F instanceof fl){if(F.status===401||F.status===403){const ee=(Z=(j=(U=F.response)==null?void 0:U.data)==null?void 0:j.error)==null?void 0:Z.reason;throw new C(pL(ee),"0004",void 0,!1,ee)}throw F.status===404?(c.error("[ERROR:0004] participant-details returned 404."),new C("The auth token is not associated with an active participant in this meeting. The meeting may have ended, or the participant may no longer exist. (404)","0004")):F.status>=500?new C(`The server encountered an error. Try again. (${F.status})`,"0001"):F.isHttpError?new C(`Request rejected by the server. (${F.status})`,"0001"):F.isTimeout?new C("Connection timed out. Check the network and try again.","0001"):new C("Unable to connect to the server. Check the internet connection.","0001")}throw new C((F==null?void 0:F.message)||"Failed to initialize.","0001")}try{await v}catch(F){c.error("[Controller]: Failed to connect to socket server:",{error:F})}const k=yp.init(h.preset,!s.getValue("modules").theme);s.setValue("theme",k);const I=bp.init(s,k.viewType,h.preset.permissions),D=Fo.setupControllers(g,s,h,u,k,I);wD(k)&&((re=Fo.createRoomNodeClient(s,g).initializeConnection(h.participant.name,i,!1,I))==null||re.catch(ee=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:ee})}));const{controllers:N}=await D;return dC(),new Fo(e,N,s)}static async setupControllers(s,t,e,r,i,n){var fe,V,_;const o=t.getValue("modules"),{participant:c}=e,d=t.getValue("defaults"),l=t.getValue("logger"),{viewType:u,mediaConstraints:{audio:h}}=i;t.setValue("viewType",u),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(fe=h.enableHighBitrate)!=null?fe:!1,enableStereo:(V=h.enableStereo)!=null?V:!1}},...d}),t.setValue("maxPreferredStreams",Pe.isMobile()?i.maxVideoStreams.mobile:i.maxVideoStreams.desktop);let g,v,y,k,I,D,N,B,U;const j=new CN(t,s),Z=new nL(s);t.setValue("connectedMeetingsSocketHandler",Z);const re=new Ll(t,s),F=new dr(t,s),ee=new DN(s),we=new hS(t,s),vt=new NN(t,s),A=new _N(s),S=await Kr.init(t,we,c,n,i);t.setValue("selfController",S);const w=await Ov.init(t,S.self,we,j,r);o.participant&&(B=await pr.init(t,S.self,we)),(_=o.e2ee)!=null&&_.enabled&&o.e2ee.manager.init(l,t.getValue("peerSessionStore")),o.chat&&(v=await wo.init(t,F,S.self,B.participants)),o.internals&&(I=await mp.init(t)),o.livestream&&i.viewType===Ss.Livestream&&(N=new Zv(t,S.self,A)),o.poll&&(g=await Iv.init(t,S.self,re)),o.recording&&(D=new Uv(t,S.self,we)),o.stage&&(y=new Dv(t,ee,we,S.self,B.participants));const $=new D1(t,vt);if(o.plugin){if(!B)throw new C("The plugin module cannot be initialized without the `participant` module","0102");const He=d.plugins||[];k=await xv.init(t,He,S.self,$)}if(o.connectedMeetings&&(U=await Jl.init(t)),o.pip){const He=await Vh._init(t,S.self);t.setValue("pip",He)}return{theme:i,permissions:n,controllers:{storesManager:$,pollController:g,selfController:S,metaController:w,chatController:v,stageController:y,pluginController:k,recordingController:D,internalsController:I,livestreamController:N,participantController:B,connectedMeetingsController:U}}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return lS(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=[];return new Bo(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Kl=Fo;Hp([E.trace("Controller.init")],Kl,"init",1),Hp([E.trace("Controller.createRoomNodeClient")],Kl,"createRoomNodeClient",1),Hp([E.trace("Controller.createSocketService")],Kl,"createSocketService",1);class mL{constructor(){p(this,"battery");p(this,"logger");p(this,"init",async t=>{this.logger=t;try{"getBattery"in navigator&&(this.battery=await navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){t.error("Error getting battery",e)}});p(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});p(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});p(this,"cleanup",()=>{var t,e;"getBattery"in navigator&&((t=this.battery)==null||t.removeEventListener("chargingchange",this.updateChargeInfo),(e=this.battery)==null||e.removeEventListener("levelchange",this.updateLevelInfo))})}}const xS=new mL;class gL{constructor(){m(this,eh);m(this,wi,new Audio);m(this,Dn,new MediaStream);m(this,Nn,new Map);m(this,nd,void 0);a(this,wi).srcObject=a(this,Dn),a(this,wi).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,Nn).has(e.id)||(a(this,Dn).addTrack(e),a(this,Nn).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,wi).setSinkId(t)}removeTrack(t){const e=a(this,Nn).get(t);e&&(a(this,Dn).removeTrack(e),a(this,Nn).delete(t))}async play(){return a(this,wi).srcObject=a(this,Dn),a(this,wi).play().catch(t=>{R(this,eh,zT).call(this,t)})}onError(t){f(this,nd,t)}}wi=new WeakMap,Dn=new WeakMap,Nn=new WeakMap,nd=new WeakMap,eh=new WeakSet,zT=function(t){var e;(e=a(this,nd))==null||e.call(this,t)};class fL extends gL{constructor(){super();m(this,Zs,void 0);f(this,Zs,new Map)}addParticipantTrack(e,r){a(this,Zs).set(e,r.id),this.playTracks([r])}reassignParticipantTrack(e,r){const i=a(this,Zs).get(e);i&&(a(this,Zs).delete(e),a(this,Zs).set(r,i))}removeParticipantTrack(e){const r=a(this,Zs).get(e);r&&this.removeTrack(r),a(this,Zs).delete(e)}}Zs=new WeakMap;var vL=Object.defineProperty,SL=Object.getOwnPropertyDescriptor,zl=(s,t,e,r)=>{for(var i=r>1?void 0:r?SL(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&vL(t,e,i),i};let Zr=(rT=class{constructor(t,e){m(this,qe,void 0);m(this,Ln,void 0);f(this,Ln,t),f(this,qe,e)}get peerId(){return a(this,Ln).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:Ci(),n=Br.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new sS(n,o);return await c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var v,y,k,I,D,N,B,U;Pe.init();const e=(y=(v=t==null?void 0:t.cachedUserDetails)==null?void 0:v.peerId)!=null?y:Ci(),{authToken:r,baseURI:i}=t,{meetingId:n,...o}=YN(r,i);if((k=o.baseURI)!=null&&k.includes("dyte.io"))throw new C("Dyte Base URIs are no longer supported. Use RealtimeKit Base URIs.","0001");const c=Y1((I=t.defaults)==null?void 0:I.mediaProducerConfiguration);if(c.valid!==!0)throw new C(c.message,"0001");window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const d=Zr.setupContext(e,t,n,o);d.setValue("mediaProducerCodecs",c.codecs);const l=d.getValue("telemetry"),u=d.getValue("logger");ZT(u),xS.init(u),l.init(d,{roomName:n,userId:o.participantId,organizationId:o.orgId,peerId:e},(N=(D=t.modules)==null?void 0:D.tracing)!=null?N:!0,(U=(B=t==null?void 0:t.modules)==null?void 0:B.devTools)==null?void 0:U.logLevel),u.init(d),u.info("Client::init::options",{clientInitOptions:{...t,authToken:OS(t.authToken)}}),u.info(`Using producer codecs: ${JSON.stringify(c.codecs)}`);const h=await Kl.init(d),g=new Zr(d,h);return d.setValue("meeting",g),u.info(`Meeting view type: ${g.meta.viewType}`),g}static setupContext(t,e,r,i){var d,l;const n=Br.createContext(t,e),o={...B_,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return n.setValue("options",e),n.setValue("peerId",t),n.setValue("modules",o),n.setValue("sdkName","web-core"),n.setValue("meetingId",r),n.setValue("apiBase",i.apiBase),n.setValue("baseURI",i.baseURI),n.setValue("userId",i.participantId),n.setValue("organizationId",i.orgId),n.setValue("authToken",e.authToken),n.setValue("overrides",(d=e.overrides)!=null?d:{}),n.setValue("env",F_({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Ls(e.cachedUserDetails)),n.setValue("sdkVersion","2.2.0-staging.2"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new fL),n}async join(){const{selfController:t}=a(this,qe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){var r;xS.cleanup(),a(this,Ln).getValue("peerSessionStore").reset(),(r=a(this,qe).pluginController)==null||r.cleanup();const{selfController:e}=a(this,qe);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,qe).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,qe).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,qe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,qe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,qe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,qe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,qe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,qe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,qe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,qe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,qe).stageController)==null?void 0:t.stage}get stores(){return a(this,qe).storesManager}get audio(){return a(this,Ln).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,qe).internalsController)==null?void 0:t.internals}},qe=new WeakMap,Ln=new WeakMap,rT);zl([pt("0002"),ur.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Zr.prototype,"join",1),zl([pt("0003")],Zr.prototype,"leave",1),zl([pt("0001"),ur.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Zr,"init",1),Zr=zl([pt("0000")],Zr);const $S=Zr;return $S}();
|