@cloudflare/realtimekit 2.0.3-staging.6 → 2.0.3-staging.7
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.d.ts +1 -0
- package/dist/browser.js +10 -10
- package/dist/dependencies.txt +1 -1
- package/dist/index.cjs.js +7 -7
- package/dist/index.d.ts +1 -0
- package/dist/index.es.js +6434 -6384
- package/dist/index.es5.js +5856 -5735
- package/dist/index.rn.js +7 -7
- package/dist/ts3.4/dist/EncryptionManager.d.ts +1 -0
- package/dist/ts3.4/dist/index.d.ts +1 -0
- package/package.json +1 -1
package/dist/browser.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
var RealtimeKitClient=function(){var Oo,lr,ur,lv,ss,Vi,lt,rs,Oe,Ts,hr,St,xe,Wn,Jn,pr,Kn,Bt,zn,re,xi,rt,Yn,Il,Iv,Do,bp,uv,Ui,hv,Al,Av,Ml,Mv,Qn,Xn,No,pv,Kr,Zn,$i,mv,ea,Lo,wp,Bi,Vo,gv,xo,fv,zr,ta,Ft,Sv,is,Ol,de,Uo,Ls,Ke,$o,Pp,sa,Iu,Yr,ys,Qr,Bo,vt,Fi,mr,Fo,Ho,Hi,vv,Ue,qi,Es,ra,Xr,ji,Dl,Ov,qo,_p,jo,kp,Go,Cp,Tv,Wo,ia,na,aa,Au,yv,Gi,Wi,He,be,ve,gr,ns,Jo,De,Ji,Ko,Ki,Nl,oa,as,ze,Ev,zi,zo,ca,Yo,Tt,Yi,Qo,da,ua,Xo,ha,pa,fr,Vs,it,Zr,ei,Ll,Dv,ti,si,Zo,Rp,ec,bs,Vl,Nv,ma,ga,Ht,Qi,od,ri,Ga,Xi,cd,xl,Lv,Sr,tc,ii,Zi,dd,vr,Ul,sc,Ip,$l,Vv,Bl,xv,bv,ni,Ne,rc,Ap,en,ld,fa,Mu,tn,It,wv,os,ws,ai,Pv,Y,Sa,va,Fl,yt,zt,qt,Ta,Et,ya,Ye,Tr,_n,Qe,pt,Ea,Ou,$e,je,ba,wa,ic,Mp,_v,nc,Xe,ac,oc,sn,xs,ql,Us,vi,cc,Op,jl,Uv,Gl,$v,Ps,Pa,_a,rn,cs,nt,oi,ka,Wl,jt,Cs,Ca,yr,nn,Ia,Ze,et,dc,lc,an,Aa,uc,Ma,on,$s,Oa,Du,hc,Dp,Jl,Bv,pc,Np,Kl,Fv,zl,Hv,Yl,qv,Ql,jv,Xl,Gv,mc,Lp,ci,Wa,Zl,ds,di,li,Da,gc,Bs,eu,Er,Na,fc,Vp,tu,Wv,su,Jv,ru,Kv,iu,zv,Sc,vc,Tc,La,Va,xa,yc,Ec,Ua,At,_s,ks,cn,dn,br,bc,nu,Yv,au,Qv,ou,Xv,cu,Zv,wc,Pc,wr,Pr,_r,_c,$a,Ba,ui,ln,Fa,un,kr,Fs,lu,eT,kc,xp,uu,tT,hu,sT,Rc,Ic,ut,H,pu,bt,hn,pn,mn,Ac,Gt,Hs,ht,Mt,Cr,kn,mu,rT,gu,iT,fu,nT,Mc,Up,Su,aT,vu,oT,wt,Yt,gn,ud,Tu,cT,yu,dT,Eu,lT,Oc,ls,te,Ot,us,kv,Dc,Nc,Lc,Rr,Ha,Wt,Dt,hi,qa,qs,ja,Pe,tt,mt,fn,pi,Sn,vn,mi,js,Gs,gi,Tn,Pt,fi,_t,qe,Vc,$p,bu,uT,wu,hT,Pu,pT,xc,Bp,Uc,Fp,yn,hd,_u,Tp,mT,ku,gT,$c,Hp,Bc,qp,Fc,jp,Cu,fT,Hc,Gp,qc,Wp,Jt,Te,Cv,Si,En,bn,jc,Ru,ST,wn,Fe,Pn,Rv;"use strict";var DN=Object.defineProperty;var NN=(ke,we,Ce)=>we in ke?DN(ke,we,{enumerable:!0,configurable:!0,writable:!0,value:Ce}):ke[we]=Ce;var p=(ke,we,Ce)=>(NN(ke,typeof we!="symbol"?we+"":we,Ce),Ce),Ep=(ke,we,Ce)=>{if(!we.has(ke))throw TypeError("Cannot "+Ce)};var a=(ke,we,Ce)=>(Ep(ke,we,"read from private field"),Ce?Ce.call(ke):we.get(ke)),m=(ke,we,Ce)=>{if(we.has(ke))throw TypeError("Cannot add the same private member more than once");we instanceof WeakSet?we.add(ke):we.set(ke,Ce)},g=(ke,we,Ce,pd)=>(Ep(ke,we,"write to private field"),pd?pd.call(ke,Ce):we.set(ke,Ce),Ce);var N=(ke,we,Ce)=>(Ep(ke,we,"access private method"),Ce);function ke(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:ke});function we(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:we});var Ce,pd=new Uint8Array(16);function vT(){if(!Ce&&(Ce=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!Ce))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Ce(pd)}const TT=/^(?:[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 Nu(s){return typeof s=="string"&&TT.test(s)}for(var st=[],Lu=0;Lu<256;++Lu)st.push((Lu+256).toString(16).substr(1));function yT(s){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(st[s[t+0]]+st[s[t+1]]+st[s[t+2]]+st[s[t+3]]+"-"+st[s[t+4]]+st[s[t+5]]+"-"+st[s[t+6]]+st[s[t+7]]+"-"+st[s[t+8]]+st[s[t+9]]+"-"+st[s[t+10]]+st[s[t+11]]+st[s[t+12]]+st[s[t+13]]+st[s[t+14]]+st[s[t+15]]).toLowerCase();if(!Nu(e))throw TypeError("Stringified UUID is invalid");return e}function Cn(s,t,e){s=s||{};var r=s.random||(s.rng||vT)();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 ET=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")}))},bT={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"},Jp={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"},ot={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"},Ir={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("."),f=>new Array(20-f.length).join("0")+f).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 bT[t]}static getBrowserTypeByAlias(t){return Jp[t]||""}}const X=/version\/(\d+(\.?_?\d+)+)/i,wT=[{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)}}}],PT=[{test:[/Roku\/DVP/],describe(s){const t=b.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,s);return{name:ot.Roku,version:t}}},{test:[/windows phone/i],describe(s){const t=b.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,s);return{name:ot.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:ot.Windows,version:t,versionName:e}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(s){const t={name:ot.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:ot.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:ot.iOS,version:t}}},{test:[/OpenHarmony/i],describe(s){const t=b.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,s);return{name:ot.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:ot.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:ot.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:ot.BlackBerry,version:t}}},{test:[/bada/i],describe(s){const t=b.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,s);return{name:ot.Bada,version:t}}},{test:[/tizen/i],describe(s){const t=b.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,s);return{name:ot.Tizen,version:t}}},{test:[/linux/i],describe(){return{name:ot.Linux}}},{test:[/CrOS/],describe(){return{name:ot.ChromeOS}}},{test:[/PlayStation 4/],describe(s){const t=b.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,s);return{name:ot.PlayStation4,version:t}}}],_T=[{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}}}],kT=[{test(s){return s.getBrowserName(!0)==="microsoft edge"},describe(s){if(/\sedg\//i.test(s))return{name:Ir.Blink};const e=b.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,s);return{name:Ir.EdgeHTML,version:e}}},{test:[/trident/i],describe(s){const t={name:Ir.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:Ir.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:Ir.Gecko},e=b.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:Ir.Blink}}},{test:[/(apple)?webkit/i],describe(s){const t={name:Ir.WebKit},e=b.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}}];class Kp{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(wT,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(PT,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(_T,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(kT,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 Do,ur,hr,vv,rs,Vi,lt,is,Oe,Ts,pr,vt,xe,Kn,zn,mr,Yn,Ft,Qn,re,xi,rt,Xn,Ol,xv,No,Cp,Tv,Ui,yv,Dl,Uv,Nl,$v,Zn,ea,Lo,Ev,zr,ta,$i,bv,sa,Vo,Rp,Bi,xo,wv,Uo,Pv,Yr,ra,Ht,_v,ns,Ll,le,$o,Ls,Ke,Bo,Ip,ia,Du,Qr,ys,Xr,Fo,Tt,Fi,gr,Ho,qo,Hi,kv,Ue,qi,Es,na,Zr,ji,Vl,Bv,jo,Ap,Go,Mp,Wo,Op,Cv,Jo,aa,oa,ca,Nu,Rv,Gi,Wi,He,we,Te,fr,as,Ko,De,Ji,zo,Ki,xl,da,os,ze,Iv,zi,Yo,la,Qo,yt,Yi,Xo,ua,pa,Zo,ma,ga,Sr,Vs,it,ei,ti,Ul,Fv,si,ri,ec,Dp,tc,bs,$l,Hv,fa,Sa,qt,Qi,cd,ii,Ja,Xi,dd,Bl,qv,vr,sc,ni,Zi,ld,Tr,Fl,rc,Np,Hl,jv,ql,Gv,Av,ai,Ne,ic,Lp,en,ud,va,Lu,tn,At,Mv,cs,ws,oi,Ov,Y,Ta,ya,jl,Et,Yt,jt,Ea,bt,ba,Ye,yr,Cn,Qe,mt,wa,Vu,$e,je,Pa,_a,nc,Vp,Dv,ac,oc,cc,sn,xs,Wl,Us,vi,dc,xp,Jl,Wv,Kl,Jv,ka,Ps,Ra,Ia,rn,ds,nt,ci,Aa,zl,Gt,Cs,Xe,Er,nn,Ma,Ze,et,lc,uc,an,Oa,hc,Da,on,$s,Na,xu,pc,Up,Yl,Kv,mc,$p,Ql,zv,Xl,Yv,Zl,Qv,eu,Xv,tu,Zv,gc,Bp,di,Ka,su,ls,cn,li,La,fc,Bs,ru,br,Va,Sc,Fp,iu,eT,nu,tT,au,sT,ou,rT,vc,Tc,yc,xa,Ua,$a,Ec,bc,Ba,Mt,_s,ks,dn,ln,wr,wc,cu,iT,du,nT,lu,aT,uu,oT,Pc,_c,Pr,_r,kr,kc,Fa,Ha,ui,un,qa,hn,Cr,Fs,pu,cT,Cc,Hp,mu,dT,gu,lT,Ic,Ac,ut,H,fu,wt,pn,mn,gn,Mc,Wt,Hs,ht,qs,Ot,Rr,Rn,Su,uT,vu,hT,Tu,pT,Oc,qp,yu,mT,Eu,gT,bu,wp,fT,Pt,Qt,fn,hd,wu,ST,Sn,pd,Pu,vT,_u,TT,Dc,us,te,pt,Nt,Nv,Nc,Lc,Vc,Ir,ja,Jt,Dt,hi,Ga,js,Wa,_e,tt,gt,vn,pi,Tn,yn,mi,Gs,Ws,gi,En,_t,fi,kt,qe,xc,jp,ku,yT,Cu,ET,Ru,bT,Uc,Gp,$c,Wp,bn,md,Iu,Pp,wT,Au,PT,Bc,Jp,Fc,Kp,Hc,zp,Mu,_T,qc,Yp,jc,Qp,Kt,ye,Lv,Si,wn,Pn,Gc,Ou,kT,_n,Fe,kn,Vv;"use strict";var HN=Object.defineProperty;var qN=(Ce,Pe,Re)=>Pe in Ce?HN(Ce,Pe,{enumerable:!0,configurable:!0,writable:!0,value:Re}):Ce[Pe]=Re;var p=(Ce,Pe,Re)=>(qN(Ce,typeof Pe!="symbol"?Pe+"":Pe,Re),Re),kp=(Ce,Pe,Re)=>{if(!Pe.has(Ce))throw TypeError("Cannot "+Re)};var a=(Ce,Pe,Re)=>(kp(Ce,Pe,"read from private field"),Re?Re.call(Ce):Pe.get(Ce)),m=(Ce,Pe,Re)=>{if(Pe.has(Ce))throw TypeError("Cannot add the same private member more than once");Pe instanceof WeakSet?Pe.add(Ce):Pe.set(Ce,Re)},g=(Ce,Pe,Re,gd)=>(kp(Ce,Pe,"write to private field"),gd?gd.call(Ce,Re):Pe.set(Ce,Re),Re);var D=(Ce,Pe,Re)=>(kp(Ce,Pe,"access private method"),Re);function Ce(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:Ce});function Pe(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:Pe});var Re,gd=new Uint8Array(16);function CT(){if(!Re&&(Re=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!Re))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Re(gd)}const RT=/^(?:[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 Uu(s){return typeof s=="string"&&RT.test(s)}for(var st=[],$u=0;$u<256;++$u)st.push(($u+256).toString(16).substr(1));function IT(s){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(st[s[t+0]]+st[s[t+1]]+st[s[t+2]]+st[s[t+3]]+"-"+st[s[t+4]]+st[s[t+5]]+"-"+st[s[t+6]]+st[s[t+7]]+"-"+st[s[t+8]]+st[s[t+9]]+"-"+st[s[t+10]]+st[s[t+11]]+st[s[t+12]]+st[s[t+13]]+st[s[t+14]]+st[s[t+15]]).toLowerCase();if(!Uu(e))throw TypeError("Stringified UUID is invalid");return e}function In(s,t,e){s=s||{};var r=s.random||(s.rng||CT)();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 IT(r)}const AT=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")}))},MT={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"},Xp={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"},ot={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"},Ar={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("."),f=>new Array(20-f.length).join("0")+f).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 MT[t]}static getBrowserTypeByAlias(t){return Xp[t]||""}}const X=/version\/(\d+(\.?_?\d+)+)/i,OT=[{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)}}}],DT=[{test:[/Roku\/DVP/],describe(s){const t=b.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,s);return{name:ot.Roku,version:t}}},{test:[/windows phone/i],describe(s){const t=b.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,s);return{name:ot.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:ot.Windows,version:t,versionName:e}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(s){const t={name:ot.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:ot.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:ot.iOS,version:t}}},{test:[/OpenHarmony/i],describe(s){const t=b.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,s);return{name:ot.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:ot.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:ot.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:ot.BlackBerry,version:t}}},{test:[/bada/i],describe(s){const t=b.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,s);return{name:ot.Bada,version:t}}},{test:[/tizen/i],describe(s){const t=b.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,s);return{name:ot.Tizen,version:t}}},{test:[/linux/i],describe(){return{name:ot.Linux}}},{test:[/CrOS/],describe(){return{name:ot.ChromeOS}}},{test:[/PlayStation 4/],describe(s){const t=b.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,s);return{name:ot.PlayStation4,version:t}}}],NT=[{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}}}],LT=[{test(s){return s.getBrowserName(!0)==="microsoft edge"},describe(s){if(/\sedg\//i.test(s))return{name:Ar.Blink};const e=b.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,s);return{name:Ar.EdgeHTML,version:e}}},{test:[/trident/i],describe(s){const t={name:Ar.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:Ar.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:Ar.Gecko},e=b.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:Ar.Blink}}},{test:[/(apple)?webkit/i],describe(s){const t={name:Ar.WebKit},e=b.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}}];class Zp{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(OT,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(DT,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(NT,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(LT,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 zp{static getParser(t,e=!1,r=null){if(typeof t!="string")throw new Error("UserAgent should be a string");return new Kp(t,e,r)}static parse(t,e=null){return new Kp(t,e).getResult()}static get BROWSER_MAP(){return Jp}static get ENGINE_MAP(){return Ir}static get OS_MAP(){return ot}static get PLATFORMS_MAP(){return Q}}const Ja="chrome",Yp="opera",Qp="firefox",Xp="iexplorer",Zp="safari",em="nwjs",tm="electron",sm="react-native",Vu="unknown",md={Chrome:Ja,Chromium:Ja,Opera:Yp,Firefox:Qp,"Internet Explorer":Xp,Safari:Zp};function CT(){const{userAgent:s}=navigator,t={name:Vu,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=Ja,t.version=e)}else t.name=Ja,t.version=s.match(/Chrome\/([\d.]+)/)[1];return t}function RT(){const{userAgent:s}=navigator;if(s.match(/Electron/)){const t=s.match(/Electron\/([\d.]+)/)[1];return{name:tm,version:t}}return null}function IT(){const{userAgent:s}=navigator;if(s.match(/JitsiMeetNW/)){const t=s.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:em,version:t}}}function AT(){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:sm,version:t}}function MT(s){let t;const e=[AT,RT,IT];for(let i=0;i<e.length;i+=1)if(t=e[i](),t)return t;const r=s.getBrowserName();return r in md?{name:md[r],version:s.getBrowserVersion()}:(t=CT(),t||{name:Vu,version:void 0})}class OT{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=zp.getParser(navigator.userAgent),typeof t=="undefined"){const i=MT(this._bowser);e=i.name,r=i.version}else t.name in md?(e=md[t.name],r=t.version):(e=Vu,r=void 0);this._name=e,this._version=r}getName(){return this._name}isChrome(){return this._name===Ja}isOpera(){return this._name===Yp}isFirefox(){return this._name===Qp}isIExplorer(){return this._name===Xp}isSafari(){return this._name===Zp}isNWJS(){return this._name===em}isElectron(){return this._name===tm}isReactNative(){return this._name===sm||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 DT extends OT{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 ye=new DT;var gt={},NT={get exports(){return gt},set exports(s){gt=s}},Rn=typeof Reflect=="object"?Reflect:null,rm=Rn&&typeof Rn.apply=="function"?Rn.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},gd;Rn&&typeof Rn.ownKeys=="function"?gd=Rn.ownKeys:Object.getOwnPropertySymbols?gd=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:gd=function(t){return Object.getOwnPropertyNames(t)};function LT(s){console&&console.warn&&console.warn(s)}var im=Number.isNaN||function(t){return t!==t};function le(){le.init.call(this)}NT.exports=le,gt.once=$T,le.EventEmitter=le,le.prototype._events=void 0,le.prototype._eventsCount=0,le.prototype._maxListeners=void 0;var nm=10;function fd(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(le,"defaultMaxListeners",{enumerable:!0,get:function(){return nm},set:function(s){if(typeof s!="number"||s<0||im(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");nm=s}}),le.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},le.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||im(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 am(s){return s._maxListeners===void 0?le.defaultMaxListeners:s._maxListeners}le.prototype.getMaxListeners=function(){return am(this)},le.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")rm(d,this,e);else for(var l=d.length,u=um(d,l),r=0;r<l;++r)rm(u[r],this,e);return!0};function om(s,t,e,r){var i,n,o;if(fd(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=am(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,LT(c)}return s}le.prototype.addListener=function(t,e){return om(this,t,e,!1)},le.prototype.on=le.prototype.addListener,le.prototype.prependListener=function(t,e){return om(this,t,e,!0)};function VT(){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 cm(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=VT.bind(r);return i.listener=e,r.wrapFn=i,i}le.prototype.once=function(t,e){return fd(e),this.on(t,cm(this,t,e)),this},le.prototype.prependOnceListener=function(t,e){return fd(e),this.prependListener(t,cm(this,t,e)),this},le.prototype.removeListener=function(t,e){var r,i,n,o,c;if(fd(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():xT(r,n),r.length===1&&(i[t]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",t,c||e)}return this},le.prototype.off=le.prototype.removeListener,le.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 dm(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?UT(i):um(i,i.length)}le.prototype.listeners=function(t){return dm(this,t,!0)},le.prototype.rawListeners=function(t){return dm(this,t,!1)},le.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):lm.call(s,t)},le.prototype.listenerCount=lm;function lm(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}le.prototype.eventNames=function(){return this._eventsCount>0?gd(this._events):[]};function um(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function xT(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function UT(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function $T(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))}hm(s,t,n,{once:!0}),t!=="error"&&BT(s,i,{once:!0})})}function BT(s,t,e){typeof s.on=="function"&&hm(s,"error",t,e)}function hm(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 FT=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 HT{constructor(){p(this,"events");this.events=[]}add(t){this.events.push(t)}flush(){return{entries:this.events.splice(0,25)}}}class qT extends gt{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}/api/v1/message`,this.eventStore=new HT}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),FT.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 pm;(function(s){s.CHROMIUM="chromum",s.FIREFOX="firefox",s.SAFARI="safari"})(pm||(pm={}));const mm={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var Qt;(function(s){s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.SPEAKER="SPEAKER",s.SCREENSHARE="SCREENSHARE"})(Qt||(Qt={}));var gm;(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"})(gm||(gm={}));function Ar(s){return s?s.split(".").slice(0,2).concat(["0","0"]).join("."):""}function Sd({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function vd({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}const fm=240,Sm=720,vm=8,Tm=3,Td=10,yd=.02,Ed=.03;function Ws({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 ym({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 Em({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function bm({packetsLost:s,packetsSent:t,jitter:e}){const i=Ws({stat:Em({packetsLost:s,packetsSent:t}),weight:.7,rangeMin:0,rangeMax:Td,rangeRankingDirection:"UP"}),o=Ws({stat:e,weight:.3,rangeMin:yd,rangeMax:Ed,rangeRankingDirection:"UP"});return i+o}function jT({frameWidth:s,isScreenShare:t}){return s<(t?Sm:fm)}function GT({framesPerSecond:s,isScreenShare:t}){return s<(t?Tm:vm)}function WT({framesEncoded:s}){return s===0}function wm({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsSent:r,jitter:i,isScreenShare:n,framesEncoded:o}){const c=Ws({stat:Em({packetsLost:e,packetsSent:r}),weight:1,rangeMin:0,rangeMax:Td,rangeRankingDirection:"UP"}),d=Ws({stat:i,weight:1,rangeMin:yd,rangeMax:Ed,rangeRankingDirection:"UP"}),l=jT({frameWidth:s,isScreenShare:n}),u=GT({framesPerSecond:t,isScreenShare:n}),h=WT({framesEncoded:o,isScreenShare:n});return ym({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:h,jitterQuality:d,packetsLostQuality:c})}function Pm({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}function _m({concealmentEvents:s,packetsLost:t,packetsReceived:e,jitter:r}){const n=Ws({stat:s,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),o=.5,c=Ws({stat:Pm({packetsLost:t,packetsReceived:e}),weight:o,rangeMin:0,rangeMax:Td,rangeRankingDirection:"UP"}),l=Ws({stat:r,weight:.3,rangeMin:yd,rangeMax:Ed,rangeRankingDirection:"UP"});return n+c+l}function JT({framesDecoded:s}){return s===0}function KT({framesPerSecond:s,isScreenShare:t}){return s<(t?Tm:vm)}function zT({frameWidth:s,isScreenShare:t}){return s<(t?Sm:fm)}function km({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsReceived:r,jitter:i,isScreenShare:n,framesDecoded:o}){const c=Ws({stat:Pm({packetsLost:e,packetsReceived:r}),weight:1,rangeMin:0,rangeMax:Td,rangeRankingDirection:"UP"}),d=Ws({stat:i,weight:1,rangeMin:yd,rangeMax:Ed,rangeRankingDirection:"UP"}),l=zT({frameWidth:s,isScreenShare:n}),u=KT({framesPerSecond:t,isScreenShare:n}),h=JT({framesDecoded:o,isScreenShare:n});return ym({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:h,jitterQuality:d,packetsLostQuality:c})}class Js{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=Js.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=Js.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 em{static getParser(t,e=!1,r=null){if(typeof t!="string")throw new Error("UserAgent should be a string");return new Zp(t,e,r)}static parse(t,e=null){return new Zp(t,e).getResult()}static get BROWSER_MAP(){return Xp}static get ENGINE_MAP(){return Ar}static get OS_MAP(){return ot}static get PLATFORMS_MAP(){return Q}}const za="chrome",tm="opera",sm="firefox",rm="iexplorer",im="safari",nm="nwjs",am="electron",om="react-native",Bu="unknown",fd={Chrome:za,Chromium:za,Opera:tm,Firefox:sm,"Internet Explorer":rm,Safari:im};function VT(){const{userAgent:s}=navigator,t={name:Bu,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=za,t.version=e)}else t.name=za,t.version=s.match(/Chrome\/([\d.]+)/)[1];return t}function xT(){const{userAgent:s}=navigator;if(s.match(/Electron/)){const t=s.match(/Electron\/([\d.]+)/)[1];return{name:am,version:t}}return null}function UT(){const{userAgent:s}=navigator;if(s.match(/JitsiMeetNW/)){const t=s.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:nm,version:t}}}function $T(){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:om,version:t}}function BT(s){let t;const e=[$T,xT,UT];for(let i=0;i<e.length;i+=1)if(t=e[i](),t)return t;const r=s.getBrowserName();return r in fd?{name:fd[r],version:s.getBrowserVersion()}:(t=VT(),t||{name:Bu,version:void 0})}class FT{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=em.getParser(navigator.userAgent),typeof t=="undefined"){const i=BT(this._bowser);e=i.name,r=i.version}else t.name in fd?(e=fd[t.name],r=t.version):(e=Bu,r=void 0);this._name=e,this._version=r}getName(){return this._name}isChrome(){return this._name===za}isOpera(){return this._name===tm}isFirefox(){return this._name===sm}isIExplorer(){return this._name===rm}isSafari(){return this._name===im}isNWJS(){return this._name===nm}isElectron(){return this._name===am}isReactNative(){return this._name===om||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 HT extends FT{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 Ee=new HT;var ft={},qT={get exports(){return ft},set exports(s){ft=s}},An=typeof Reflect=="object"?Reflect:null,cm=An&&typeof An.apply=="function"?An.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},Sd;An&&typeof An.ownKeys=="function"?Sd=An.ownKeys:Object.getOwnPropertySymbols?Sd=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Sd=function(t){return Object.getOwnPropertyNames(t)};function jT(s){console&&console.warn&&console.warn(s)}var dm=Number.isNaN||function(t){return t!==t};function ue(){ue.init.call(this)}qT.exports=ue,ft.once=KT,ue.EventEmitter=ue,ue.prototype._events=void 0,ue.prototype._eventsCount=0,ue.prototype._maxListeners=void 0;var lm=10;function vd(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 lm},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+".");lm=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 um(s){return s._maxListeners===void 0?ue.defaultMaxListeners:s._maxListeners}ue.prototype.getMaxListeners=function(){return um(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")cm(d,this,e);else for(var l=d.length,u=fm(d,l),r=0;r<l;++r)cm(u[r],this,e);return!0};function hm(s,t,e,r){var i,n,o;if(vd(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=um(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,jT(c)}return s}ue.prototype.addListener=function(t,e){return hm(this,t,e,!1)},ue.prototype.on=ue.prototype.addListener,ue.prototype.prependListener=function(t,e){return hm(this,t,e,!0)};function GT(){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 pm(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=GT.bind(r);return i.listener=e,r.wrapFn=i,i}ue.prototype.once=function(t,e){return vd(e),this.on(t,pm(this,t,e)),this},ue.prototype.prependOnceListener=function(t,e){return vd(e),this.prependListener(t,pm(this,t,e)),this},ue.prototype.removeListener=function(t,e){var r,i,n,o,c;if(vd(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():WT(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 mm(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?JT(i):fm(i,i.length)}ue.prototype.listeners=function(t){return mm(this,t,!0)},ue.prototype.rawListeners=function(t){return mm(this,t,!1)},ue.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):gm.call(s,t)},ue.prototype.listenerCount=gm;function gm(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?Sd(this._events):[]};function fm(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function WT(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function JT(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function KT(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))}Sm(s,t,n,{once:!0}),t!=="error"&&zT(s,i,{once:!0})})}function zT(s,t,e){typeof s.on=="function"&&Sm(s,"error",t,e)}function Sm(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 YT=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 QT{constructor(){p(this,"events");this.events=[]}add(t){this.events.push(t)}flush(){return{entries:this.events.splice(0,25)}}}class XT extends ft{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}/api/v1/message`,this.eventStore=new QT}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),YT.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 vm;(function(s){s.CHROMIUM="chromum",s.FIREFOX="firefox",s.SAFARI="safari"})(vm||(vm={}));const Tm={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var Xt;(function(s){s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.SPEAKER="SPEAKER",s.SCREENSHARE="SCREENSHARE"})(Xt||(Xt={}));var ym;(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"})(ym||(ym={}));function Mr(s){return s?s.split(".").slice(0,2).concat(["0","0"]).join("."):""}function Td({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function yd({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}const Em=240,bm=720,wm=8,Pm=3,Ed=10,bd=.02,wd=.03;function Js({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 _m({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 km({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function Cm({packetsLost:s,packetsSent:t,jitter:e}){const i=Js({stat:km({packetsLost:s,packetsSent:t}),weight:.7,rangeMin:0,rangeMax:Ed,rangeRankingDirection:"UP"}),o=Js({stat:e,weight:.3,rangeMin:bd,rangeMax:wd,rangeRankingDirection:"UP"});return i+o}function ZT({frameWidth:s,isScreenShare:t}){return s<(t?bm:Em)}function ey({framesPerSecond:s,isScreenShare:t}){return s<(t?Pm:wm)}function ty({framesEncoded:s}){return s===0}function Rm({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsSent:r,jitter:i,isScreenShare:n,framesEncoded:o}){const c=Js({stat:km({packetsLost:e,packetsSent:r}),weight:1,rangeMin:0,rangeMax:Ed,rangeRankingDirection:"UP"}),d=Js({stat:i,weight:1,rangeMin:bd,rangeMax:wd,rangeRankingDirection:"UP"}),l=ZT({frameWidth:s,isScreenShare:n}),u=ey({framesPerSecond:t,isScreenShare:n}),h=ty({framesEncoded:o,isScreenShare:n});return _m({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:h,jitterQuality:d,packetsLostQuality:c})}function Im({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}function Am({concealmentEvents:s,packetsLost:t,packetsReceived:e,jitter:r}){const n=Js({stat:s,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),o=.5,c=Js({stat:Im({packetsLost:t,packetsReceived:e}),weight:o,rangeMin:0,rangeMax:Ed,rangeRankingDirection:"UP"}),l=Js({stat:r,weight:.3,rangeMin:bd,rangeMax:wd,rangeRankingDirection:"UP"});return n+c+l}function sy({framesDecoded:s}){return s===0}function ry({framesPerSecond:s,isScreenShare:t}){return s<(t?Pm:wm)}function iy({frameWidth:s,isScreenShare:t}){return s<(t?bm:Em)}function Mm({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsReceived:r,jitter:i,isScreenShare:n,framesDecoded:o}){const c=Js({stat:Im({packetsLost:e,packetsReceived:r}),weight:1,rangeMin:0,rangeMax:Ed,rangeRankingDirection:"UP"}),d=Js({stat:i,weight:1,rangeMin:bd,rangeMax:wd,rangeRankingDirection:"UP"}),l=iy({frameWidth:s,isScreenShare:n}),u=ry({framesPerSecond:t,isScreenShare:n}),h=sy({framesDecoded:o,isScreenShare:n});return _m({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:h,jitterQuality:d,packetsLostQuality:c})}class Ks{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=Ks.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=Ks.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 Cm extends gt{constructor(e){super();p(this,"call");p(this,"timeOut");this.call=new Js(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 YT=8,QT=1/1e3;class XT extends Cm{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(Js.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)*YT/(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*QT)})}}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 xu extends Cm{constructor(e,r=Js.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 ZT extends xu{constructor(t){super(t,Js.isHost)}}class ey extends xu{constructor(t){super(t,Js.isRelay)}}class ty extends xu{constructor(t){super(t,Js.isReflexive)}}class sy{constructor(){p(this,"ipInformation",null)}async getIPDetails({peerId:t,apiHostnames:e,logger:r}){var i,n,o;if(!this.ipInformation){try{const c=`https://${e.location}`,l=await(await fetch(c)).json();if(((i=l.loc)==null?void 0:i.length)>5)return this.ipInformation=l,(n=this.ipInformation)!=null&&n.ip&&(this.ipInformation.ip=Ar(this.ipInformation.ip)),l;throw Error("Insufficient data")}catch(c){r.error("callstats::ipDetails:: failed to fetch ip using location service",{error:c})}try{const c=await fetch(`https://${e.locationLegacy}/?token=3c493932b0624c&peerId=${t}`,{method:"POST"});this.ipInformation=await c.json(),(o=this.ipInformation)!=null&&o.ip&&(this.ipInformation.ip=Ar(this.ipInformation.ip))}catch(c){r.error("callstats::ipDetails:: failed to fetch ip using legacy location service",{error:c})}}return this.ipInformation}resetCache(){this.ipInformation=null}}const Rm=new sy,Im=[{urls:"turn:turn.dyte.in:443?transport=tcp",username:"dyte",credential:"dytein",credentialType:"password"},{urls:"turn:turn.dyte.in:3478?transport=udp",username:"dyte",credential:"dytein",credentialType:"password"}];function Am(s){const[t,e]=s.split(",");return{coords:{latitude:Number(t),longitude:Number(e)}}}class Mm{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 Om extends gt{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,"ipDetails");p(this,"callStatsInstance");this.observer=new gt}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,R,U,D,x,B,q,Z,se,at,kt,Kt;const c=e,d=new Mm,l=r.length?new Set(r):void 0,u=[],h=[],f=[],S=new Map,E=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:T}=A,{selected:w}=A,F=A,_e={nominated:T!=null?T:w,currentRoundTripTime:F.currentRoundTripTime,totalRoundTripTime:F.totalRoundTripTime,bytesReceived:F.bytesReceived,bytesSent:F.bytesSent,availableOutgoingBitrate:F.availableOutgoingBitrate,availableIncomingBitrate:F.availableIncomingBitrate,lastPacketReceivedTimestamp:F.lastPacketReceivedTimestamp,lastPacketSentTimestamp:F.lastPacketSentTimestamp,localCandidateId:F.localCandidateId,remoteCandidateId:F.remoteCandidateId,bytesDiscardedOnSend:F.bytesDiscardedOnSend,packetsSent:F.packetsSent,packetsReceived:F.packetsReceived,packetsDiscardedOnSend:F.packetsDiscardedOnSend};f.push(_e),(A.nominated===!0||A.selected===!0)&&(d.candidatePair=_e);break}case"transport":{const T=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:T.bytesReceived,bytesSent:T.bytesSent,packetsSent:T.packetsSent,packetsReceived:T.packetsReceived,dtlsCipher:T.dtlsCipher,dtlsState:T.dtlsState,iceRole:T.iceRole};if(d.transport=w,o){if(o.producing){const F=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,F,w)}if(o.consuming){const F=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,F,w)}}break}case"remote-inbound-rtp":{const T=A,w={jitter:T.jitter,fractionLost:T.fractionLost,roundTripTime:T.roundTripTime,roundTripTimeMeasurements:T.roundTripTimeMeasurements,totalRoundTripTime:T.totalRoundTripTime,packetsLost:T.packetsLost};d.remoteInboundRtp.set(T.localId,w);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(A.id))break;const T=A,w=n||this.outboundProducerMap.get(A.id),F=this.pausedProducerMap.get(w);if(F){if(F.lastReportCalculated===!0)break;this.pausedProducerMap.set(w,{lastReportCalculated:!0})}this.overallProducersStatsMap[w]||(this.overallProducersStatsMap[w]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const _e=this.overallProducersStatsMap[w];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.outboundProducerMap.has(A.id)){d.staleProducerStreamMap=!0;break}const Le=this.callStatsInstance.producers.get(w);if(((k=Le==null?void 0:Le.track)==null?void 0:k.readyState)==="ended")break;d.producerStreamMap.has(w)||d.producerStreamMap.set(w,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const V={bytesSent:T.bytesSent,packetsSent:T.packetsSent,nackCount:T.nackCount,ssrc:T.ssrc,mid:T.mid,active:T.active,codecId:T.codecId,headerBytesSent:T.headerBytesSent||0,totalPacketSendDelay:T.totalPacketSendDelay||0};if(T.mediaType==="video"||T.kind==="video"){const C=T,Be={frameHeight:C.frameHeight,frameWidth:C.frameWidth,framesEncoded:C.framesEncoded,framesDropped:C.framesDropped,framesPerSecond:C.framesPerSecond,framesSent:C.framesSent,keyFramesEncoded:C.keyFramesEncoded,firCount:C.firCount,encoderImplementation:C.encoderImplementation,hugeFramesSent:C.hugeFramesSent,pliCount:C.pliCount,qpSum:C.qpSum,qualityLimitationDurations:C.qualityLimitationDurations,qualityLimitationReason:C.qualityLimitationReason,qualityLimitationResolutionChanges:C.qualityLimitationResolutionChanges,totalEncodeTime:C.targetBitrate,totalPacketSendDelay:C.totalPacketSendDelay,retransmittedBytesSent:C.retransmittedBytesSent,retransmittedPacketsSent:C.retransmittedPacketsSent,scalabilityMode:C.scalabilityMode,powerEfficientEncoder:C.powerEfficientEncoder,...V};d.outboundVideoRtp.set(A.id,Be),d.producerStreamMap.get(w).outboundVideoRtpId.push(A.id),this.processOutboundProducerVideoStats(w,_e,Be)}else if(T.mediaType==="audio"||T.kind==="audio"){const C=T,Be={retransmittedBytesSent:C.retransmittedBytesSent,retransmittedPacketsSent:C.retransmittedPacketsSent,...V};d.outboundAudioRtp.set(A.id,Be),d.producerStreamMap.get(w).outboundAudioRtpId.push(A.id),this.processOutboundProducerAudioStats(w,_e,Be)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(A.id))break;const T=A,w=n||this.inboundConsumerMap.get(A.id),F=this.pausedConsumerMap.get(w);if(F){if(F.lastReportCalculated===!0)break;this.pausedConsumerMap.set(w,{lastReportCalculated:!0})}if(T.ssrc===1234)break;this.overallConsumersStatsMap[w]||(this.overallConsumersStatsMap[w]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const _e=this.overallConsumersStatsMap[w];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.inboundConsumerMap.has(A.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(w)||d.consumerStreamMap.set(w,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Le={bytesReceived:T.bytesReceived,packetsReceived:T.packetsReceived,packetsLost:T.packetsLost>=0?T.packetsLost:0,jitter:T.jitter,nackCount:T.nackCount,jitterBufferDelay:T.jitterBufferDelay,jitterBufferEmittedCount:T.jitterBufferEmittedCount,lastPacketReceivedTimestamp:T.lastPacketReceivedTimestamp,ssrc:T.ssrc,mid:T.mid,codecId:T.codecId,headerBytesReceived:T.headerBytesReceived||0,packetsDiscarded:T.packetsDiscarded||0,jitterBufferMinimumDelay:T.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:T.jitterBufferTargetDelay||0};if(T.mediaType==="video"||T.kind==="video"){const V=T,C={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,...Le};C.score=km({frameWidth:C.frameWidth||0,framesDecoded:(C.framesDecoded||0)-(((I=this.videoConsumerToStatsMap.get(w))==null?void 0:I.framesDecoded)||0),framesPerSecond:C.framesPerSecond||0,packetsLost:(C.packetsLost||0)-(((R=this.videoConsumerToStatsMap.get(w))==null?void 0:R.packetsLost)||0),packetsReceived:(C.packetsReceived||0)-(((U=this.videoConsumerToStatsMap.get(w))==null?void 0:U.packetsReceived)||0),jitter:C.jitter||0,isScreenShare:this.screenShareConsumers.has(w)}),E.set(w,{score:+(C.score*10).toFixed(),frameWidth:C.frameWidth||0,frameHeight:C.frameHeight||0,framesPerSecond:C.framesPerSecond||0,packetsLostPercentage:vd({packetsLost:(C.packetsLost||0)-(((D=this.videoConsumerToStatsMap.get(w))==null?void 0:D.packetsLost)||0),packetsReceived:(C.packetsReceived||0)-(((x=this.videoConsumerToStatsMap.get(w))==null?void 0:x.packetsReceived)||0)}),jitter:C.jitter||0,isScreenShare:this.screenShareConsumers.has(w),bitrate:((C.bytesReceived||0)-(((B=this.videoConsumerToStatsMap.get(w))==null?void 0:B.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(w,C),d.inboundVideoRtp.set(A.id,C),d.consumerStreamMap.get(w).inboundVideoRtpId.push(A.id),this.processInboundConsumerVideoStats(w,_e,C)}else if(T.mediaType==="audio"||T.kind==="audio"){const V=T,C={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,...Le};C.score=_m({concealmentEvents:(C.concealmentEvents||0)-(((q=this.audioConsumerToStatsMap.get(w))==null?void 0:q.concealmentEvents)||0),packetsLost:(C.packetsLost||0)-(((Z=this.audioConsumerToStatsMap.get(w))==null?void 0:Z.packetsLost)||0),packetsReceived:(C.packetsReceived||0)-(((se=this.audioConsumerToStatsMap.get(w))==null?void 0:se.packetsReceived)||0),jitter:C.jitter||0}),E.set(w,{score:+(C.score*10).toFixed(),packetsLostPercentage:vd({packetsLost:(C.packetsLost||0)-(((at=this.audioConsumerToStatsMap.get(w))==null?void 0:at.packetsLost)||0),packetsReceived:(C.packetsReceived||0)-(((kt=this.audioConsumerToStatsMap.get(w))==null?void 0:kt.packetsReceived)||0)}),jitter:C.jitter||0,isScreenShare:this.screenShareConsumers.has(w),bitrate:((C.bytesReceived||0)-(((Kt=this.audioConsumerToStatsMap.get(w))==null?void 0:Kt.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(w,C),d.inboundAudioRtp.set(A.id,C),d.consumerStreamMap.get(w).inboundAudioRtpId.push(A.id),this.processInboundConsumerAudioStats(w,_e,C)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}}}if(d.producerStreamMap.forEach((A,T)=>{var w,F,_e,Le,V,C,Be,Gc,Wc,Jc,Kc,zc,Yc,Qc,Xc,Zc,ed,td,sd,rd,id,nd,ad;if(A.outboundVideoRtpId.length>0){const ge=[];A.outboundVideoRtpId.forEach(yp=>{ge.push(d.outboundVideoRtp.get(yp))});const ee=this.getWorkingSimulcastVideoStats(ge);ee.score=wm({frameWidth:ee.frameWidth||0,framesPerSecond:ee.framesPerSecond||0,jitter:((w=ee.remoteData)==null?void 0:w.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsSent:(ee.packetsSent||0)-(((F=this.videoProducerToStatsMap.get(T))==null?void 0:F.packetsSent)||0),packetsLost:(((_e=ee.remoteData)==null?void 0:_e.packetsLost)||0)-(((V=(Le=this.videoProducerToStatsMap.get(T))==null?void 0:Le.remoteData)==null?void 0:V.packetsLost)||0),framesEncoded:(ee.framesEncoded||0)-(((C=this.videoProducerToStatsMap.get(T))==null?void 0:C.framesEncoded)||0)}),S.set(T,{score:+(ee.score*10).toFixed(),frameWidth:ee.frameWidth||0,frameHeight:ee.frameHeight||0,framesPerSecond:ee.framesPerSecond||0,jitter:((Be=ee.remoteData)==null?void 0:Be.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsLostPercentage:Sd({packetsSent:(ee.packetsSent||0)-(((Gc=this.videoProducerToStatsMap.get(T))==null?void 0:Gc.packetsSent)||0),packetsLost:(((Wc=ee.remoteData)==null?void 0:Wc.packetsLost)||0)-(((Kc=(Jc=this.videoProducerToStatsMap.get(T))==null?void 0:Jc.remoteData)==null?void 0:Kc.packetsLost)||0)}),bitrate:((ee.bytesSent||0)-(((zc=this.videoProducerToStatsMap.get(T))==null?void 0:zc.bytesSent)||0))*8/7,cpuLimitations:ee.qualityLimitationReason==="cpu",bandwidthLimitations:ee.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(T,ee)}else if(A.outboundAudioRtpId.length>0){const ge=d.outboundAudioRtp.get(A.outboundAudioRtpId[0]);ge.score=bm({packetsSent:(ge.packetsSent||0)-(((Yc=this.audioProducerToStatsMap.get(T))==null?void 0:Yc.packetsSent)||0),packetsLost:(((Qc=ge.remoteData)==null?void 0:Qc.packetsLost)||0)-(((Zc=(Xc=this.audioProducerToStatsMap.get(T))==null?void 0:Xc.remoteData)==null?void 0:Zc.packetsLost)||0),jitter:((ed=ge.remoteData)==null?void 0:ed.jitter)||0}),S.set(T,{score:+(ge.score*10).toFixed(),bitrate:((ge.bytesSent||0)-(((td=this.audioProducerToStatsMap.get(T))==null?void 0:td.bytesSent)||0))*8/7,packetsLostPercentage:Sd({packetsSent:(ge.packetsSent||0)-(((sd=this.audioProducerToStatsMap.get(T))==null?void 0:sd.packetsSent)||0),packetsLost:(((rd=ge.remoteData)==null?void 0:rd.packetsLost)||0)-(((nd=(id=this.audioProducerToStatsMap.get(T))==null?void 0:id.remoteData)==null?void 0:nd.packetsLost)||0)}),jitter:((ad=ge.remoteData)==null?void 0:ad.jitter)||0,isScreenShare:this.screenShareProducers.has(T)}),this.audioProducerToStatsMap.set(T,ge)}}),f.forEach(A=>{const T=u.find(F=>F.id===A.localCandidateId?(A.localCandidateId=F.id,F):null),w=h.find(F=>F.id===A.remoteCandidateId?(A.remoteCandidateId=F.id,F):null);T&&(A.localCandidateType=T.type,A.localCandidateAddress=Ar(T.address),A.localCandidatePort=T.port,A.localCandidateProtocol=T.protocol,A.localCandidateUrl=T.url,A.localCandidateNetworkType=T.networkType,A.localCandidateRelatedAddress=Ar(T.relatedAddress),A.localCandidateRelatedPort=T.relatedPort),w&&(A.remoteCandidateType=w.type,A.remoteCandidateAddress=Ar(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=f),d.transport&&!d.transport.roundTripTime){let A=0,T=0;d.remoteInboundRtp.forEach((w,F)=>{w.roundTripTime&&w.roundTripTime>A&&(A=w.roundTripTime,T=w.totalRoundTripTime)}),d.transport.roundTripTime=A,d.transport.totalRoundTripTime=T}if(E.size>0)try{this.observer.emit("consumer_score",E)}catch(A){}if(S.size>0)try{this.observer.emit("producer_score",S)}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||Im},i=new Promise((u,h)=>{try{const f=new ZT(r);f.addListener("done",u),f.addListener("failed",()=>{u({connectivity:!1})}),f.start(2e3)}catch(f){h(f)}}),n=new Promise((u,h)=>{try{const f=new ey(r);f.addListener("done",u),f.addListener("failed",()=>{u({connectivity:!1})}),f.start(2e3)}catch(f){h(f)}}),o=new Promise((u,h)=>{try{const f=new ty(r);f.addListener("done",u),f.addListener("failed",()=>{u({connectivity:!1})}),f.start(2e3)}catch(f){h(f)}}),[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||Im},d=new XT(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 getIPDetails(){var e,r;try{return this.ipDetails||(this.ipDetails=await Rm.getIPDetails({peerId:(e=this.callStatsInstance)==null?void 0:e.peerId,apiHostnames:(r=this.callStatsInstance)==null?void 0:r.apiHostnames,logger:this.callStatsInstance.logger})),this.ipDetails}catch(i){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 c,d;if(r){const l=await this.getIPDetails();return{ipDetails:l,effectiveNetworkType:(c=navigator.connection)==null?void 0:c.effectiveType,location:l!=null&&l.loc?Am(l==null?void 0:l.loc):void 0}}const[i,n,o]=await Promise.all([this.getConnectivity(e),this.getThroughput(e),this.getIPDetails()]);return{ipDetails:o,effectiveNetworkType:(d=navigator.connection)==null?void 0:d.effectiveType,location:o!=null&&o.loc?Am(o==null?void 0:o.loc):void 0,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 ry extends Om{}class Dm extends Om{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,R,U,D,x,B,q,Z,se,at,kt,Kt;const c=e,d=new Mm,l=r.length?new Set(r):void 0,u=[],h=[],f=[],S=new Map,E=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:T}=A,{selected:w}=A,F=A,_e={nominated:T!=null?T:w,currentRoundTripTime:F.currentRoundTripTime,totalRoundTripTime:F.totalRoundTripTime,bytesReceived:F.bytesReceived,bytesSent:F.bytesSent,availableOutgoingBitrate:F.availableOutgoingBitrate,availableIncomingBitrate:F.availableIncomingBitrate,lastPacketReceivedTimestamp:F.lastPacketReceivedTimestamp,lastPacketSentTimestamp:F.lastPacketSentTimestamp,localCandidateId:F.localCandidateId,remoteCandidateId:F.remoteCandidateId,bytesDiscardedOnSend:F.bytesDiscardedOnSend,packetsSent:F.packetsSent,packetsReceived:F.packetsReceived,packetsDiscardedOnSend:F.packetsDiscardedOnSend};f.push(_e),(A.nominated===!0||A.selected===!0)&&(d.candidatePair=_e);break}case"transport":{const T=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:T.bytesReceived,bytesSent:T.bytesSent,packetsSent:T.packetsSent,packetsReceived:T.packetsReceived,dtlsCipher:T.dtlsCipher,dtlsState:T.dtlsState,iceRole:T.iceRole};if(d.transport=w,o){if(o.producing){const F=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,F,w)}if(o.consuming){const F=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,F,w)}}break}case"remote-inbound-rtp":{const T=A,w={jitter:T.jitter,fractionLost:T.fractionLost,roundTripTime:T.roundTripTime,roundTripTimeMeasurements:T.roundTripTimeMeasurements,totalRoundTripTime:T.totalRoundTripTime,packetsLost:T.packetsLost};d.remoteInboundRtp.set(T.localId,w);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(A.id))break;const T=A,w=n||this.outboundProducerMap.get(A.id),F=this.pausedProducerMap.get(w);if(F){if(F.lastReportCalculated===!0)break;this.pausedProducerMap.set(w,{lastReportCalculated:!0})}this.overallProducersStatsMap[w]||(this.overallProducersStatsMap[w]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const _e=this.overallProducersStatsMap[w];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.outboundProducerMap.has(A.id)){d.staleProducerStreamMap=!0;break}const Le=this.callStatsInstance.producers.get(w);if(((k=Le==null?void 0:Le.track)==null?void 0:k.readyState)==="ended")break;d.producerStreamMap.has(w)||d.producerStreamMap.set(w,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const V={bytesSent:T.bytesSent,packetsSent:T.packetsSent,nackCount:T.nackCount,ssrc:T.ssrc,mid:T.mid,active:T.active,codecId:T.codecId,headerBytesSent:T.headerBytesSent||0,totalPacketSendDelay:T.totalPacketSendDelay||0};if(T.mediaType==="video"||T.kind==="video"){const C=T,Be={frameHeight:C.frameHeight,frameWidth:C.frameWidth,framesEncoded:C.framesEncoded,framesDropped:C.framesDropped?C.framesDropped:C.droppedFrames,framesPerSecond:C.framesPerSecond?C.framesPerSecond:C.framerateMean,framesSent:C.framesSent,keyFramesEncoded:C.keyFramesEncoded,firCount:C.firCount,encoderImplementation:C.encoderImplementation,hugeFramesSent:C.hugeFramesSent,pliCount:C.pliCount,qpSum:C.qpSum,qualityLimitationReason:C.qualityLimitationReason,qualityLimitationDurations:C.qualityLimitationDurations,qualityLimitationResolutionChanges:C.qualityLimitationResolutionChanges,totalEncodeTime:C.totalEncodeTime,totalPacketSendDelay:C.totalEncodeTime,retransmittedBytesSent:C.retransmittedBytesSent,retransmittedPacketsSent:C.retransmittedPacketsSent,scalabilityMode:C.scalabilityMode,powerEfficientEncoder:C.powerEfficientEncoder,...V};d.outboundVideoRtp.set(A.id,Be),d.producerStreamMap.get(w).outboundVideoRtpId.push(A.id),this.processOutboundProducerVideoStats(w,_e,Be)}else if(T.mediaType==="audio"||T.kind==="audio"){const C=T,Be={retransmittedBytesSent:C.retransmittedBytesSent,retransmittedPacketsSent:C.retransmittedPacketsSent,...V};d.outboundAudioRtp.set(A.id,Be),d.producerStreamMap.get(w).outboundAudioRtpId.push(A.id),this.processOutboundProducerAudioStats(w,_e,Be)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(A.id))break;const T=A,w=n||this.inboundConsumerMap.get(A.id),F=this.pausedConsumerMap.get(w);if(F){if(F.lastReportCalculated===!0)break;this.pausedConsumerMap.set(w,{lastReportCalculated:!0})}if(T.ssrc===1234)break;this.overallConsumersStatsMap[w]||(this.overallConsumersStatsMap[w]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const _e=this.overallConsumersStatsMap[w];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.inboundConsumerMap.has(A.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(w)||d.consumerStreamMap.set(w,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Le={bytesReceived:T.bytesReceived,packetsReceived:T.packetsReceived,packetsLost:T.packetsLost>=0?T.packetsLost:0,jitter:T.jitter,nackCount:T.nackCount,jitterBufferDelay:T.jitterBufferDelay,jitterBufferEmittedCount:T.jitterBufferEmittedCount,lastPacketReceivedTimestamp:T.lastPacketReceivedTimestamp,ssrc:T.ssrc,mid:T.mid,codecId:T.codecId,headerBytesReceived:T.headerBytesReceived||0,packetsDiscarded:T.packetsDiscarded||0,jitterBufferMinimumDelay:T.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:T.jitterBufferTargetDelay||0};if(T.mediaType==="video"||T.kind==="video"){const V=T,C={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,...Le};C.score=km({frameWidth:C.frameWidth||0,framesDecoded:(C.framesDecoded||0)-(((I=this.videoConsumerToStatsMap.get(w))==null?void 0:I.framesDecoded)||0),framesPerSecond:C.framesPerSecond||0,packetsLost:(C.packetsLost||0)-(((R=this.videoConsumerToStatsMap.get(w))==null?void 0:R.packetsLost)||0),packetsReceived:(C.packetsReceived||0)-(((U=this.videoConsumerToStatsMap.get(w))==null?void 0:U.packetsReceived)||0),jitter:C.jitter||0,isScreenShare:this.screenShareConsumers.has(w)}),E.set(w,{score:+(C.score*10).toFixed(),frameWidth:C.frameWidth||0,frameHeight:C.frameHeight||0,framesPerSecond:C.framesPerSecond||0,packetsLostPercentage:vd({packetsLost:(C.packetsLost||0)-(((D=this.videoConsumerToStatsMap.get(w))==null?void 0:D.packetsLost)||0),packetsReceived:(C.packetsReceived||0)-(((x=this.videoConsumerToStatsMap.get(w))==null?void 0:x.packetsReceived)||0)}),jitter:C.jitter||0,isScreenShare:this.screenShareConsumers.has(w),bitrate:((C.bytesReceived||0)-(((B=this.videoConsumerToStatsMap.get(w))==null?void 0:B.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(w,C),d.inboundVideoRtp.set(A.id,C),d.consumerStreamMap.get(w).inboundVideoRtpId.push(A.id),this.processInboundConsumerVideoStats(w,_e,C)}else if(T.mediaType==="audio"||T.kind==="audio"){const V=T,C={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,...Le};C.score=_m({concealmentEvents:(C.concealmentEvents||0)-(((q=this.audioConsumerToStatsMap.get(w))==null?void 0:q.concealmentEvents)||0),packetsLost:(C.packetsLost||0)-(((Z=this.audioConsumerToStatsMap.get(w))==null?void 0:Z.packetsLost)||0),packetsReceived:(C.packetsReceived||0)-(((se=this.audioConsumerToStatsMap.get(w))==null?void 0:se.packetsReceived)||0),jitter:C.jitter||0}),E.set(w,{score:+(C.score*10).toFixed(),packetsLostPercentage:vd({packetsLost:(C.packetsLost||0)-(((at=this.audioConsumerToStatsMap.get(w))==null?void 0:at.packetsLost)||0),packetsReceived:(C.packetsReceived||0)-(((kt=this.audioConsumerToStatsMap.get(w))==null?void 0:kt.packetsReceived)||0)}),jitter:C.jitter||0,isScreenShare:this.screenShareConsumers.has(w),bitrate:((C.bytesReceived||0)-(((Kt=this.audioConsumerToStatsMap.get(w))==null?void 0:Kt.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(w,C),d.inboundAudioRtp.set(A.id,C),d.consumerStreamMap.get(w).inboundAudioRtpId.push(A.id),this.processInboundConsumerAudioStats(w,_e,C)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}}}if(d.producerStreamMap.forEach((A,T)=>{var w,F,_e,Le,V,C,Be,Gc,Wc,Jc,Kc,zc,Yc,Qc,Xc,Zc,ed,td,sd,rd,id,nd,ad;if(A.outboundVideoRtpId.length>0){const ge=[];A.outboundVideoRtpId.forEach(yp=>{ge.push(d.outboundVideoRtp.get(yp))});const ee=this.getWorkingSimulcastVideoStats(ge);ee.score=wm({frameWidth:ee.frameWidth||0,framesPerSecond:ee.framesPerSecond||0,jitter:((w=ee.remoteData)==null?void 0:w.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsSent:(ee.packetsSent||0)-(((F=this.videoProducerToStatsMap.get(T))==null?void 0:F.packetsSent)||0),packetsLost:(((_e=ee.remoteData)==null?void 0:_e.packetsLost)||0)-(((V=(Le=this.videoProducerToStatsMap.get(T))==null?void 0:Le.remoteData)==null?void 0:V.packetsLost)||0),framesEncoded:(ee.framesEncoded||0)-(((C=this.videoProducerToStatsMap.get(T))==null?void 0:C.framesEncoded)||0)}),S.set(T,{score:+(ee.score*10).toFixed(),frameWidth:ee.frameWidth||0,frameHeight:ee.frameHeight||0,framesPerSecond:ee.framesPerSecond||0,jitter:((Be=ee.remoteData)==null?void 0:Be.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsLostPercentage:Sd({packetsSent:(ee.packetsSent||0)-(((Gc=this.videoProducerToStatsMap.get(T))==null?void 0:Gc.packetsSent)||0),packetsLost:(((Wc=ee.remoteData)==null?void 0:Wc.packetsLost)||0)-(((Kc=(Jc=this.videoProducerToStatsMap.get(T))==null?void 0:Jc.remoteData)==null?void 0:Kc.packetsLost)||0)}),bitrate:((ee.bytesSent||0)-(((zc=this.videoProducerToStatsMap.get(T))==null?void 0:zc.bytesSent)||0))*8/7,cpuLimitations:ee.qualityLimitationReason==="cpu",bandwidthLimitations:ee.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(T,ee)}else if(A.outboundAudioRtpId.length>0){const ge=d.outboundAudioRtp.get(A.outboundAudioRtpId[0]);ge.score=bm({packetsSent:(ge.packetsSent||0)-(((Yc=this.audioProducerToStatsMap.get(T))==null?void 0:Yc.packetsSent)||0),packetsLost:(((Qc=ge.remoteData)==null?void 0:Qc.packetsLost)||0)-(((Zc=(Xc=this.audioProducerToStatsMap.get(T))==null?void 0:Xc.remoteData)==null?void 0:Zc.packetsLost)||0),jitter:((ed=ge.remoteData)==null?void 0:ed.jitter)||0}),S.set(T,{score:+(ge.score*10).toFixed(),bitrate:((ge.bytesSent||0)-(((td=this.audioProducerToStatsMap.get(T))==null?void 0:td.bytesSent)||0))*8/7,packetsLostPercentage:Sd({packetsSent:(ge.packetsSent||0)-(((sd=this.audioProducerToStatsMap.get(T))==null?void 0:sd.packetsSent)||0),packetsLost:(((rd=ge.remoteData)==null?void 0:rd.packetsLost)||0)-(((nd=(id=this.audioProducerToStatsMap.get(T))==null?void 0:id.remoteData)==null?void 0:nd.packetsLost)||0)}),jitter:((ad=ge.remoteData)==null?void 0:ad.jitter)||0,isScreenShare:this.screenShareProducers.has(T)}),this.audioProducerToStatsMap.set(T,ge)}}),f.forEach(A=>{const T=u.find(F=>F.id===A.localCandidateId?(A.localCandidateId=F.id,F):null),w=h.find(F=>F.id===A.remoteCandidateId?(A.remoteCandidateId=F.id,F):null);T&&(A.localCandidateType=T.type,A.localCandidateAddress=Ar(T.address),A.localCandidatePort=T.port,A.localCandidateProtocol=T.protocol,A.localCandidateUrl=T.url,A.localCandidateNetworkType=T.networkType,A.localCandidateRelatedAddress=Ar(T.relatedAddress),A.localCandidateRelatedPort=T.relatedPort),w&&(A.remoteCandidateType=w.type,A.remoteCandidateAddress=Ar(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=f),d.transport&&!d.transport.roundTripTime){let A=0,T=0;d.remoteInboundRtp.forEach((w,F)=>{w.roundTripTime&&w.roundTripTime>A&&(A=w.roundTripTime,T=w.totalRoundTripTime)}),d.transport.roundTripTime=A,d.transport.totalRoundTripTime=T}if(E.size>0)try{this.observer.emit("consumer_score",E)}catch(A){}if(S.size>0)try{this.observer.emit("producer_score",S)}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 f=this.consumerMap.get(i).track.getSettings(),S=e.inboundVideoRtp.get(u);return S.frameHeight||(S.frameHeight=f.height,S.frameWidth=f.width,S.framesPerSecond=f.frameRate),S});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 iy extends Dm{}function bd(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 Nm(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=>{bd(this,t,e,o)}):n}catch(n){bd(this,t,e,n)}return null},s}const z=(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=>{bd(this,s,t,d)}):c}catch(c){bd(this,s,t,c)}return null},i},ny=(s,t)=>(e,r,i)=>{if(i)return Nm(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,Nm(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 j=class extends gt{constructor(e="https://api.testingv3.dyte.in",r="Blink",i=mm.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 qT({logger:o,peerId:c,apiHostnames:d,authToken:l}),this.logger.debug("callStats::engineName: ",{engineName:r}),r){case"Blink":this.measurements=new ry;break;case"Gecko":this.measurements=new Dm;break;case"WebKit":this.measurements=new iy;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 gt,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&&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===Qt.AUDIO&&L.AUDIO_DEVICES_UPDATES||e===Qt.VIDEO&&L.VIDEO_DEVICES_UPDATES||e===Qt.SPEAKER&&L.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:r},timestamp:i})}selectedDevice(e,r,i){this.eventHandler.callEvent({event:e===Qt.AUDIO&&L.SELECTED_MICROHPONE_UPDATE||e===Qt.VIDEO&&L.SELECTED_CAMERA_UPDATE||e===Qt.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===Qt.AUDIO&&L.AUDIO_PLAY_FAILED||e===Qt.VIDEO&&L.VIDEO_PLAY_FAILED,metaData:{deviceType:e},timestamp:r})}mediaTrackMuted(e,r){this.eventHandler.callEvent({event:e===Qt.AUDIO&&L.AUDIO_TRACK_MUTED||e===Qt.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&&(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 l=await this.measurements.getConsumersReport([...this.consumers.values()]);n&&l?n.consumerReport=l:(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([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"registerIceServers",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"registerConsumer",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"registerProducer",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendConsumerSharedMediaStateEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"registerProducingTransport",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"registerConsumingTransport",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"deRegisterConsumer",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"deRegisterProducer",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"disconnectConsumingTransport",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"disconnectProducingTransport",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendPreCallTestBeginEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendScreenShareToggleEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendScreenShareRequestedEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendActiveSpeakerEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"devices",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"selectedDevice",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"mediaPermission",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"mediaPlaybackFailed",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"mediaTrackMuted",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"tabChanged",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"browserBackgrounded",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"browserForegrounded",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"legacySwitch",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"getPreCallTestResults",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendCallJoinBeginEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendNetworkQualityTestBeginEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendWebSocketConnectedEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendTransportConnectedEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendAudioToggleEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendVideoToggleEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendParticipantRoleToggleEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"startPingStats",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"stopPingStats",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendPingStatsEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerRebufferEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerAudioBlockEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerPlaybackBlockedEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerNetworkUnavailableEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerInitializedEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerWorkerErrorEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerErrorEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerRecoverableErrorEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerAnalyticsEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerQualityChanged",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendPlayerLiveLatency",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendDisconnectEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendReconnectEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"expectedVideoResolution",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"expectedScreenshareResolution",null),j=J([ny(TypeError,(s,t)=>K.error(t,s))],j);const ay=j;class Lm extends gt{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,"ipInformation");p(this,"logger")}async initialize({peerId:e,engineName:r,env:i=mm.PROD,iceServers:n,apiBase:o="https://api.cluster.dyte.in",flags:c,logger:d=console,apiHostnames:l,skipConnectivityChecks:u=!1,authToken:h}){var f,S,E;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.ipInformation=await Rm.getIPDetails({peerId:e,apiHostnames:l,logger:d}),this.backend=new ay(o,r,i,c,d,e,l,h),this.iceServers=n,(f=this.backend)==null||f.registerIceServers(this.iceServers),this.initialized=!0,(E=(S=this.backend)==null?void 0:S.eventHandler)==null||E.emit("initialized",this.ipInformation),this.emit("initialized",this.ipInformation),this.startPreCallTest(u)}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;(r=this.backend)==null||r.eventHandler.once("precall_end",e)}),e}onReceivingConsumerAudioStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_audio_status",e)})}onReceivingConsumerVideoStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_video_status",e)})}onReceivingProducerAudioStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_audio_status",e)})}onReceivingProducerVideoStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_video_status",e)})}onReceivingProducingTransportStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producing_transport_status",e)})}onReceivingConsumingTransportStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consuming_transport_status",e)})}onProducerScore(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_score",e)})}onConsumerScore(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_score",e)})}onSafeInitialization(e){if(this.initialized)e(this.ipInformation,!1);else if(!this.stalled){const r=i=>{e(i,!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,f,S,E,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":(f=this.backend)==null||f.sendIVSPlayerRecoverableErrorEvent(r,i);break;case"PlayerAnalyticsEvent":(S=this.backend)==null||S.sendIVSPlayerAnalyticsEvent(r,i);break;case"PlayerPlaybackRateChanged":(E=this.backend)==null||E.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 Lm().setMaxListeners(30);class oy{constructor(){m(this,Oo,void 0)}get telemetry(){var t;return(t=a(this,Oo))==null?void 0:t.getValue("telemetry")}init(t){g(this,Oo,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)}}Oo=new WeakMap;function Vm(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 Ka(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=>Vm(s,r,t,c))}catch(o){Vm(s,r,t,o)}}),i.length>0}class In extends gt.EventEmitter{constructor(e){super();p(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return Ka(this,"*",[e,...r],this.logger),Ka(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 Nt extends gt.EventEmitter{constructor(e){super();p(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return Ka(this,"*",[e,...r],this.logger),Ka(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 cy extends gt.EventEmitter{constructor(e){super();m(this,lr,void 0);m(this,ur,void 0);p(this,"asyncPromiseTimeout");p(this,"logger");this.logger=e,g(this,lr,new Map),g(this,ur,new Map),this.asyncPromiseTimeout=8e3}emit(e,...r){return Ka(this,e,r,this.logger)}async emitAsync(e,...r){a(this,lr).set(e,[]);const i=a(this,ur).get(e).map(()=>new Promise(n=>{a(this,lr).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,lr).delete(e)}onAsync(e,r){const i=a(this,lr),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,ur).get(e)||a(this,ur).set(e,[]),a(this,ur).get(e).push(n),super.on(e,n)}reset(){g(this,lr,new Map),g(this,ur,new Map),super.removeAllListeners()}}lr=new WeakMap,ur=new WeakMap;var dy=typeof global=="object"&&global&&global.Object===Object&&global;const xm=dy;var ly=typeof self=="object"&&self&&self.Object===Object&&self,uy=xm||ly||Function("return this")();const hs=uy;var hy=hs.Symbol;const Rs=hy;var Um=Object.prototype,py=Um.hasOwnProperty,my=Um.toString,za=Rs?Rs.toStringTag:void 0;function gy(s){var t=py.call(s,za),e=s[za];try{s[za]=void 0;var r=!0}catch(n){}var i=my.call(s);return r&&(t?s[za]=e:delete s[za]),i}var fy=Object.prototype,Sy=fy.toString;function vy(s){return Sy.call(s)}var Ty="[object Null]",yy="[object Undefined]",$m=Rs?Rs.toStringTag:void 0;function Ti(s){return s==null?s===void 0?yy:Ty:$m&&$m in Object(s)?gy(s):vy(s)}function Is(s){return s!=null&&typeof s=="object"}var Ey="[object Symbol]";function wd(s){return typeof s=="symbol"||Is(s)&&Ti(s)==Ey}function by(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 wy=Array.isArray;const Lt=wy;var Py=1/0,Bm=Rs?Rs.prototype:void 0,Fm=Bm?Bm.toString:void 0;function Hm(s){if(typeof s=="string")return s;if(Lt(s))return by(s,Hm)+"";if(wd(s))return Fm?Fm.call(s):"";var t=s+"";return t=="0"&&1/s==-Py?"-0":t}var _y=/\s/;function ky(s){for(var t=s.length;t--&&_y.test(s.charAt(t)););return t}var Cy=/^\s+/;function Ry(s){return s&&s.slice(0,ky(s)+1).replace(Cy,"")}function Xt(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var qm=0/0,Iy=/^[-+]0x[0-9a-f]+$/i,Ay=/^0b[01]+$/i,My=/^0o[0-7]+$/i,Oy=parseInt;function jm(s){if(typeof s=="number")return s;if(wd(s))return qm;if(Xt(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=Xt(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=Ry(s);var e=Ay.test(s);return e||My.test(s)?Oy(s.slice(2),e?2:8):Iy.test(s)?qm:+s}function Uu(s){return s}var Dy="[object AsyncFunction]",Ny="[object Function]",Ly="[object GeneratorFunction]",Vy="[object Proxy]";function $u(s){if(!Xt(s))return!1;var t=Ti(s);return t==Ny||t==Ly||t==Dy||t==Vy}var xy=hs["__core-js_shared__"];const Bu=xy;var Gm=function(){var s=/[^.]+$/.exec(Bu&&Bu.keys&&Bu.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function Uy(s){return!!Gm&&Gm in s}var $y=Function.prototype,By=$y.toString;function yi(s){if(s!=null){try{return By.call(s)}catch(t){}try{return s+""}catch(t){}}return""}var Fy=/[\\^$.*+?()[\]{}|]/g,Hy=/^\[object .+?Constructor\]$/,qy=Function.prototype,jy=Object.prototype,Gy=qy.toString,Wy=jy.hasOwnProperty,Jy=RegExp("^"+Gy.call(Wy).replace(Fy,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Ky(s){if(!Xt(s)||Uy(s))return!1;var t=$u(s)?Jy:Hy;return t.test(yi(s))}function zy(s,t){return s==null?void 0:s[t]}function Ei(s,t){var e=zy(s,t);return Ky(e)?e:void 0}var Yy=Ei(hs,"WeakMap");const Fu=Yy;var Wm=Object.create,Qy=function(){function s(){}return function(t){if(!Xt(t))return{};if(Wm)return Wm(t);s.prototype=t;var e=new s;return s.prototype=void 0,e}}();const Xy=Qy;function Zy(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 eE(){}function Jm(s,t){var e=-1,r=s.length;for(t||(t=Array(r));++e<r;)t[e]=s[e];return t}var tE=800,sE=16,rE=Date.now;function iE(s){var t=0,e=0;return function(){var r=rE(),i=sE-(r-e);if(e=r,i>0){if(++t>=tE)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}function nE(s){return function(){return s}}var aE=function(){try{var s=Ei(Object,"defineProperty");return s({},"",{}),s}catch(t){}}();const Pd=aE;var oE=Pd?function(s,t){return Pd(s,"toString",{configurable:!0,enumerable:!1,value:nE(t),writable:!0})}:Uu,cE=iE(oE);const dE=cE;function lE(s,t){for(var e=-1,r=s==null?0:s.length;++e<r&&t(s[e],e,s)!==!1;);return s}function uE(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 hE(s){return s!==s}function pE(s,t,e){for(var r=e-1,i=s.length;++r<i;)if(s[r]===t)return r;return-1}function mE(s,t,e){return t===t?pE(s,t,e):uE(s,hE,e)}function gE(s,t){var e=s==null?0:s.length;return!!e&&mE(s,t,0)>-1}var fE=9007199254740991,SE=/^(?:0|[1-9]\d*)$/;function Hu(s,t){var e=typeof s;return t=t==null?fE:t,!!t&&(e=="number"||e!="symbol"&&SE.test(s))&&s>-1&&s%1==0&&s<t}function qu(s,t,e){t=="__proto__"&&Pd?Pd(s,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):s[t]=e}function Ya(s,t){return s===t||s!==s&&t!==t}var vE=Object.prototype,TE=vE.hasOwnProperty;function Km(s,t,e){var r=s[t];(!(TE.call(s,t)&&Ya(r,e))||e===void 0&&!(t in s))&&qu(s,t,e)}function Qa(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?qu(e,c,d):Km(e,c,d)}return e}var zm=Math.max;function yE(s,t,e){return t=zm(t===void 0?s.length-1:t,0),function(){for(var r=arguments,i=-1,n=zm(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),Zy(s,this,c)}}function EE(s,t){return dE(yE(s,t,Uu),s+"")}var bE=9007199254740991;function ju(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=bE}function Xa(s){return s!=null&&ju(s.length)&&!$u(s)}function wE(s,t,e){if(!Xt(e))return!1;var r=typeof t;return(r=="number"?Xa(e)&&Hu(t,e.length):r=="string"&&t in e)?Ya(e[t],s):!1}function PE(s){return EE(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&&wE(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 _E=Object.prototype;function _d(s){var t=s&&s.constructor,e=typeof t=="function"&&t.prototype||_E;return s===e}function kE(s,t){for(var e=-1,r=Array(s);++e<s;)r[e]=t(e);return r}var CE="[object Arguments]";function Ym(s){return Is(s)&&Ti(s)==CE}var Qm=Object.prototype,RE=Qm.hasOwnProperty,IE=Qm.propertyIsEnumerable,AE=Ym(function(){return arguments}())?Ym:function(s){return Is(s)&&RE.call(s,"callee")&&!IE.call(s,"callee")};const Za=AE;function ME(){return!1}var Xm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Zm=Xm&&typeof module=="object"&&module&&!module.nodeType&&module,OE=Zm&&Zm.exports===Xm,eg=OE?hs.Buffer:void 0,DE=eg?eg.isBuffer:void 0,NE=DE||ME;const An=NE;var LE="[object Arguments]",VE="[object Array]",xE="[object Boolean]",UE="[object Date]",$E="[object Error]",BE="[object Function]",FE="[object Map]",HE="[object Number]",qE="[object Object]",jE="[object RegExp]",GE="[object Set]",WE="[object String]",JE="[object WeakMap]",KE="[object ArrayBuffer]",zE="[object DataView]",YE="[object Float32Array]",QE="[object Float64Array]",XE="[object Int8Array]",ZE="[object Int16Array]",eb="[object Int32Array]",tb="[object Uint8Array]",sb="[object Uint8ClampedArray]",rb="[object Uint16Array]",ib="[object Uint32Array]",Ee={};Ee[YE]=Ee[QE]=Ee[XE]=Ee[ZE]=Ee[eb]=Ee[tb]=Ee[sb]=Ee[rb]=Ee[ib]=!0,Ee[LE]=Ee[VE]=Ee[KE]=Ee[xE]=Ee[zE]=Ee[UE]=Ee[$E]=Ee[BE]=Ee[FE]=Ee[HE]=Ee[qE]=Ee[jE]=Ee[GE]=Ee[WE]=Ee[JE]=!1;function nb(s){return Is(s)&&ju(s.length)&&!!Ee[Ti(s)]}function Gu(s){return function(t){return s(t)}}var tg=typeof exports=="object"&&exports&&!exports.nodeType&&exports,eo=tg&&typeof module=="object"&&module&&!module.nodeType&&module,ab=eo&&eo.exports===tg,Wu=ab&&xm.process,ob=function(){try{var s=eo&&eo.require&&eo.require("util").types;return s||Wu&&Wu.binding&&Wu.binding("util")}catch(t){}}();const Mn=ob;var sg=Mn&&Mn.isTypedArray,cb=sg?Gu(sg):nb;const kd=cb;var db=Object.prototype,lb=db.hasOwnProperty;function rg(s,t){var e=Lt(s),r=!e&&Za(s),i=!e&&!r&&An(s),n=!e&&!r&&!i&&kd(s),o=e||r||i||n,c=o?kE(s.length,String):[],d=c.length;for(var l in s)(t||lb.call(s,l))&&!(o&&(l=="length"||i&&(l=="offset"||l=="parent")||n&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||Hu(l,d)))&&c.push(l);return c}function ig(s,t){return function(e){return s(t(e))}}var ub=ig(Object.keys,Object);const hb=ub;var pb=Object.prototype,mb=pb.hasOwnProperty;function ng(s){if(!_d(s))return hb(s);var t=[];for(var e in Object(s))mb.call(s,e)&&e!="constructor"&&t.push(e);return t}function Cd(s){return Xa(s)?rg(s):ng(s)}function gb(s){var t=[];if(s!=null)for(var e in Object(s))t.push(e);return t}var fb=Object.prototype,Sb=fb.hasOwnProperty;function vb(s){if(!Xt(s))return gb(s);var t=_d(s),e=[];for(var r in s)r=="constructor"&&(t||!Sb.call(s,r))||e.push(r);return e}function to(s){return Xa(s)?rg(s,!0):vb(s)}var Tb=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,yb=/^\w*$/;function Ju(s,t){if(Lt(s))return!1;var e=typeof s;return e=="number"||e=="symbol"||e=="boolean"||s==null||wd(s)?!0:yb.test(s)||!Tb.test(s)||t!=null&&s in Object(t)}var Eb=Ei(Object,"create");const so=Eb;function bb(){this.__data__=so?so(null):{},this.size=0}function wb(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var Pb="__lodash_hash_undefined__",_b=Object.prototype,kb=_b.hasOwnProperty;function Cb(s){var t=this.__data__;if(so){var e=t[s];return e===Pb?void 0:e}return kb.call(t,s)?t[s]:void 0}var Rb=Object.prototype,Ib=Rb.hasOwnProperty;function Ab(s){var t=this.__data__;return so?t[s]!==void 0:Ib.call(t,s)}var Mb="__lodash_hash_undefined__";function Ob(s,t){var e=this.__data__;return this.size+=this.has(s)?0:1,e[s]=so&&t===void 0?Mb:t,this}function bi(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])}}bi.prototype.clear=bb,bi.prototype.delete=wb,bi.prototype.get=Cb,bi.prototype.has=Ab,bi.prototype.set=Ob;function Db(){this.__data__=[],this.size=0}function Rd(s,t){for(var e=s.length;e--;)if(Ya(s[e][0],t))return e;return-1}var Nb=Array.prototype,Lb=Nb.splice;function Vb(s){var t=this.__data__,e=Rd(t,s);if(e<0)return!1;var r=t.length-1;return e==r?t.pop():Lb.call(t,e,1),--this.size,!0}function xb(s){var t=this.__data__,e=Rd(t,s);return e<0?void 0:t[e][1]}function Ub(s){return Rd(this.__data__,s)>-1}function $b(s,t){var e=this.__data__,r=Rd(e,s);return r<0?(++this.size,e.push([s,t])):e[r][1]=t,this}function Ks(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])}}Ks.prototype.clear=Db,Ks.prototype.delete=Vb,Ks.prototype.get=xb,Ks.prototype.has=Ub,Ks.prototype.set=$b;var Bb=Ei(hs,"Map");const ro=Bb;function Fb(){this.size=0,this.__data__={hash:new bi,map:new(ro||Ks),string:new bi}}function Hb(s){var t=typeof s;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?s!=="__proto__":s===null}function Id(s,t){var e=s.__data__;return Hb(t)?e[typeof t=="string"?"string":"hash"]:e.map}function qb(s){var t=Id(this,s).delete(s);return this.size-=t?1:0,t}function jb(s){return Id(this,s).get(s)}function Gb(s){return Id(this,s).has(s)}function Wb(s,t){var e=Id(this,s),r=e.size;return e.set(s,t),this.size+=e.size==r?0:1,this}function zs(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])}}zs.prototype.clear=Fb,zs.prototype.delete=qb,zs.prototype.get=jb,zs.prototype.has=Gb,zs.prototype.set=Wb;var Jb="Expected a function";function Ku(s,t){if(typeof s!="function"||t!=null&&typeof t!="function")throw new TypeError(Jb);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(Ku.Cache||zs),e}Ku.Cache=zs;var Kb=500;function zb(s){var t=Ku(s,function(r){return e.size===Kb&&e.clear(),r}),e=t.cache;return t}var Yb=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Qb=/\\(\\)?/g,Xb=zb(function(s){var t=[];return s.charCodeAt(0)===46&&t.push(""),s.replace(Yb,function(e,r,i,n){t.push(i?n.replace(Qb,"$1"):r||e)}),t});const Zb=Xb;function ew(s){return s==null?"":Hm(s)}function ag(s,t){return Lt(s)?s:Ju(s,t)?[s]:Zb(ew(s))}var tw=1/0;function Ad(s){if(typeof s=="string"||wd(s))return s;var t=s+"";return t=="0"&&1/s==-tw?"-0":t}function og(s,t){t=ag(t,s);for(var e=0,r=t.length;s!=null&&e<r;)s=s[Ad(t[e++])];return e&&e==r?s:void 0}function sw(s,t,e){var r=s==null?void 0:og(s,t);return r===void 0?e:r}function cg(s,t){for(var e=-1,r=t.length,i=s.length;++e<r;)s[i+e]=t[e];return s}var rw=ig(Object.getPrototypeOf,Object);const zu=rw;var iw="[object Object]",nw=Function.prototype,aw=Object.prototype,dg=nw.toString,ow=aw.hasOwnProperty,cw=dg.call(Object);function dw(s){if(!Is(s)||Ti(s)!=iw)return!1;var t=zu(s);if(t===null)return!0;var e=ow.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&dg.call(e)==cw}function lw(){this.__data__=new Ks,this.size=0}function uw(s){var t=this.__data__,e=t.delete(s);return this.size=t.size,e}function hw(s){return this.__data__.get(s)}function pw(s){return this.__data__.has(s)}var mw=200;function gw(s,t){var e=this.__data__;if(e instanceof Ks){var r=e.__data__;if(!ro||r.length<mw-1)return r.push([s,t]),this.size=++e.size,this;e=this.__data__=new zs(r)}return e.set(s,t),this.size=e.size,this}function ps(s){var t=this.__data__=new Ks(s);this.size=t.size}ps.prototype.clear=lw,ps.prototype.delete=uw,ps.prototype.get=hw,ps.prototype.has=pw,ps.prototype.set=gw;function fw(s,t){return s&&Qa(t,Cd(t),s)}function Sw(s,t){return s&&Qa(t,to(t),s)}var lg=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ug=lg&&typeof module=="object"&&module&&!module.nodeType&&module,vw=ug&&ug.exports===lg,hg=vw?hs.Buffer:void 0,pg=hg?hg.allocUnsafe:void 0;function mg(s,t){if(t)return s.slice();var e=s.length,r=pg?pg(e):new s.constructor(e);return s.copy(r),r}function Tw(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 gg(){return[]}var yw=Object.prototype,Ew=yw.propertyIsEnumerable,fg=Object.getOwnPropertySymbols,bw=fg?function(s){return s==null?[]:(s=Object(s),Tw(fg(s),function(t){return Ew.call(s,t)}))}:gg;const Yu=bw;function ww(s,t){return Qa(s,Yu(s),t)}var Pw=Object.getOwnPropertySymbols,_w=Pw?function(s){for(var t=[];s;)cg(t,Yu(s)),s=zu(s);return t}:gg;const Sg=_w;function kw(s,t){return Qa(s,Sg(s),t)}function vg(s,t,e){var r=t(s);return Lt(s)?r:cg(r,e(s))}function Qu(s){return vg(s,Cd,Yu)}function Cw(s){return vg(s,to,Sg)}var Rw=Ei(hs,"DataView");const Xu=Rw;var Iw=Ei(hs,"Promise");const Zu=Iw;var Aw=Ei(hs,"Set");const On=Aw;var Tg="[object Map]",Mw="[object Object]",yg="[object Promise]",Eg="[object Set]",bg="[object WeakMap]",wg="[object DataView]",Ow=yi(Xu),Dw=yi(ro),Nw=yi(Zu),Lw=yi(On),Vw=yi(Fu),wi=Ti;(Xu&&wi(new Xu(new ArrayBuffer(1)))!=wg||ro&&wi(new ro)!=Tg||Zu&&wi(Zu.resolve())!=yg||On&&wi(new On)!=Eg||Fu&&wi(new Fu)!=bg)&&(wi=function(s){var t=Ti(s),e=t==Mw?s.constructor:void 0,r=e?yi(e):"";if(r)switch(r){case Ow:return wg;case Dw:return Tg;case Nw:return yg;case Lw:return Eg;case Vw:return bg}return t});const Dn=wi;var xw=Object.prototype,Uw=xw.hasOwnProperty;function $w(s){var t=s.length,e=new s.constructor(t);return t&&typeof s[0]=="string"&&Uw.call(s,"index")&&(e.index=s.index,e.input=s.input),e}var Bw=hs.Uint8Array;const Md=Bw;function eh(s){var t=new s.constructor(s.byteLength);return new Md(t).set(new Md(s)),t}function Fw(s,t){var e=t?eh(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.byteLength)}var Hw=/\w*$/;function qw(s){var t=new s.constructor(s.source,Hw.exec(s));return t.lastIndex=s.lastIndex,t}var Pg=Rs?Rs.prototype:void 0,_g=Pg?Pg.valueOf:void 0;function jw(s){return _g?Object(_g.call(s)):{}}function kg(s,t){var e=t?eh(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.length)}var Gw="[object Boolean]",Ww="[object Date]",Jw="[object Map]",Kw="[object Number]",zw="[object RegExp]",Yw="[object Set]",Qw="[object String]",Xw="[object Symbol]",Zw="[object ArrayBuffer]",eP="[object DataView]",tP="[object Float32Array]",sP="[object Float64Array]",rP="[object Int8Array]",iP="[object Int16Array]",nP="[object Int32Array]",aP="[object Uint8Array]",oP="[object Uint8ClampedArray]",cP="[object Uint16Array]",dP="[object Uint32Array]";function lP(s,t,e){var r=s.constructor;switch(t){case Zw:return eh(s);case Gw:case Ww:return new r(+s);case eP:return Fw(s,e);case tP:case sP:case rP:case iP:case nP:case aP:case oP:case cP:case dP:return kg(s,e);case Jw:return new r;case Kw:case Qw:return new r(s);case zw:return qw(s);case Yw:return new r;case Xw:return jw(s)}}function Cg(s){return typeof s.constructor=="function"&&!_d(s)?Xy(zu(s)):{}}var uP="[object Map]";function hP(s){return Is(s)&&Dn(s)==uP}var Rg=Mn&&Mn.isMap,pP=Rg?Gu(Rg):hP;const mP=pP;var gP="[object Set]";function fP(s){return Is(s)&&Dn(s)==gP}var Ig=Mn&&Mn.isSet,SP=Ig?Gu(Ig):fP;const vP=SP;var TP=1,yP=2,EP=4,Ag="[object Arguments]",bP="[object Array]",wP="[object Boolean]",PP="[object Date]",_P="[object Error]",Mg="[object Function]",kP="[object GeneratorFunction]",CP="[object Map]",RP="[object Number]",Og="[object Object]",IP="[object RegExp]",AP="[object Set]",MP="[object String]",OP="[object Symbol]",DP="[object WeakMap]",NP="[object ArrayBuffer]",LP="[object DataView]",VP="[object Float32Array]",xP="[object Float64Array]",UP="[object Int8Array]",$P="[object Int16Array]",BP="[object Int32Array]",FP="[object Uint8Array]",HP="[object Uint8ClampedArray]",qP="[object Uint16Array]",jP="[object Uint32Array]",fe={};fe[Ag]=fe[bP]=fe[NP]=fe[LP]=fe[wP]=fe[PP]=fe[VP]=fe[xP]=fe[UP]=fe[$P]=fe[BP]=fe[CP]=fe[RP]=fe[Og]=fe[IP]=fe[AP]=fe[MP]=fe[OP]=fe[FP]=fe[HP]=fe[qP]=fe[jP]=!0,fe[_P]=fe[Mg]=fe[DP]=!1;function io(s,t,e,r,i,n){var o,c=t&TP,d=t&yP,l=t&EP;if(e&&(o=i?e(s,r,i,n):e(s)),o!==void 0)return o;if(!Xt(s))return s;var u=Lt(s);if(u){if(o=$w(s),!c)return Jm(s,o)}else{var h=Dn(s),f=h==Mg||h==kP;if(An(s))return mg(s,c);if(h==Og||h==Ag||f&&!i){if(o=d||f?{}:Cg(s),!c)return d?kw(s,Sw(o,s)):ww(s,fw(o,s))}else{if(!fe[h])return i?s:{};o=lP(s,h,c)}}n||(n=new ps);var S=n.get(s);if(S)return S;n.set(s,o),vP(s)?s.forEach(function(I){o.add(io(I,t,e,I,s,n))}):mP(s)&&s.forEach(function(I,R){o.set(R,io(I,t,e,R,s,n))});var E=l?d?Cw:Qu:d?to:Cd,k=u?void 0:E(s);return lE(k||s,function(I,R){k&&(R=I,I=s[R]),Km(o,R,io(I,t,e,R,s,n))}),o}var GP=4;function WP(s){return io(s,GP)}var JP=1,KP=4;function th(s){return io(s,JP|KP)}var zP="__lodash_hash_undefined__";function YP(s){return this.__data__.set(s,zP),this}function QP(s){return this.__data__.has(s)}function no(s){var t=-1,e=s==null?0:s.length;for(this.__data__=new zs;++t<e;)this.add(s[t])}no.prototype.add=no.prototype.push=YP,no.prototype.has=QP;function XP(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 Dg(s,t){return s.has(t)}var ZP=1,e_=2;function Ng(s,t,e,r,i,n){var o=e&ZP,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,f=!0,S=e&e_?new no:void 0;for(n.set(s,t),n.set(t,s);++h<c;){var E=s[h],k=t[h];if(r)var I=o?r(k,E,h,t,s,n):r(E,k,h,s,t,n);if(I!==void 0){if(I)continue;f=!1;break}if(S){if(!XP(t,function(R,U){if(!Dg(S,U)&&(E===R||i(E,R,e,r,n)))return S.push(U)})){f=!1;break}}else if(!(E===k||i(E,k,e,r,n))){f=!1;break}}return n.delete(s),n.delete(t),f}function t_(s){var t=-1,e=Array(s.size);return s.forEach(function(r,i){e[++t]=[i,r]}),e}function sh(s){var t=-1,e=Array(s.size);return s.forEach(function(r){e[++t]=r}),e}var s_=1,r_=2,i_="[object Boolean]",n_="[object Date]",a_="[object Error]",o_="[object Map]",c_="[object Number]",d_="[object RegExp]",l_="[object Set]",u_="[object String]",h_="[object Symbol]",p_="[object ArrayBuffer]",m_="[object DataView]",Lg=Rs?Rs.prototype:void 0,rh=Lg?Lg.valueOf:void 0;function g_(s,t,e,r,i,n,o){switch(e){case m_:if(s.byteLength!=t.byteLength||s.byteOffset!=t.byteOffset)return!1;s=s.buffer,t=t.buffer;case p_:return!(s.byteLength!=t.byteLength||!n(new Md(s),new Md(t)));case i_:case n_:case c_:return Ya(+s,+t);case a_:return s.name==t.name&&s.message==t.message;case d_:case u_:return s==t+"";case o_:var c=t_;case l_:var d=r&s_;if(c||(c=sh),s.size!=t.size&&!d)return!1;var l=o.get(s);if(l)return l==t;r|=r_,o.set(s,t);var u=Ng(c(s),c(t),r,i,n,o);return o.delete(s),u;case h_:if(rh)return rh.call(s)==rh.call(t)}return!1}var f_=1,S_=Object.prototype,v_=S_.hasOwnProperty;function T_(s,t,e,r,i,n){var o=e&f_,c=Qu(s),d=c.length,l=Qu(t),u=l.length;if(d!=u&&!o)return!1;for(var h=d;h--;){var f=c[h];if(!(o?f in t:v_.call(t,f)))return!1}var S=n.get(s),E=n.get(t);if(S&&E)return S==t&&E==s;var k=!0;n.set(s,t),n.set(t,s);for(var I=o;++h<d;){f=c[h];var R=s[f],U=t[f];if(r)var D=o?r(U,R,f,t,s,n):r(R,U,f,s,t,n);if(!(D===void 0?R===U||i(R,U,e,r,n):D)){k=!1;break}I||(I=f=="constructor")}if(k&&!I){var x=s.constructor,B=t.constructor;x!=B&&"constructor"in s&&"constructor"in t&&!(typeof x=="function"&&x instanceof x&&typeof B=="function"&&B instanceof B)&&(k=!1)}return n.delete(s),n.delete(t),k}var y_=1,Vg="[object Arguments]",xg="[object Array]",Od="[object Object]",E_=Object.prototype,Ug=E_.hasOwnProperty;function b_(s,t,e,r,i,n){var o=Lt(s),c=Lt(t),d=o?xg:Dn(s),l=c?xg:Dn(t);d=d==Vg?Od:d,l=l==Vg?Od:l;var u=d==Od,h=l==Od,f=d==l;if(f&&An(s)){if(!An(t))return!1;o=!0,u=!1}if(f&&!u)return n||(n=new ps),o||kd(s)?Ng(s,t,e,r,i,n):g_(s,t,d,e,r,i,n);if(!(e&y_)){var S=u&&Ug.call(s,"__wrapped__"),E=h&&Ug.call(t,"__wrapped__");if(S||E){var k=S?s.value():s,I=E?t.value():t;return n||(n=new ps),i(k,I,e,r,n)}}return f?(n||(n=new ps),T_(s,t,e,r,i,n)):!1}function Dd(s,t,e,r,i){return s===t?!0:s==null||t==null||!Is(s)&&!Is(t)?s!==s&&t!==t:b_(s,t,e,r,Dd,i)}var w_=1,P_=2;function __(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 ps;if(r)var f=r(l,u,d,s,t,h);if(!(f===void 0?Dd(u,l,w_|P_,r,h):f))return!1}}return!0}function $g(s){return s===s&&!Xt(s)}function k_(s){for(var t=Cd(s),e=t.length;e--;){var r=t[e],i=s[r];t[e]=[r,i,$g(i)]}return t}function Bg(s,t){return function(e){return e==null?!1:e[s]===t&&(t!==void 0||s in Object(e))}}function C_(s){var t=k_(s);return t.length==1&&t[0][2]?Bg(t[0][0],t[0][1]):function(e){return e===s||__(e,s,t)}}function R_(s,t){return s!=null&&t in Object(s)}function I_(s,t,e){t=ag(t,s);for(var r=-1,i=t.length,n=!1;++r<i;){var o=Ad(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&&ju(i)&&Hu(o,i)&&(Lt(s)||Za(s)))}function A_(s,t){return s!=null&&I_(s,t,R_)}var M_=1,O_=2;function D_(s,t){return Ju(s)&&$g(t)?Bg(Ad(s),t):function(e){var r=sw(e,s);return r===void 0&&r===t?A_(e,s):Dd(t,r,M_|O_)}}function N_(s){return function(t){return t==null?void 0:t[s]}}function L_(s){return function(t){return og(t,s)}}function V_(s){return Ju(s)?N_(Ad(s)):L_(s)}function x_(s){return typeof s=="function"?s:s==null?Uu:typeof s=="object"?Lt(s)?D_(s[0],s[1]):C_(s):V_(s)}function U_(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 $_=U_();const B_=$_;var F_=function(){return hs.Date.now()};const ih=F_;var H_="Expected a function",q_=Math.max,j_=Math.min;function nh(s,t,e){var r,i,n,o,c,d,l=0,u=!1,h=!1,f=!0;if(typeof s!="function")throw new TypeError(H_);t=jm(t)||0,Xt(e)&&(u=!!e.leading,h="maxWait"in e,n=h?q_(jm(e.maxWait)||0,t):n,f="trailing"in e?!!e.trailing:f);function S(q){var Z=r,se=i;return r=i=void 0,l=q,o=s.apply(se,Z),o}function E(q){return l=q,c=setTimeout(R,t),u?S(q):o}function k(q){var Z=q-d,se=q-l,at=t-Z;return h?j_(at,n-se):at}function I(q){var Z=q-d,se=q-l;return d===void 0||Z>=t||Z<0||h&&se>=n}function R(){var q=ih();if(I(q))return U(q);c=setTimeout(R,k(q))}function U(q){return c=void 0,f&&r?S(q):(r=i=void 0,o)}function D(){c!==void 0&&clearTimeout(c),l=0,r=d=i=c=void 0}function x(){return c===void 0?o:U(ih())}function B(){var q=ih(),Z=I(q);if(r=arguments,i=this,d=q,Z){if(c===void 0)return E(d);if(h)return clearTimeout(c),c=setTimeout(R,t),S(d)}return c===void 0&&(c=setTimeout(R,t)),o}return B.cancel=D,B.flush=x,B}function ah(s,t,e){(e!==void 0&&!Ya(s[t],e)||e===void 0&&!(t in s))&&qu(s,t,e)}function G_(s){return Is(s)&&Xa(s)}function oh(s,t){if(!(t==="constructor"&&typeof s[t]=="function")&&t!="__proto__")return s[t]}function W_(s){return Qa(s,to(s))}function J_(s,t,e,r,i,n,o){var c=oh(s,e),d=oh(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 f=Lt(d),S=!f&&An(d),E=!f&&!S&&kd(d);u=d,f||S||E?Lt(c)?u=c:G_(c)?u=Jm(c):S?(h=!1,u=mg(d,!0)):E?(h=!1,u=kg(d,!0)):u=[]:dw(d)||Za(d)?(u=c,Za(c)?u=W_(c):(!Xt(c)||$u(c))&&(u=Cg(d))):h=!1}h&&(o.set(d,u),i(u,d,r,n,o),o.delete(d)),ah(s,e,u)}function Fg(s,t,e,r,i){s!==t&&B_(t,function(n,o){if(i||(i=new ps),Xt(n))J_(s,t,o,e,Fg,r,i);else{var c=r?r(oh(s,o),n,o+"",s,t,i):void 0;c===void 0&&(c=n),ah(s,o,c)}},to)}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 z_="[object Map]",Y_="[object Set]",Q_=Object.prototype,X_=Q_.hasOwnProperty;function Z_(s){if(s==null)return!0;if(Xa(s)&&(Lt(s)||typeof s=="string"||typeof s.splice=="function"||An(s)||kd(s)||Za(s)))return!s.length;var t=Dn(s);if(t==z_||t==Y_)return!s.size;if(_d(s))return!ng(s).length;for(var e in s)if(X_.call(s,e))return!1;return!0}function ek(s,t){return Dd(s,t)}var tk=PE(function(s,t,e){Fg(s,t,e)});const Mr=tk;var sk=1/0,rk=On&&1/sh(new On([,-0]))[1]==sk?function(s){return new On(s)}:eE;const ik=rk;var nk=200;function Hg(s,t,e){var r=-1,i=gE,n=s.length,o=!0,c=[],d=c;if(e)o=!1,i=K_;else if(n>=nk){var l=t?null:ik(s);if(l)return sh(l);o=!1,i=Dg,d=new no}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 f=d.length;f--;)if(d[f]===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 ak(s){return s&&s.length?Hg(s):[]}function ok(s,t){return s&&s.length?Hg(s,x_(t)):[]}function Nd(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 ck={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},qg={STAGING:"staging",PROD:"prod"},dk={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 ao(s,t){const e=s.getValue("overrides");return e&&e[t]?e[t]:!1}function lk({baseURI:s}){return s.includes("staging.realtime")?qg.STAGING:qg.PROD}function Ld({servicePrefix:s,baseURI:t}){return`${s}.${t}`}function ch({servicePrefix:s,baseURI:t}){const e=s==="ws"?"wss":"https",r=Ld({servicePrefix:"api",baseURI:t});return`${e}://${r}/${s}`}function uk(s){const t=s.getValue("baseURI");return{location:Ld({servicePrefix:"location",baseURI:t}),locationLegacy:Ld({servicePrefix:"location-legacy",baseURI:t}),daCollector:ch({servicePrefix:"telemetry",baseURI:t}).replace("https://","")}}const hk='<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>',pk='<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>',Vd=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})},Pi={logs:"https://api.realtime.cloudflare.com/logs/otel/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"}},mk=/\b(?:1[7-9](?:\.\d+)?|[2-9]\d(?:\.\d+)?|[1-9]\d{2,}(?:\.\d+)?)\b/,dh="__rtk_plugins__",gk=[dh];function jg(s){var r,i,n;const t=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((r=window.location.host)==null?void 0:r.includes(Pi.baseURI.staging)),e=!!((n=(i=s==null?void 0:s.getValue("modules"))==null?void 0:i.devTools)!=null&&n.logs);return t||e}function fk(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 Gg(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"?Gg(s[r],i,e):["number","string","boolean"].includes(typeof s[r])&&(e[i]=s[r])}),e}function Wg(s,t,e={},r=""){const i={};try{const n=JSON.stringify(e),o=JSON.parse(n),c=Gg(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 d=n&&!!i;r&&r.endsWith("00")&&i&&(d=!0),d&&i.error("ClientError",{error:{message:this.message,name:this.name,code:r}});const l=Or.getContext(Or.getMostRecentPeerId());if(l){const u=l.getValue("onError");try{u(this)}catch(h){}}typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("ClientError",{detail:this}))}catch(d){}}}function Ud(s,t,e,r){if(r instanceof P)throw r;if(r instanceof t){const i=new P(r.message,e);throw i.stack=r.stack,i}else throw r}function Jg(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){Ud(this,t,e,o)}}),n&&(s.set=function(o){try{return n.apply(this,[o])}catch(c){Ud(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=>{Ud(this,t,e,o)}):n}catch(n){Ud(this,t,e,n)}},s}function yk(s,t){return(e,r,i)=>{if(i)return Jg(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,Jg(o,s,t))}}}const ct=s=>yk(Error,s);var Ys=(s=>(s.GroupCall="GROUP_CALL",s.Webinar="WEBINAR",s.AudioRoom="AUDIO_ROOM",s.Livestream="LIVESTREAM",s.Chat="CHAT",s))(Ys||{}),G=(s=>(s.Allowed="ALLOWED",s.NotAllowed="NOT_ALLOWED",s.CanRequest="CAN_REQUEST",s))(G||{});typeof process!="undefined"&&(lv=process==null?void 0:process.env)!=null&&lv.FLAGSMITH_ENVIRONMENT_KEY&&process.env.FLAGSMITH_ENVIRONMENT_KEY;var Kg=[-2,-1,0,1,2],Ek=[0,1,2,3,4];function bk(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 wk=(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)]},Pk=(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]},_k=(s,t,e)=>{const r=i=>i.toString(16).padStart(2,"0");return`#${r(s)}${r(t)}${r(e)}`},zg=(s,t=Kg,e=.4)=>{const r=[],[i,n,o]=bk(s),[c,d,l]=Pk(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 f=5-h,S=h+1,E=(100-u)/f,k=u/S;for(const I of t){let R;I<0?R=u+I*k*e:I>0?R=u+I*E*e:R=u;const[U,D,x]=wk(c,d,R/100);r.push(_k(U,D,x))}return r},Yg={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"}},kk=s=>{const[t,e,r,i,n]=zg(s,Kg);return{300:t,400:e,500:r,600:i,700:n}},Ck=s=>{if(s==="#FFFFFF")return Yg.light.background;if(s==="#000000")return Yg.dark.background;const[t,e,r,i,n]=zg(s,Ek);return{1e3:t,900:e,800:r,700:i,600:n}},Rk={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:kk("#2160FD"),background:Ck("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function Qg(){return th(Rk)}var Ik={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:Qg(),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 Ak(){return th(Ik)}var Mk={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:Qg(),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 th(Mk)}function Ok(){ye.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 _=(s=>(s.NEW_PRODUCER="NEW_PRODUCER",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.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))(_||{});function Dk(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 Xg=1080,Zg=1920,Nk=(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,f=l*u,S,E,k,I,R=1;return h<e&&(R=e/h),Math.abs(R-1)<1e-14&&f<r&&(R=r/f),h*=R,f*=R,k=d/(h/e),I=l/(f/r),S=(d-k)*o,E=(l-I)*c,S<0&&(S=0),E<0&&(E=0),k>d&&(k=d),I>l&&(I=l),[S,E,k,I,s,t,e,r]},vp=class extends Nt{constructor(e,r,i,n){const o=e.getValue("logger");super(o);m(this,ss,void 0);m(this,Vi,void 0);m(this,lt,void 0);m(this,rs,void 0);m(this,Oe,{height:Xg,width:Zg});m(this,Ts,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"});m(this,hr,void 0);m(this,St,{});m(this,xe,void 0);m(this,Wn,void 0);m(this,Jn,void 0);m(this,pr,void 0);m(this,Kn,!1);p(this,"cleanupEventListeners",()=>{a(this,Vi).unsubscribe("stageStatus",this.handlePipMediaControls),a(this,xe).removeListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,xe).removeListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,xe).removeListener("roomLeft",()=>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,xe).videoEnabled?a(this,xe).disableVideo():a(this,xe).enableVideo(),this.emit("cameraToggled")),e==="MIC"&&(a(this,xe).audioEnabled?a(this,xe).disableAudio():a(this,xe).enableAudio(),this.emit("micToggled")),e==="END"&&(a(this,Vi).getValue("peerSessionStore").emit(_.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,pr)==="active"){this.disable(!0);return}a(this,St)!==void 0&&this.paintCanvas(),a(this,hr)!==void 0&&g(this,hr,requestAnimationFrame(()=>this.animate()))});p(this,"disable",(e=!1)=>{g(this,pr,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(a(this,hr)),e!==!0&&document.body.removeChild(a(this,lt)),g(this,hr,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()});g(this,Vi,e),g(this,pr,"idle"),g(this,xe,r),g(this,Ts,{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){let i,n;try{i=await Vd(hk),n=await Vd(pk)}catch(o){}return new vp(e,r,i,n)}async setupIcon(e,r){switch(e){case"handRaise":g(this,Jn,r);break;case"pin":g(this,Wn,r);break}}async overrideIcon(e,r){switch(e){case"handRaise":g(this,Jn,await Vd(r));break;case"pin":g(this,Wn,await Vd(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(){g(this,lt,document.createElement("div")),a(this,lt).style.width="0.1px",a(this,lt).style.height="0.1px",a(this,lt).style.overflow="hidden",a(this,lt).style.position="absolute",a(this,lt).style.bottom="0",a(this,lt).style.right="0",a(this,lt).style.opacity="0",a(this,lt).appendChild(a(this,rs))}setupEventListeners(){a(this,Vi).subscribe("stageStatus",this.handlePipMediaControls),a(this,xe).addListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,xe).addListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,xe).addListener("roomLeft",()=>this.disable())}createCanvas(){const e=document.createElement("canvas");e.height=a(this,Oe).height,e.width=a(this,Oe).width,g(this,ss,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,xe).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||a(this,xe).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const r=Object.values(a(this,St)).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,ss)===void 0)return;const o=a(this,ss).getContext("2d"),c=a(this,ss).width,d=0,l=0,u=r-d*2,h=i-d*2,f=Math.floor(c/u),S=Math.floor(e/f),k=e%f*(u+d)+d,I=S*(h+d)+d,{displayText:R,image:U}=n!=null?n:{};o.fillStyle=R||U?a(this,Ts).videoBackground:a(this,Ts).background,o.strokeStyle=a(this,Ts).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 D=u/6,x=u/2+k,B=h/2+I;o.save(),(R||U)&&(o.beginPath(),o.arc(x,B,D,0,Math.PI*2),o.fillStyle=a(this,Ts).brand,o.fill(),U?(o.clip(),o.drawImage(U,x-D,B-D,D*2,D*2),o.restore()):R&&(o.fillStyle=a(this,Ts).textOnBrand,o.font=`${D/2}px sans-serif`,o.textAlign="center",o.textBaseline="middle",o.fillText(R,x,B)),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=f=>{const S=a(this,ss).getContext("2d");S.save(),S.fillStyle=a(this,Ts).background,S.beginPath(),S.moveTo(l+d,u),S.arcTo(l+o,u,l+o,u+d,d),S.arcTo(l+o,u+o,l+o-d,u+o,d),S.arcTo(l,u+o,l,u+o-d,d),S.arcTo(l,u,l+d,u,d),S.closePath(),S.fill(),typeof f=="string"?(S.font=`${o/1.5}px sans-serif`,S.fillStyle=a(this,Ts).text,S.textAlign="center",S.textBaseline="top",S.fillText(f,o/2+l,u+c)):S.drawImage(f,l+c,u+c,o-c*2,o-c*2),l+=o+c,S.restore()};e.pinned&&h(a(this,Wn)),e.handRaised&&h(a(this,Jn)),e.reaction&&h(e.reaction)}drawTile(e,r,i){var l,u;if(a(this,ss)===void 0)return;const n=a(this,ss).getContext("2d"),o=this.getSources();let c=0,d=0;for(;c<a(this,Oe).height-5;){let h=0;for(;h<a(this,Oe).width-5&&d<i;){if((l=o[d])!=null&&l.enabled){const f=o[d].element,[S,E,k,I,R,U,D,x]=Nk(h,c,e,r,f.videoWidth,f.videoHeight);((u=f==null?void 0:f.classList)==null?void 0:u.contains("mirror"))?(n.save(),n.scale(-1,1),n.drawImage(f,S,E,k,I,-1*R,U,-1*D,x),n.restore()):n.drawImage(f,S,E,k,I,R,U,D,x),this.drawIcons(o[d],R,U,Math.max(D,x))}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,Oe).width,a(this,Oe).height];case 2:return[Math.floor(a(this,Oe).width/2),a(this,Oe).height];case 3:case 4:return[Math.floor(a(this,Oe).width/2),Math.floor(a(this,Oe).height/2)];case 5:case 6:return[Math.floor(a(this,Oe).width/3),Math.floor(a(this,Oe).height/2)];case 7:case 8:case 9:return[Math.floor(a(this,Oe).width/3),Math.floor(a(this,Oe).height/3)];default:return[Math.floor(a(this,Oe).width/3),Math.floor(a(this,Oe).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,xe).config)==null?void 0:e.viewType)!=="LIVESTREAM"}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(g(this,Kn,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),a(this,lt))try{document.body.removeChild(a(this,lt))}catch(e){}this.removeAllSources(),g(this,ss,void 0),g(this,rs,void 0),g(this,hr,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,Kn))return;g(this,Kn,!0),this.createCanvas(),this.setupMediaSessionEvents();const i=document.createElement("video");g(this,Oe,{height:e!=null?e:Xg,width:r!=null?r:Zg}),i.height=a(this,Oe).height,i.width=a(this,Oe).width,i.autoplay=!0,i.muted=!0,i.srcObject=a(this,ss).captureStream(24),g(this,rs,i),a(this,rs).onloadedmetadata=()=>{try{this.emit("pipStarted"),a(this,rs).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,St)[e]!==void 0&&(a(this,St)[e].enabled=!0)}disableSource(e){a(this,St)[e]!==void 0&&(a(this,St)[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,St)[e]={id:e,element:r,enabled:i,pinned:n,displayText:o?Dk(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,St)[e];i&&(a(this,St)[e]={...i,...r})}removeSource(e){delete a(this,St)[e]}removePinnedSource(){Object.values(a(this,St)).forEach(r=>{r.pinned&&this.removeSource(r.id)})}removeAllSources(){g(this,St,{})}enable(){g(this,pr,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",a(this,xe).videoEnabled),this.updateMediaSession("MIC",a(this,xe).audioEnabled),document.body.appendChild(a(this,lt)),g(this,hr,requestAnimationFrame(()=>this.animate())),a(this,rs).onloadedmetadata=()=>{a(this,rs).requestPictureInPicture().then(()=>{g(this,pr,"active")})},a(this,rs).readyState===4&&a(this,rs).requestPictureInPicture().then(()=>{g(this,pr,"active")})}};let uh=vp;ss=new WeakMap,Vi=new WeakMap,lt=new WeakMap,rs=new WeakMap,Oe=new WeakMap,Ts=new WeakMap,hr=new WeakMap,St=new WeakMap,xe=new WeakMap,Wn=new WeakMap,Jn=new WeakMap,pr=new WeakMap,Kn=new WeakMap;function hh(s){let t=typeof s;if(t=="object"){if(Array.isArray(s))return"array";if(s===null)return"null"}return t}function Lk(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}let Qs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),$d=[];for(let s=0;s<Qs.length;s++)$d[Qs[s].charCodeAt(0)]=s;$d["-".charCodeAt(0)]=Qs.indexOf("+"),$d["_".charCodeAt(0)]=Qs.indexOf("/");function Vk(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=$d[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 xk(s){let t="",e=0,r,i=0;for(let n=0;n<s.length;n++)switch(r=s[n],e){case 0:t+=Qs[r>>2],i=(r&3)<<4,e=1;break;case 1:t+=Qs[i|r>>4],i=(r&15)<<2,e=2;break;case 2:t+=Qs[i|r>>6],t+=Qs[r&63],e=0;break}return e&&(t+=Qs[i],t+="=",e==1&&(t+="=")),t}var Bd;(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])})(Bd||(Bd={}));var Ve;(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"})(Ve||(Ve={}));function Uk(){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 ph(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 Fd=(1<<16)*(1<<16);function ef(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>=Fd&&(i=i+(r/Fd|0),r=r%Fd)}return n(-24,-18),n(-18,-12),n(-12,-6),n(-6),[t,r,i]}function mh(s,t){if(t>>>0<=2097151)return""+(Fd*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 f=u?String(u):"";return h?"0000000".slice(f.length)+f:f}return l(c,0)+l(o,c)+l(n,1)}function tf(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 $k(){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 me;function Bk(){const s=new DataView(new ArrayBuffer(8));me=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}Bk();function sf(s){if(!s)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const rf=/^-?[0-9]+$/,Hd=4294967296,qd=2147483648;class nf{constructor(t,e){this.lo=t|0,this.hi=e|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let t=this.hi*Hd+(this.lo>>>0);if(!Number.isSafeInteger(t))throw new Error("cannot convert to safe number");return t}}class dt extends nf{static from(t){if(me)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=me.C(t);case"number":if(t===0)return this.ZERO;t=me.C(t);case"bigint":if(!t)return this.ZERO;if(t<me.UMIN)throw new Error("signed value for ulong");if(t>me.UMAX)throw new Error("ulong too large");return me.V.setBigUint64(0,t,!0),new dt(me.V.getInt32(0,!0),me.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!rf.test(t))throw new Error("string is no integer");let[e,r,i]=ef(t);if(e)throw new Error("signed value for ulong");return new dt(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 dt(t,t/Hd)}throw new Error("unknown value "+typeof t)}toString(){return me?this.toBigInt().toString():mh(this.lo,this.hi)}toBigInt(){return sf(me),me.V.setInt32(0,this.lo,!0),me.V.setInt32(4,this.hi,!0),me.V.getBigUint64(0,!0)}}dt.ZERO=new dt(0,0);class Se extends nf{static from(t){if(me)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=me.C(t);case"number":if(t===0)return this.ZERO;t=me.C(t);case"bigint":if(!t)return this.ZERO;if(t<me.MIN)throw new Error("signed long too small");if(t>me.MAX)throw new Error("signed long too large");return me.V.setBigInt64(0,t,!0),new Se(me.V.getInt32(0,!0),me.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!rf.test(t))throw new Error("string is no integer");let[e,r,i]=ef(t);if(e){if(i>qd||i==qd&&r!=0)throw new Error("signed long too small")}else if(i>=qd)throw new Error("signed long too large");let n=new Se(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 Se(t,t/Hd):new Se(-t,-t/Hd).negate()}throw new Error("unknown value "+typeof t)}isNegative(){return(this.hi&qd)!==0}negate(){let t=~this.hi,e=this.lo;return e?e=~e+1:t+=1,new Se(e,t)}toString(){if(me)return this.toBigInt().toString();if(this.isNegative()){let t=this.negate();return"-"+mh(t.lo,t.hi)}return mh(this.lo,this.hi)}toBigInt(){return sf(me),me.V.setInt32(0,this.lo,!0),me.V.setInt32(4,this.hi,!0),me.V.getBigInt64(0,!0)}}Se.ZERO=new Se(0,0);const af={readUnknownField:!0,readerFactory:s=>new Hk(s)};function Fk(s){return s?Object.assign(Object.assign({},af),s):af}class Hk{constructor(t,e){this.varint64=Uk,this.uint32=$k,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 Ve.Varint:for(;this.buf[this.pos++]&128;);break;case Ve.Bit64:this.pos+=4;case Ve.Bit32:this.pos+=4;break;case Ve.LengthDelimited:let r=this.uint32();this.pos+=r;break;case Ve.StartGroup:let i;for(;(i=this.tag()[1])!==Ve.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 Se(...this.varint64())}uint64(){return new dt(...this.varint64())}sint64(){let[t,e]=this.varint64(),r=-(t&1);return t=(t>>>1|(e&1)<<31)^r,e=e>>>1^r,new Se(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 dt(this.sfixed32(),this.sfixed32())}sfixed64(){return new Se(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 ie(s,t){if(!s)throw new Error(t)}const qk=34028234663852886e22,jk=-34028234663852886e22,Gk=4294967295,Wk=2147483647,Jk=-2147483648;function oo(s){if(typeof s!="number")throw new Error("invalid int 32: "+typeof s);if(!Number.isInteger(s)||s>Wk||s<Jk)throw new Error("invalid int 32: "+s)}function jd(s){if(typeof s!="number")throw new Error("invalid uint 32: "+typeof s);if(!Number.isInteger(s)||s>Gk||s<0)throw new Error("invalid uint 32: "+s)}function gh(s){if(typeof s!="number")throw new Error("invalid float 32: "+typeof s);if(Number.isFinite(s)&&(s>qk||s<jk))throw new Error("invalid float 32: "+s)}const of={writeUnknownFields:!0,writerFactory:()=>new zk};function Kk(s){return s?Object.assign(Object.assign({},of),s):of}class zk{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(jd(t);t>127;)this.buf.push(t&127|128),t=t>>>7;return this.buf.push(t),this}int32(t){return oo(t),tf(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){gh(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){jd(t);let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),this.raw(e)}sfixed32(t){oo(t);let e=new Uint8Array(4);return new DataView(e.buffer).setInt32(0,t,!0),this.raw(e)}sint32(t){return oo(t),t=(t<<1^t>>31)>>>0,tf(t,this.buf),this}sfixed64(t){let e=new Uint8Array(8),r=new DataView(e.buffer),i=Se.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=dt.from(t);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(e)}int64(t){let e=Se.from(t);return ph(e.lo,e.hi,this.buf),this}sint64(t){let e=Se.from(t),r=e.hi>>31,i=e.lo<<1^r,n=(e.hi<<1|e.lo>>>31)^r;return ph(i,n,this.buf),this}uint64(t){let e=dt.from(t);return ph(e.lo,e.hi,this.buf),this}}const cf={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},df={ignoreUnknownFields:!1};function Yk(s){return s?Object.assign(Object.assign({},df),s):df}function Qk(s){return s?Object.assign(Object.assign({},cf),s):cf}const lf=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 As;(function(s){s[s.BIGINT=0]="BIGINT",s[s.STRING=1]="STRING",s[s.NUMBER=2]="NUMBER"})(As||(As={}));var Gd;(function(s){s[s.NO=0]="NO",s[s.PACKED=1]="PACKED",s[s.UNPACKED=2]="UNPACKED"})(Gd||(Gd={}));function Xk(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:Gd.NO,s.opt=(i=s.opt)!==null&&i!==void 0?i:s.repeat||s.oneof?!1:s.kind=="message",s}function Zk(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 eC{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(!Zk(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 As.BIGINT:return i=="bigint";case As.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,As.STRING)}}}function ms(s,t){switch(t){case As.BIGINT:return s.toBigInt();case As.NUMBER:return s.toNumber();default:return s.toString()}}class tC{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=hh(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(Lk(o),c.name,o);const u=l[d];for(const[h,f]of Object.entries(o)){this.assert(f!==null,c.name+" map value",null);let S;switch(c.V.kind){case"message":S=c.V.T().internalJsonRead(f,r);break;case"enum":if(S=this.enum(c.V.T(),f,c.name,r.ignoreUnknownFields),S===!1)continue;break;case"scalar":S=this.scalar(f,c.V.T,c.V.L,c.name);break}this.assert(S!==void 0,c.name+" map value",f);let E=h;c.K==O.BOOL&&(E=E=="true"?!0:E=="false"?!1:E),E=this.scalar(E,c.K,As.STRING,c.name).toString(),u[E]=S}}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 f;switch(c.kind){case"message":f=c.T().internalJsonRead(h,r);break;case"enum":if(f=this.enum(c.T(),h,c.name,r.ignoreUnknownFields),f===!1)continue;break;case"scalar":f=this.scalar(h,c.T,c.L,c.name);break}this.assert(f!==void 0,c.name,o),u.push(f)}}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"&&ie(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 ie(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:(ie(typeof o=="number",`Unable to parse field ${this.info.typeName}#${r}, enum ${t[0]} has no value for "${e}".`),o)}ie(!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&&gh(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?jd(c):oo(c),c;case O.INT64:case O.SFIXED64:case O.SINT64:if(t===null)return ms(Se.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return ms(Se.from(t),r);case O.FIXED64:case O.UINT64:if(t===null)return ms(dt.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return ms(dt.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 Vk(t)}}catch(o){n=o.message}this.assert(!1,i+(n?" - "+n:""),t)}}class sC{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);ie(d!==void 0),r[e.useProtoFieldName?n.name:n.jsonName]=d}return r}field(t,e,r){let i;if(t.kind=="map"){ie(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);ie(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);ie(u!==void 0),n[d.toString()]=u}break;case"enum":const c=t.V.T();for(const[d,l]of Object.entries(e)){ie(l===void 0||typeof l=="number");const u=this.enum(c,l,t.name,!1,!0,r.enumAsInteger);ie(u!==void 0),n[d.toString()]=u}break}(r.emitDefaultValues||Object.keys(n).length>0)&&(i=n)}else if(t.repeat){ie(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);ie(l!==void 0),n.push(l)}break;case"enum":const o=t.T();for(let d=0;d<e.length;d++){ie(e[d]===void 0||typeof e[d]=="number");const l=this.enum(o,e[d],t.name,t.opt,!0,r.enumAsInteger);ie(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);ie(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){ie(i);return}if(!(e===0&&!n&&!i))return ie(typeof e=="number"),ie(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){ie(i);return}const o=n||i;switch(t){case O.INT32:case O.SFIXED32:case O.SINT32:return e===0?o?0:void 0:(oo(e),e);case O.FIXED32:case O.UINT32:return e===0?o?0:void 0:(jd(e),e);case O.FLOAT:gh(e);case O.DOUBLE:return e===0?o?0:void 0:(ie(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:(ie(typeof e=="string"),e);case O.BOOL:return e===!1?o?!1:void 0:(ie(typeof e=="boolean"),e);case O.UINT64:case O.FIXED64:ie(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let c=dt.from(e);return c.isZero()&&!o?void 0:c.toString();case O.INT64:case O.SFIXED64:case O.SINT64:ie(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let d=Se.from(e);return d.isZero()&&!o?void 0:d.toString();case O.BYTES:return ie(e instanceof Uint8Array),e.byteLength?xk(e):o?"":void 0}}}function fh(s,t=As.STRING){switch(s){case O.BOOL:return!1;case O.UINT64:case O.FIXED64:return ms(dt.ZERO,t);case O.INT64:case O.SFIXED64:case O.SINT64:return ms(Se.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 rC{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 f=r.readUnknownField;if(f=="throw")throw new Error(`Unknown field ${o} (wire type ${c}) for ${this.info.typeName}`);let S=t.skip(c);f!==!1&&(f===!0?Bd.onRead:f)(this.info.typeName,e,o,c,S);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 f=d.kind=="enum"?O.INT32:d.T,S=d.kind=="scalar"?d.L:void 0;if(u){let I=l[h];if(c==Ve.LengthDelimited&&f!=O.STRING&&f!=O.BYTES){let R=t.uint32()+t.pos;for(;t.pos<R;)I.push(this.scalar(t,f,S))}else I.push(this.scalar(t,f,S))}else l[h]=this.scalar(t,f,S);break;case"message":if(u){let I=l[h],R=d.T().internalBinaryRead(t,t.uint32(),r);I.push(R)}else l[h]=d.T().internalBinaryRead(t,t.uint32(),r,l[h]);break;case"map":let[E,k]=this.mapEntry(d,t,r);l[h][E]=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,As.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 ms(t.int64(),r);case O.UINT64:return ms(t.uint64(),r);case O.FIXED64:return ms(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 ms(t.sfixed64(),r);case O.SINT32:return t.sint32();case O.SINT64:return ms(t.sint64(),r)}}}class iC{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(ie(Array.isArray(o)),d==Gd.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?ie(n.opt):this.scalar(e,u,n.no,o,c||n.opt);break;case"message":if(d){ie(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":ie(typeof o=="object"&&o!==null);for(const[h,f]of Object.entries(o))this.mapEntry(e,r,n,h,f);break}}let i=r.writeUnknownFields;i!==!1&&(i===!0?Bd.onWrite:i)(this.info.typeName,t,e)}mapEntry(t,e,r,i,n){t.tag(r.no,Ve.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:ie(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,Ve.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;ie(e!==O.BYTES&&e!==O.STRING),t.tag(r,Ve.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=Ve.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=Ve.LengthDelimited,i="string";break;case O.BOOL:o=e===!1,i="bool";break;case O.UINT32:i="uint32";break;case O.DOUBLE:r=Ve.Bit64,i="double";break;case O.FLOAT:r=Ve.Bit32,i="float";break;case O.INT64:o=n||Se.from(e).isZero(),i="int64";break;case O.UINT64:o=n||dt.from(e).isZero(),i="uint64";break;case O.FIXED64:o=n||dt.from(e).isZero(),r=Ve.Bit64,i="fixed64";break;case O.BYTES:o=n||!e.byteLength,r=Ve.LengthDelimited,i="bytes";break;case O.FIXED32:r=Ve.Bit32,i="fixed32";break;case O.SFIXED32:r=Ve.Bit32,i="sfixed32";break;case O.SFIXED64:o=n||Se.from(e).isZero(),r=Ve.Bit64,i="sfixed64";break;case O.SINT32:i="sint32";break;case O.SINT64:o=n||Se.from(e).isZero(),i="sint64";break}return[r,i,n||o]}}function nC(s){const t=s.messagePrototype?Object.create(s.messagePrototype):Object.defineProperty({},lf,{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 Sh(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 aC(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?pf(c,n,o):hf(c,n,o)))return!1;break;case"map":if(!(r.V.kind=="message"?mf(r.V.T(),Wd(n),Wd(o)):pf(r.V.kind=="enum"?O.INT32:r.V.T,Wd(n),Wd(o))))return!1;break;case"message":let d=r.T();if(!(r.repeat?mf(d,n,o):d.equals(n,o)))return!1;break}}return!0}const Wd=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 pf(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 mf(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({})),oC=gf[lf]={};class v{constructor(t,e,r){this.defaultCheckDepth=16,this.typeName=t,this.fields=e.map(Xk),this.options=r!=null?r:{},oC.value=this,this.messagePrototype=Object.create(null,gf),this.refTypeCheck=new eC(this),this.refJsonReader=new tC(this),this.refJsonWriter=new sC(this),this.refBinReader=new rC(this),this.refBinWriter=new iC(this)}create(t){let e=nC(this);return t!==void 0&&Sh(this,e,t),e}clone(t){let e=this.create();return Sh(this,e,t),e}equals(t,e){return aC(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){Sh(this,t,e)}fromBinary(t,e){let r=Fk(e);return this.internalBinaryRead(r.readerFactory(t),t.byteLength,r)}fromJson(t,e){return this.internalJsonRead(t,Yk(e))}fromJsonString(t,e){let r=JSON.parse(t);return this.fromJson(r,e)}toJson(t,e){return this.internalJsonWrite(t,Qk(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=Kk(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 ${hh(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 Xs;(function(s){s[s.PUBLISHER=0]="PUBLISHER",s[s.SUBSCRIBER=1]="SUBSCRIBER"})(Xs||(Xs={}));var Zs;(function(s){s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO"})(Zs||(Zs={}));class cC extends v{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 ff=new cC;class dC extends v{constructor(){super("media.HeaderExtension",[{no:1,name:"direction",kind:"scalar",opt:!0,T:9},{no:2,name:"uri",kind:"scalar",T:9}])}}const lC=new dC;class uC extends v{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new uC;class hC extends v{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",Xs]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const gs=new hC;class pC extends v{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 mC=new pC;class gC extends v{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:()=>gs},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8},{no:5,name:"producers",kind:"message",repeat:1,T:()=>mC}])}}const fC=new gC;class SC extends v{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 vC=new SC;class TC extends v{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>gs},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:4,name:"producer_ids",kind:"scalar",repeat:2,T:9}])}}const Sf=new TC;class yC extends v{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>gs}])}}const EC=new yC;class bC extends v{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>gs}])}}new bC;class wC extends v{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 PC=new wC;class _C extends v{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 kC=new _C;class CC extends v{constructor(){super("media.ProducerEntry",[{no:1,name:"producing_transport_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9}])}}new CC;class RC extends v{constructor(){super("media.ConsumerEntry",[{no:1,name:"consuming_transport_id",kind:"scalar",T:9},{no:2,name:"consumer_id",kind:"scalar",T:9}])}}new RC;class IC extends v{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",Zs]},{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:()=>ff}])}}const co=new IC;class AC extends v{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>co},{no:3,name:"producer_track",kind:"message",T:()=>kC},{no:4,name:"error_code",kind:"scalar",opt:!0,T:9}])}}const MC=new AC;class OC extends v{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>MC}}])}}const vf=new OC;class DC extends v{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>Ef},{no:2,name:"receiver",kind:"message",T:()=>Ef}])}}const Tf=new DC;class NC extends v{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>ff},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>lC}])}}const yf=new NC;class LC extends v{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>yf},{no:2,name:"video",kind:"message",T:()=>yf}])}}const Ef=new LC;class VC extends v{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 xC=new VC;class UC extends v{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 bf=new UC;class $C extends v{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 BC=new $C;class FC extends v{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:()=>BC},{no:9,name:"capabilities",kind:"message",T:()=>Tf}])}}const HC=new FC;class qC extends v{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const jC=new qC;class GC extends v{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const WC=new GC;class JC extends v{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 JC;class KC extends v{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:()=>xC},{no:5,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:6,name:"simulcast",kind:"message",T:()=>bf}])}}const zC=new KC;class YC extends v{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>zC},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const QC=new YC;class XC extends v{constructor(){super("media.edge.UpdateConsumerSimulcastConfigRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"simulcast",kind:"message",T:()=>bf},{no:3,name:"producing_transport_id",kind:"scalar",T:9},{no:4,name:"mid",kind:"scalar",T:9}])}}const ZC=new XC;class eR extends v{constructor(){super("media.edge.UpdateConsumersSimulcastConfigRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>ZC},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const tR=new eR;class sR extends v{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:()=>gs},{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 rR=new sR;class iR extends v{constructor(){super("media.edge.SelectedPeersRequest",[])}}new iR;class nR extends v{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const aR=new nR;class oR extends v{constructor(){super("media.edge.ProducerToggleRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const Jd=new oR;class cR extends v{constructor(){super("media.edge.ConsumerToggleRequest",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}new cR;class dR extends v{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>gs},{no:3,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const lR=new dR;class uR extends v{constructor(){super("media.edge.ConsumerCloseRequest",[{no:1,name:"consumer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"description",kind:"message",T:()=>gs},{no:3,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const hR=new uR;class pR extends v{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new pR;class mR extends v{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const wf=new mR;class gR extends v{constructor(){super("media.edge.PeerDisplayNameEditRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}const fR=new gR;class SR extends v{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 vR=new SR;class TR extends v{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 yR=new TR;class ER extends v{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 bR=new ER;class wR extends v{constructor(){super("media.edge.ErrorResponse",[{no:1,name:"error_message",kind:"scalar",T:9},{no:2,name:"event_id",kind:"scalar",T:5}])}}const PR=new wR;class _R extends v{constructor(){super("media.edge.EmptyResponse",[])}}new _R;class kR extends v{constructor(){super("media.edge.RoomParticipants",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"producer_states",kind:"message",repeat:1,T:()=>co},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"user_id",kind:"scalar",opt:!0,T:9},{no:5,name:"capabilities",kind:"message",T:()=>Tf}])}}const Pf=new kR;class CR extends v{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 vh=new CR;class RR extends v{constructor(){super("media.edge.SelectedPeersDiffEntry",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"priority",kind:"scalar",T:5}])}}const IR=new RR;class AR extends v{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>IR}])}}const _f=new AR;class MR extends v{constructor(){super("media.edge.PeerJoinResponse",[])}}new MR;class OR extends v{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>bR},{no:2,name:"participants",kind:"message",repeat:1,T:()=>Pf},{no:3,name:"selected_peers",kind:"message",T:()=>vh},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const Th=new OR;class DR extends v{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}new DR;class NR extends v{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>vf}])}}new NR;class LR extends v{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>vf},{no:3,name:"description",kind:"message",T:()=>gs}])}}const VR=new LR;class xR extends v{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:()=>gs}])}}const UR=new xR;class $R extends v{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>PC}])}}new $R;class BR extends v{constructor(){super("media.edge.ActiveSpeakerResponse",[{no:1,name:"responsepeer_id",kind:"scalar",T:9},{no:2,name:"volume",kind:"scalar",T:5}])}}new BR;class FR extends v{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new FR;class HR extends v{constructor(){super("media.edge.ProducerToggleResponse",[])}}new HR;class qR extends v{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new qR;class jR extends v{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>gs}])}}const GR=new jR;class WR extends v{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>gs}])}}const JR=new WR;class KR extends v{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new KR;class zR extends v{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new zR;class YR extends v{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new YR;class QR extends v{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const XR=new QR;class ZR extends v{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const eI=new ZR;class tI extends v{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const sI=new tI;class rI extends v{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>Pf}])}}const kf=new rI;class iI extends v{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const Cf=new iI;class nI extends v{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>Cf},{no:3,name:"screenshare",kind:"message",T:()=>Cf}])}}const aI=new nI;class oI extends v{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>Sf},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>aI}])}}new oI;class cI extends v{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>co}])}}const dI=new cI;class lI extends v{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>co},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const yh=new lI;class uI extends v{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>co}])}}const hI=new uI;class pI extends v{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Eh=new pI;class mI extends v{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Rf=new mI;class gI extends v{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new gI;class fI extends v{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new fI;class SI extends v{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new SI;class vI extends v{constructor(){super("media.edge.PeerDisplayNameEditBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}new vI;class TI extends v{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new TI;class yI extends v{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new yI;class EI extends v{constructor(){super("socket.ai.MeetingTranscript",[{no:1,name:"meeting_id",kind:"scalar",T:9},{no:2,name:"transcript",kind:"scalar",T:9},{no:3,name:"is_partial",kind:"scalar",T:8}])}}const bh=new EI;class bI extends v{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 bI;class wI extends v{constructor(){super("socket.api.ErrorMessage",[{no:1,name:"code",kind:"scalar",opt:!0,T:5},{no:2,name:"message",kind:"scalar",T:9}])}}const PI=new wI;var _i;(function(s){s[s.BROWSER=0]="BROWSER",s[s.TRACK=1]="TRACK",s[s.COMPOSITE=2]="COMPOSITE"})(_i||(_i={}));var er;(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"})(er||(er={}));var wh;(function(s){s[s.NONE=0]="NONE",s[s.RECORDER=1]="RECORDER",s[s.LIVESTREAMER=2]="LIVESTREAMER"})(wh||(wh={}));var Ph;(function(s){s[s.PEERS=0]="PEERS",s[s.ROOMS=1]="ROOMS"})(Ph||(Ph={}));var Kd;(function(s){s[s.HIVE=0]="HIVE",s[s.CHAT=1]="CHAT",s[s.PING=2]="PING"})(Kd||(Kd={}));class _I extends v{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 kI=new _I;class CI extends v{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",er,"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:()=>kI}])}}const zd=new CI;class RI extends v{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>zd}])}}const Nn=new RI;class II extends v{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",er,"STAGE_TYPE_"]}])}}const If=new II;class AI extends v{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 MI=new AI;class OI extends v{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>zd}])}}const _h=new OI;class DI extends v{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const Af=new DI;class NI extends v{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:()=>VI},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const Mf=new NI;class LI extends v{constructor(){super("socket.room.ActiveRecording",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",_i]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const VI=new LI;class xI extends v{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>Mf}])}}const Of=new xI;class UI extends v{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const Df=new UI;class $I extends v{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 $I;class BI extends v{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>zd},{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",Kd,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const FI=new BI;class HI extends v{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>zd},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const qI=new HI;class jI extends v{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>Mf}])}}new jI;class GI extends v{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new GI;class WI extends v{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 kh=new WI;class JI extends v{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 KI=new JI;class zI extends v{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:()=>KI}])}}const Nf=new zI;class YI extends v{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>Nf},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>Nf}])}}const QI=new YI;class XI extends v{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const ZI=new XI;class e0 extends v{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>ZI}])}}const t0=new e0;class s0 extends v{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:()=>kh}])}}const r0=new s0;class i0 extends v{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>r0}])}}const Lf=new i0;class n0 extends v{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 a0=new n0;class o0 extends v{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>a0}])}}new o0;class c0 extends v{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const d0=new c0;class l0 extends v{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>d0}])}}const u0=new l0;class h0 extends v{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>g0}])}}const p0=new h0;class m0 extends v{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:()=>kh}])}}const g0=new m0;class f0 extends v{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 S0=new f0;class v0 extends v{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:()=>S0}])}}const T0=new v0;class y0 extends v{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:()=>kh}])}}const Vf=new y0;class E0 extends v{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Vf}])}}new E0;class b0 extends v{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 w0=new b0;class P0 extends v{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>C0}])}}const _0=new P0;class k0 extends v{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 C0=new k0;class R0 extends v{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const xf=new R0;class I0 extends v{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",Ph,"BROADCAST_TYPE_"]}])}}const lo=new I0;class A0 extends v{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const M0=new A0;class O0 extends v{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const D0=new O0;class N0 extends v{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 L0=new N0;class V0 extends v{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>L0}])}}const Uf=new V0;class x0 extends v{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 $f=new x0;var Ch;(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"})(Ch||(Ch={}));var Dr;(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"})(Dr||(Dr={}));class U0 extends v{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 $0=new U0;class B0 extends v{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 F0=new B0;class H0 extends v{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 q0=new H0;class j0 extends v{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 G0=new j0;class W0 extends v{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>q0},{no:2,name:"private",kind:"message",T:()=>G0}])}}const J0=new W0;class K0 extends v{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 z0=new K0;class Y0 extends v{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Dr,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Dr,"STREAM_PERMISSION_TYPE_"]}])}}const Rh=new Y0;class Q0 extends v{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>Rh},{no:2,name:"audio",kind:"message",T:()=>Rh},{no:3,name:"screenshare",kind:"message",T:()=>Rh}])}}const X0=new Q0;class Z0 extends v{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>$0},{no:2,name:"plugins",kind:"message",T:()=>F0},{no:3,name:"chat",kind:"message",T:()=>J0},{no:4,name:"accept_waiting_requests",kind:"scalar",opt:!0,T:8},{no:5,name:"can_accept_production_requests",kind:"scalar",opt:!0,T:8},{no:6,name:"can_edit_display_name",kind:"scalar",opt:!0,T:8},{no:7,name:"can_record",kind:"scalar",opt:!0,T:8},{no:8,name:"can_livestream",kind:"scalar",opt:!0,T:8},{no:9,name:"can_spotlight",kind:"scalar",opt:!0,T:8},{no:10,name:"disable_participant_audio",kind:"scalar",opt:!0,T:8},{no:11,name:"disable_participant_screensharing",kind:"scalar",opt:!0,T:8},{no:12,name:"disable_participant_video",kind:"scalar",opt:!0,T:8},{no:13,name:"kick_participant",kind:"scalar",opt:!0,T:8},{no:14,name:"pin_participant",kind:"scalar",opt:!0,T:8},{no:15,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:16,name:"waiting_room_type",kind:"enum",opt:!0,T:()=>["socket.preset.WaitingRoomType",Ch,"WAITING_ROOM_TYPE_"]},{no:17,name:"is_recorder",kind:"scalar",opt:!0,T:8},{no:18,name:"recorder_type",kind:"enum",opt:!0,T:()=>["socket.room.RecorderType",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:()=>z0},{no:23,name:"media",kind:"message",T:()=>X0}])}}const Ih=new Z0;class eA extends v{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const tA=new eA;class sA extends v{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 rA=new sA;class iA extends v{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>rA}])}}const nA=new iA;class aA extends v{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>Ih}])}}const Bf=new aA;class oA extends v{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>Bf}])}}const cA=new oA;class dA extends v{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>Bf}])}}const Ff=new dA;class lA extends v{constructor(){super("socket.preset.PeerUserIDMap",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9}])}}const uA=new lA;class hA extends v{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>uA},{no:2,name:"patch",kind:"message",T:()=>Ih}])}}new hA;class pA extends v{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>Ih}])}}new pA;class mA extends v{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 Nr=new mA;class gA extends v{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 fA=new gA;class SA extends v{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:()=>fA}])}}const vA=new SA;class TA extends v{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Nr},{no:2,name:"next",kind:"scalar",T:8}])}}const yA=new TA;class EA extends v{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Nr}])}}const Hf=new EA;class bA extends v{constructor(){super("socket.chat.SendChatMessageToRoomRequest",[{no:1,name:"payload_type",kind:"scalar",T:5},{no:2,name:"payload",kind:"scalar",T:9}])}}const wA=new bA;class PA extends v{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>Nr}])}}const Ah=new PA;class _A extends v{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 kA=new _A;class CA extends v{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>Nr}])}}const Mh=new CA;class RA extends v{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 RA;class IA extends v{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>Nr}])}}new IA;class AA extends v{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 MA=new AA;class OA extends v{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 DA=new OA;class NA extends v{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:()=>Nr}])}}const Yd=new NA;class LA extends v{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>Nr}])}}const Qd=new LA;class VA extends v{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 xA=new VA;class UA extends v{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 Xd=new UA;class $A extends v{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 BA=new $A;class FA extends v{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 FA;class HA extends v{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}new HA;class qA extends v{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 qA;class jA extends v{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 jA;class GA extends v{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new GA;class WA extends v{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new WA;class JA extends v{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>Nr},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const KA=new JA;class zA extends v{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:()=>KA},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const YA=new zA;class QA extends v{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>YA}])}}new QA;class XA extends v{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 ZA=new XA;class eM extends v{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>ZA}])}}new eM;class tM extends v{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}new tM;class sM extends v{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}new sM;class rM extends v{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}new rM;class iM extends v{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}new iM;class nM extends v{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 nM;class aM extends v{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 aM;class oM extends v{constructor(){super("socket.plugin.PluginEventToRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}new oM;class cM extends v{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 cM;class dM extends v{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 Oh=new dM;class lM extends v{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:()=>Oh}])}}const uM=new lM;class hM extends v{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:()=>Oh}])}}const pM=new hM;class mM extends v{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:()=>Oh}])}}const gM=new mM;class fM extends v{constructor(){super("socket.plugin.PluginStoreDeleteRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9}])}}new fM;class SM extends v{constructor(){super("socket.plugin.EnablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"enabled_by",kind:"scalar",T:9}])}}const vM=new SM;class TM extends v{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>vM}])}}new TM;class yM extends v{constructor(){super("socket.plugin.DisablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"disabled_by",kind:"scalar",T:9}])}}new yM;class EM extends v{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 bM=new EM;class wM extends v{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:()=>bM}])}}const qf=new wM;class PM extends v{constructor(){super("socket.plugin.PluginEventResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}new PM;class _M extends v{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 jf=new _M;class kM extends v{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const Gf=new kM;class CM extends v{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 RM=new CM;class IM extends v{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>RM}])}}const Dh=new IM;class AM extends v{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const MM=new AM;class OM extends v{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const DM=new OM;class NM extends v{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const Wf=new NM;class LM extends v{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:()=>xM},{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 Jf=new LM;class VM extends v{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:()=>$M}])}}const xM=new VM;class UM extends v{constructor(){super("socket.polls.PollVote",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])}}const $M=new UM;class BM extends v{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 FM=new BM;class HM extends v{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 qM=new HM;class jM extends v{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>Jf}])}}const Nh=new jM;class GM extends v{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>Jf}])}}const WM=new GM;class JM extends v{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",_i]}])}}const Kf=new JM;class KM extends v{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=Se.from(Math.floor(e/1e3)).toBigInt(),t.nanos=e%1e3*1e6,t}toDate(t){return new Date(Se.from(t.seconds).toNumber()*1e3+Math.ceil(t.nanos/1e6))}fromDate(t){const e=this.create(),r=t.getTime();return e.seconds=Se.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}internalJsonWrite(t,e){let r=Se.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 "+hh(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=Se.from(n/1e3).toBigInt(),r.nanos=0,i[7]&&(r.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),r}}new KM;class zM extends v{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 Lh=new zM;class YM extends v{constructor(){super("common.BulkedHubMessage",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Lh}])}}new YM;class QM extends v{constructor(){super("common.CFWorkersResponse",[{no:1,name:"responses",kind:"message",repeat:1,T:()=>Lh},{no:2,name:"broadcast_responses",kind:"message",repeat:1,T:()=>Lh}])}}new QM;const XM=0,ZM=1,eO=2,tO=3,sO=5,rO={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},iO={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,searchChannelMessages:7,pinMessage:10},nO={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},aO={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},zf={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},oO={getUserPresets:0,updateUserPreset:1};function uo(s,t){return Object.keys(t).reduce((e,r)=>(e[r]=(s<<16)+t[r],e),{})}function Yf(s,t){return Object.keys(s).reduce((e,r)=>(e[r]=t|s[r],e),{})}const $=uo(XM,rO),Ge=uo(ZM,iO),tr=uo(eO,nO),sr=uo(tO,aO),Lr=Yf(zf,16777216),fs=Yf(zf,50331648),Zd=uo(sO,oO);var cO=Object.defineProperty,dO=Object.getOwnPropertyDescriptor,Vr=(s,t,e,r)=>{for(var i=r>1?void 0:r?dO(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&&cO(t,e,i),i},Zt=(s=>(s[s.TEXT=0]="TEXT",s[s.IMAGE=1]="IMAGE",s[s.FILE=2]="FILE",s[s.CUSTOM=3]="CUSTOM",s))(Zt||{});class rr{constructor(t,e){m(this,Bt,void 0);m(this,zn,void 0);g(this,Bt,e),g(this,zn,t)}get telemetry(){return a(this,zn).getValue("telemetry")}get logger(){return a(this,zn).getValue("logger")}getChatMessages(){return a(this,Bt).sendMessagePromise(Ge.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,Bt).sendMessagePromise(Ge.getPaginatedMessages,vA.toBinary(n));return o.payload?yA.fromBinary(o.payload):{messages:[],next:!1}}sendMessageToRoom(t,e){const r={payloadType:e,payload:t};a(this,Bt).sendMessage(Ge.sendMessageToRoom,wA.toBinary(r))}sendMessageToPeers(t,e,r){const i={payloadType:e,peerIds:r,payload:t};a(this,Bt).sendMessage(Ge.sendMessageToPeers,kA.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,Bt).sendMessagePromise(Ge.editMessage,MA.toBinary(n));return Qd.fromBinary(o.payload).message}async deleteMessage(t){const e={chatId:t},r=await a(this,Bt).sendMessagePromise(Ge.deleteMessage,xA.toBinary(e));return{id:Xd.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,Bt).sendMessagePromise(Ge.searchChannelMessages,BA.toBinary(r));return Hf.fromBinary(d.payload).messages}catch(d){return[]}}async setPinState(t,e){const r={chatId:t,pinned:e},i=await a(this,Bt).sendMessagePromise(Ge.pinMessage,DA.toBinary(r));return Yd.fromBinary(i.payload)}on(t,e){let r,i;switch(t){case Ge.sendMessageToRoom:{r=Ah.fromBinary.bind(Ah),i=Ah.create();break}case Ge.sendMessageToPeers:{r=Mh.fromBinary.bind(Mh),i=Mh.create();break}case Ge.editMessage:{r=Qd.fromBinary.bind(Qd),i=Qd.create();break}case Ge.pinMessage:{r=Yd.fromBinary.bind(Yd),i=Yd.create();break}case Ge.deleteMessage:{r=Xd.fromBinary.bind(Xd),i=Xd.create();break}}if(!r){this.logger.warn(`ChatSocketHandler::Event ${t} is not recognized`);return}a(this,Bt).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)})}}Bt=new WeakMap,zn=new WeakMap,Vr([y.trace("SocketService.getChatMessages")],rr.prototype,"getChatMessages",1),Vr([y.trace("SocketService.getChatMessagesPaginated")],rr.prototype,"getChatMessagesPaginated",1),Vr([y.trace("SocketService.sendMessageToRoom")],rr.prototype,"sendMessageToRoom",1),Vr([y.trace("SocketService.sendMessageToPeers")],rr.prototype,"sendMessageToPeers",1),Vr([y.trace("SocketService.sendMessage")],rr.prototype,"sendMessage",1),Vr([y.trace("SocketService.editMessage")],rr.prototype,"editMessage",1),Vr([y.trace("SocketService.deleteMessage")],rr.prototype,"deleteMessage",1),Vr([y.trace("SocketService.searchMessages")],rr.prototype,"searchMessages",1);function lO(s){return s.replace(/([-_]\w)/g,t=>t[1].toUpperCase())}function Ms(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>Ms(e));const t={};return Object.keys(s).forEach(e=>{const r=Nu(e)?e:lO(e);t[r]=Ms(s[e])}),t}function uO(s){return s.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Qf(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>Qf(e));const t={};return Object.keys(s).forEach(e=>{const r=Nu(e)?e:uO(e);t[r]=s[e]}),t}class el 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 Xf{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 f=new AbortController,S=setTimeout(()=>f.abort(),d);c.signal=f.signal;const E=await fetch(r,c);clearTimeout(S);let k=null;const I=E.headers.get("content-type");I&&I.includes("application/json")?k=await E.json():k=await E.text();const R={};E.headers.forEach((D,x)=>{R[x]=D});const U={data:k,status:E.status,statusText:E.statusText,headers:R,config:t};if(!E.ok)throw U;return U}catch(f){if(f instanceof Error&&l>0)return await new Promise(S=>setTimeout(S,u)),this.defaults.baseURL===Pi.apiBase.prod?this.defaults.baseURL=Pi.apiBase.prodAlternate:this.defaults.baseURL===Pi.apiBase.prodAlternate&&(this.defaults.baseURL=Pi.apiBase.prod),this.request({...t,retry:l-1});throw f}}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 hO=3,pO=30,mO=8e3;class gO{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=mO,retry:i=hO,retryDelay:n=pO,baseURL:o=Pi.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 Xf({baseURL:o,timeout:r,retry:i,retryDelay:n,responseType:"json"}),this.fetchClient=new Xf({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 f,S,E,k,I;const h=t.getValue("telemetry");try{h.injectContext(this.requests.defaults.headers.common);const R=await l(u);return u.url!==h.logsEndpoint&&this.logger.debug("xhr::fetch",{networkCall:{status:R.status,statusText:R.statusText,baseURL:u.baseURL||this.requests.defaults.baseURL,url:u.url,method:u.method}}),R}catch(R){if(!R)throw new P("Unknown network error occurred","0011");if(R instanceof P||R instanceof el)throw R;((f=R.config)==null?void 0:f.url)!==h.logsEndpoint&&this.logger.error("xhr::fetch",{error:R,networkCall:{status:R.status,statusText:R.statusText,baseURL:((S=R.config)==null?void 0:S.baseURL)||this.requests.defaults.baseURL,url:(E=R.config)==null?void 0:E.url,retries:(k=R.config)==null?void 0:k.retry,method:(I=R.config)==null?void 0:I.method,isOnline:navigator.onLine?"online":"offline"}});const U=R instanceof Error&&R.message||"Network request failed";throw new P(U,"0011"),new el(R)}}}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 fO=Object.defineProperty,SO=Object.getOwnPropertyDescriptor,ir=(s,t,e,r)=>{for(var i=r>1?void 0:r?SO(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};class Os extends gO{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=ao(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=Ms(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=Ms((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 Ms(e)}async startRecording(e,r){return(await this.requests.post("/v2/recordings",{...Qf(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 P("Cant fetch transcript s3 url","1801")}}}ir([y.trace("APIClient.getICEServers")],Os.prototype,"getICEServers",1),ir([y.trace("APIClient.startLivestreaming")],Os.prototype,"startLivestreaming",1),ir([y.trace("APIClient.stopLivestreaming")],Os.prototype,"stopLivestreaming",1),ir([y.trace("APIClient.getActiveLivestream")],Os.prototype,"getActiveLivestream",1),ir([y.trace("APIClient.getUserDetails")],Os.prototype,"getUserDetails",1),ir([y.trace("APIClient.startRecording")],Os.prototype,"startRecording",1),ir([y.trace("APIClient.stopRecording")],Os.prototype,"updateRecording",1),ir([y.trace("APIClient.getActiveRecording")],Os.prototype,"getActiveRecording",1),ir([y.trace("APIClient.getActiveTranscript")],Os.prototype,"getActiveTranscript",1);let Vh;function vO(s,t){return Vh=new Os(s,t),Vh}function Vt(){return Vh}const Ln={maxInvocations:5,period:1};function xt(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 P(`Method rate limit ${u.maxInvocations} invocations/${u.period}sec exceeded`,"0013");return o+=1,n.apply(this,d)},i}}var TO=Object.defineProperty,yO=Object.getOwnPropertyDescriptor,Ds=(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&&TO(t,e,i),i};const EO=["text","image","file","custom","poll"],tl={maxInvocations:180,period:60};let es=(uv=class extends Nt{constructor(t,e,r,i){const n=t.getValue("logger");super(n);m(this,Il);m(this,Do);p(this,"messages");m(this,re,void 0);m(this,xi,void 0);m(this,rt,void 0);m(this,Yn,void 0);p(this,"maxTextLimit",2e3);g(this,Yn,t),g(this,rt,e),g(this,re,r),g(this,xi,i),this.messages=[]}get telemetry(){return a(this,Yn).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 P("Max character limit breached","0503");if(e&&e.length>0){if(!((i=a(this,re).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,re).permissions)!=null&&n.chatPrivate.text))throw this.logger.error("sendTextMessage::private_chat_permission_denied"),new P("Could not send message to private chat.","0501")}else if(!((c=(o=a(this,re).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,re).permissions)==null?void 0:d.chatPublic)!=null&&l.text))throw this.logger.error("sendTextMessage::public_chat_permission_denied"),new P("Could not send message to public chat.","0501");if(!t)throw this.logger.error("sendTextMessage::message_can_not_be_empty"),new P("Message can not be empty.","0502");let r=[];e&&e.length>0&&(e.push(a(this,re).id),r=a(this,xi).joined.toArray().filter(u=>e.includes(u.id)).map(u=>u.userId),r.push(a(this,re).userId)),a(this,rt).sendMessage(t,Zt.TEXT,e)}async sendImageMessageInternal(t,e){var i,n,o,c,d,l;if(e&&e.length>0){if(!((i=a(this,re).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,re).permissions)!=null&&n.chatPrivate.files)){this.logger.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((c=(o=a(this,re).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,re).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=Vt(),{getLocation:h,putLocation:f}=await u.getPresignedUrls(t.name);await u.uploadFile(t,f);let S=[];e&&e.length>0&&(e.push(a(this,re).id),S=a(this,xi).joined.toArray().filter(E=>e.includes(E.id)).map(E=>E.userId),S.push(a(this,re).userId)),a(this,rt).sendMessage(h,Zt.IMAGE,e)}catch(u){throw new P("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,re).permissions)!=null&&r.chatPrivate.canSend)||!((i=a(this,re).permissions)!=null&&i.chatPrivate.files)){this.logger.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((o=(n=a(this,re).permissions)==null?void 0:n.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,re).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=Vt(),{getLocation:u,putLocation:h}=await l.getPresignedUrls(t.name);await l.uploadFile(t,h);let f=[];e&&e.length>0&&(e.push(a(this,re).id),f=a(this,xi).joined.toArray().filter(E=>e.includes(E.id)).map(E=>E.userId),f.push(a(this,re).userId));const S=JSON.stringify({link:u,name:t.name,size:"size"in t?t.size:0});a(this,rt).sendMessage(S,Zt.FILE,e)}catch(l){throw new P("Error sending file message.","0500",this.logger)}}get rateLimits(){return tl}updateRateLimits(t,e){tl.maxInvocations=t,tl.period=e}async sendTextMessage(t,e){return this.sendTextMessageInternal(t,e)}async sendCustomMessage(t,e){var n,o,c,d,l,u,h,f,S,E,k,I,R,U,D;if(e&&e.length>0){if(!((n=a(this,re).permissions)!=null&&n.chatPrivate.canSend)||!((o=a(this,re).permissions)!=null&&o.chatPrivate.files)||!((c=a(this,re).permissions)!=null&&c.chatPrivate.text)){this.logger.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((l=(d=a(this,re).permissions)==null?void 0:d.chatPublic)!=null&&l.canSend)||!((h=(u=a(this,re).permissions)==null?void 0:u.chatPublic)!=null&&h.files)||!((S=(f=a(this,re).permissions)==null?void 0:f.chatPublic)!=null&&S.text)){this.logger.error("sendCustomMessage::permission_denied");return}const r=async x=>{try{if(typeof x=="string")return{link:x};const B=Vt(),{getLocation:q,putLocation:Z}=await B.getPresignedUrls(x.name);return await B.uploadFile(x,Z),{link:q,type:x.type,name:x.name,size:x.size}}catch(B){throw new P("Error sending image message.","0500",this.logger)}},i={...t,files:await Promise.all((k=(E=t.files)!=null?E:[])==null?void 0:k.map(async x=>r(x))),images:await Promise.all((R=(I=t.images)!=null?I:[])==null?void 0:R.map(async x=>r(x))),videos:await Promise.all((D=(U=t.videos)!=null?U:[])==null?void 0:D.map(async x=>r(x)))};a(this,rt).sendMessage(JSON.stringify(i),Zt.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,re).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(n=a(this,re).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,rt).editMessage(t,e,Zt.TEXT)}async editImageMessage(t,e){var i,n,o,c;if(!((n=(i=a(this,re).permissions)==null?void 0:i.chatPublic)!=null&&n.canSend)||!((c=(o=a(this,re).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=Vt(),{getLocation:l,putLocation:u}=await d.getPresignedUrls(e.name);await d.uploadFile(e,u),a(this,rt).editMessage(t,l,Zt.IMAGE)}catch(d){throw new P("Error editing image message.","0500",this.logger)}}async editFileMessage(t,e){var r,i,n,o;if(!((i=(r=a(this,re).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(n=a(this,re).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=Vt(),{getLocation:d,putLocation:l}=await c.getPresignedUrls(e.name);await c.uploadFile(e,l),a(this,rt).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),Zt.FILE)}catch(c){throw new P("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,rt).deleteMessage(t)}async pin(t){if(!a(this,Do,bp))throw new P("Can`t pin message without joining room","0505");try{await a(this,rt).setPinState(t,!0)}catch(e){throw new P(`No message found with id: ${t}`,"0504")}}async unpin(t){if(!a(this,Do,bp))throw new P("Can`t unpin message without joining room","0505");try{await a(this,rt).setPinState(t,!1)}catch(e){throw new P(`No message found with id: ${t}`,"0504")}}async fetchPublicMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await a(this,rt).getChatMessagesPaginated(t,e,r==="before")).messages.map(o=>ho.formatSocketPeerMessage(o))}async fetchPrivateMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after",userId:i}){return(await a(this,rt).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"userId",userId:i})).messages.map(c=>ho.formatSocketPeerMessage(c))}async fetchPinnedMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await a(this,rt).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"pinned",pinned:!0})).messages.map(o=>ho.formatSocketPeerMessage(o))}},re=new WeakMap,xi=new WeakMap,rt=new WeakMap,Yn=new WeakMap,Il=new WeakSet,Iv=function(){return a(this,Yn).getValue("connectionHandler")},Do=new WeakSet,bp=function(){return a(this,Il,Iv).socketJoined===!0},uv);Ds([y.trace("Chat.sendTextMessage"),xt(tl)],es.prototype,"sendTextMessage",1),Ds([y.trace("Chat.sendImageMessage"),xt({maxInvocations:20,period:60})],es.prototype,"sendImageMessage",1),Ds([y.trace("Chat.sendFileMessage"),xt({maxInvocations:20,period:60})],es.prototype,"sendFileMessage",1),Ds([y.trace("Chat.sendMessage"),xt({maxInvocations:180,period:60})],es.prototype,"sendMessage",1),Ds([y.trace("Chat.editTextMessage")],es.prototype,"editTextMessage",1),Ds([y.trace("Chat.editImageMessage")],es.prototype,"editImageMessage",1),Ds([y.trace("Chat.editFileMessage")],es.prototype,"editFileMessage",1),Ds([y.trace("Chat.editMessage")],es.prototype,"editMessage",1),Ds([y.trace("Chat.deleteMessage")],es.prototype,"deleteMessage",1),es=Ds([ct("0500")],es);var bO=Object.defineProperty,wO=Object.getOwnPropertyDescriptor,PO=(s,t,e,r)=>{for(var i=r>1?void 0:r?wO(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&&bO(t,e,i),i};const xr=(hv=class{constructor(s,t,e,r){p(this,"chat");p(this,"chatSocketHandler");p(this,"self");m(this,Ui,void 0);g(this,Ui,s),this.chatSocketHandler=t,this.chat=new es(s,t,e,r),this.self=e,this.setupEvents()}get telemetry(){return a(this,Ui).getValue("telemetry")}get logger(){return a(this,Ui).getValue("logger")}static async init(s,t,e,r){return new xr(s,t,e,r)}static formatMessage(s){return{...s,time:new Date(s.time),type:EO[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 Zt.TEXT:{e.message=s.payload;break}case Zt.IMAGE:{e.link=s.payload;break}case Zt.FILE:{const{link:r,name:i,size:n}=JSON.parse(s.payload);e.link=r,e.name=i,e.size=n;break}case Zt.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 xr.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=Hf.fromBinary(s.payload).messages;this.chat.messages=t.map(e=>xr.formatSocketPeerMessage(e))}setupEvents(){a(this,Ui).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,async()=>{this.getChatMessages()}),this.chatSocketHandler.on(Ge.sendMessageToRoom,s=>{if(!s.message)return;const t=xr.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(Ge.sendMessageToPeers,s=>{const t=xr.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(Ge.editMessage,s=>{if(!s.message)return;const t=xr.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(Ge.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(Ge.pinMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId),e=xr.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})})}},Ui=new WeakMap,hv);let ho=xr;PO([y.trace("ChatController.setupEvents")],ho.prototype,"setupEvents",1);var _O=Object.defineProperty,kO=Object.getOwnPropertyDescriptor,CO=(s,t,e,r)=>{for(var i=r>1?void 0:r?kO(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&&_O(t,e,i),i};let xh=(pv=class extends Nt{constructor(t,e,r){const i=t.getValue("logger");super(i);m(this,Al);m(this,Ml);p(this,"items");m(this,Qn,void 0);m(this,Xn,void 0);m(this,No,void 0);g(this,No,t),g(this,Qn,e),g(this,Xn,r),this.items=[]}async create(t,e,r=!1,i=!1){if(!a(this,Ml,Mv))throw new P("Can't create polls without joining room","0705");if(!a(this,Qn).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,Xn).createPoll(t,e,r,i)}async vote(t,e){if(!a(this,Qn).permissions.polls.canVote){this.logger.error("Polls::vote::permission_denied");return}await a(this,Xn).votePoll(t,e)}},Al=new WeakSet,Av=function(){return a(this,No).getValue("connectionHandler")},Ml=new WeakSet,Mv=function(){var t;return((t=a(this,Al,Av))==null?void 0:t.socketJoined)===!0},Qn=new WeakMap,Xn=new WeakMap,No=new WeakMap,pv);xh=CO([ct("0700")],xh);var RO=Object.defineProperty,IO=Object.getOwnPropertyDescriptor,AO=(s,t,e,r)=>{for(var i=r>1?void 0:r?IO(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&&RO(t,e,i),i};const Vn=(mv=class{constructor(s,t,e){p(this,"polls");m(this,Kr,void 0);m(this,Zn,void 0);m(this,$i,void 0);this.polls=new xh(s,t,e),g(this,Zn,t),g(this,Kr,s),g(this,$i,e),this.setupEvents()}get telemetry(){return a(this,Kr).getValue("telemetry")}get logger(){return a(this,Kr).getValue("logger")}static async init(s,t,e){return new Vn(s,t,e)}canViewPolls(){return a(this,Zn).permissions.polls.canView}setupEvents(){const s={[sr.createPoll]:r=>{r.poll&&this.updatePoll(Vn.formatSocketServicePoll(r.poll))},[sr.updatePoll]:r=>{r.poll&&this.updatePoll(Vn.formatSocketServicePoll(r.poll))},[sr.votePoll]:r=>{r.poll&&this.updatePoll(Vn.formatSocketServicePoll(r.poll))}},t=()=>{a(this,Kr).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,$i).on(r,s[r])})},e=()=>{a(this,Kr).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,$i).removeListeners(r)})};a(this,Zn).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,$i).getPolls();if(!(s!=null&&s.payload))return;const{polls:t}=WM.fromBinary(s.payload);this.polls.items=t.map(e=>Vn.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}}},Kr=new WeakMap,Zn=new WeakMap,$i=new WeakMap,mv);let Zf=Vn;AO([y.trace("PollController.setupEvents")],Zf.prototype,"setupEvents",1);var MO=Object.defineProperty,OO=Object.getOwnPropertyDescriptor,DO=(s,t,e,r)=>{for(var i=r>1?void 0:r?OO(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&&MO(t,e,i),i},eS=(s=>(s[s.User=0]="User",s[s.Meeting=1]="Meeting",s))(eS||{});let Uh=(gv=class extends Nt{constructor(t,e,r,i,n){const o=t.getValue("logger");super(o);m(this,Lo);p(this,"selfActiveTab");p(this,"broadcastTabChanges");m(this,ea,void 0);m(this,Bi,void 0);m(this,Vo,void 0);p(this,"viewType");p(this,"meetingStartedTimestamp");p(this,"meetingTitle");p(this,"sessionId");g(this,ea,t),g(this,Bi,e),this.viewType=r,g(this,Vo,i),this.meetingTitle=n,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return a(this,Lo,wp).socketState}get mediaState(){return a(this,Lo,wp).mediaState}get meetingId(){return a(this,ea).getValue("meetingId")}setBroadcastTabChanges(t){if(!a(this,Bi).permissions.canSpotlight)throw this.logger.error("Spotlight::setSpotlighted::permission_denied"),new P("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,Bi).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){a(this,Vo).broadcastMessage("spotlight",{userId:a(this,Bi).userId,currentTab:this.selfActiveTab})}},ea=new WeakMap,Lo=new WeakSet,wp=function(){return a(this,ea).getValue("connectionHandler")},Bi=new WeakMap,Vo=new WeakMap,gv);Uh=DO([ct("0800")],Uh);function NO(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=>Ur.parseTranscript(e,!1)).filter(Boolean):[]}async getActiveTranscript(){try{const t=Vt(),{transcript:e}=await t.getActiveTranscript();this.transcripts=Ur.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)}},xo=new WeakMap,fv);tS([y.trace("Ai.getActiveTranscript")],Ur.prototype,"getActiveTranscript",1),Ur=tS([ct("0000")],Ur);var xO=Object.defineProperty,UO=Object.getOwnPropertyDescriptor,$O=(s,t,e,r)=>{for(var i=r>1?void 0:r?UO(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 sS=(Sv=class{constructor(s,t,e,r,i,n){p(this,"meta");p(this,"ai");m(this,zr,void 0);m(this,ta,void 0);p(this,"aiSocketHandler");m(this,Ft,void 0);g(this,Ft,s),this.meta=new Uh(s,t,t.config.viewType,e,n),this.ai=r,g(this,zr,t),g(this,ta,e),this.aiSocketHandler=i,this.setupEvents()}get telemetry(){return a(this,Ft).getValue("telemetry")}get logger(){return a(this,Ft).getValue("logger")}static async init(s,t,e,r,i){const n=await Ur.init(s,t.permissions.transcriptionEnabled);return new sS(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,eS.Meeting),this.meta.emit("activeTabUpdate",s.currentTab))}setupEvents(){a(this,Ft).getValue("peerSessionStore").on(_.TRANSPORT_STATE_UPDATE,s=>{this.meta.emit("mediaConnectionUpdate",s)}),a(this,Ft).getValue("peerSessionStore").on(_.SOCKET_STATE_UPDATE,s=>{this.meta.emit("socketConnectionUpdate",s)}),a(this,Ft).getValue("peerSessionStore").on(_.ROOM_STATE,({createdAt:s,roomUuid:t})=>{const e=this.meta.meetingStartedTimestamp;if(t&&(this.meta.sessionId=t),s&&!e){const r=new Date(s*1e3);this.meta.meetingStartedTimestamp=r,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),a(this,Ft).getValue("peerSessionStore").on(_.PRODUCER_SCORE_UPDATE,({score:s})=>{s<5&&this.meta.emit("poorConnection",{score:s})}),a(this,zr).permissions.canSpotlight&&(this.logger.info("MetaController::Asserting Spotlight"),this.meta.selfActiveTab&&a(this,ta).broadcastMessage("spotlight",{userId:a(this,zr).userId,currentTab:this.meta.selfActiveTab})),a(this,Ft).getValue("peerSessionStore").on(_.PEER_JOINED_INTERNAL,async s=>{a(this,zr).permissions.canSpotlight&&this.meta.selfActiveTab&&a(this,ta).broadcastToPeers("spotlight",[s.id],{userId:a(this,zr).userId,currentTab:this.meta.selfActiveTab})}),a(this,Ft).getValue("peerSessionStore").on(_.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,Ft).getValue("peerSessionStore").on(_.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)}),this.aiSocketHandler.on($.transcript,s=>{const{meetingId:t,transcript:e,isPartial:r}=s;let i;try{i=Ur.parseTranscript(e,r)}catch(d){this.logger.error(`Failed to parse transcript: ${e}`,d)}if(!i){this.logger.warn("Received empty transcript data");return}this.ai.onTranscript(i);const{peerId:n,name:o,transcript:c}=i;this.logger.debug(`${t} Received transcript for peer ${n} - ${o}: ${c}`)})}},zr=new WeakMap,ta=new WeakMap,Ft=new WeakMap,Sv);let rS=sS;$O([y.trace("MetaController.setupEvents")],rS.prototype,"setupEvents",1);const po={},nr={executeWithLock({methodName:s,lockName:t,timeout:e}){return(r,i,n)=>{const o=n.value;return n.value=function(...d){var E,k;const l=(k=(this==null?void 0:this.peerId)||((E=d[0])==null?void 0:E.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 f=setTimeout(()=>delete po[u],e),S=o.apply(this,d);return Promise.resolve(S).then(()=>{delete po[u],clearTimeout(f)}).catch(()=>{delete po[u],clearTimeout(f)}),S},n}}};var BO=Object.defineProperty,FO=Object.getOwnPropertyDescriptor,ki=(s,t,e,r)=>{for(var i=r>1?void 0:r?FO(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&&BO(t,e,i),i};class $r extends Nt{constructor(e,r,i,n,o){const c=e.getValue("logger");super(c);m(this,$o);m(this,sa);m(this,is,void 0);m(this,Ol,void 0);m(this,de,void 0);m(this,Uo,void 0);m(this,Ls,void 0);m(this,Ke,void 0);g(this,Ke,e),g(this,is,n),g(this,Ol,o),g(this,de,r),g(this,Uo,i),g(this,Ls,[]),this.setupEvents()}get telemetry(){return a(this,Ke).getValue("telemetry")}get status(){return a(this,Ke).getValue("stageStatus")}setupEvents(){const e={[_.GET_STAGE_REQUESTS]:async n=>{g(this,Ls,n)},[_.UPDATE_STAGE_REQUESTS]:async({add:n})=>{const o=a(this,Ls).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,Ke).getValue("peerSessionStore").onAsync(n,o)})},i=()=>{Object.entries(e).forEach(([n,o])=>{a(this,Ke).getValue("peerSessionStore").removeListener(n,o)})};a(this,de).permissions.on("permissionsUpdate",n=>{const{canAcceptProductionRequests:o}=n;o!==void 0&&(a(this,de).permissions.acceptStageRequests?(r(),a(this,is).getStageRequests()):(i(),g(this,Ls,[]),this.emit("stageAccessRequestUpdate",a(this,Ls))))}),a(this,de).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!a(this,de).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new P("Stage is disabled","2003");if(!a(this,de).permissions.acceptStageRequests)throw this.logger.error("Stage::get_access_request::permission_denied"),new P("You do not have permission to perform this action","2001");const e=a(this,Uo).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return g(this,Ls,e),{stageRequests:a(this,Ls)}}async requestAccess(){if(!a(this,de).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new P("Stage is disabled","2003");if(this.status!=="OFF_STAGE")throw new P(`Unable to request access you are currently ${this.status}`,"2006");if(a(this,de).permissions.stageAccess===G.Allowed){N(this,sa,Iu).call(this,"ACCEPTED_TO_JOIN_STAGE");return}a(this,is).requestAccess(),N(this,sa,Iu).call(this,"REQUESTED_TO_JOIN_STAGE")}async cancelRequestAccess(){if(!a(this,de).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new P("Stage is disabled","2003");a(this,is).cancelRequestAccess(),N(this,sa,Iu).call(this,"OFF_STAGE")}grantAccess(e){if(!a(this,de).roomJoined)throw new P("Can`t grant for participant without joining room");if(!a(this,de).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new P("Stage is disabled","2003");if(!a(this,de).permissions.acceptStageRequests)throw this.logger.error("Stage::grant_access::permission_denied"),new P("You do not have permission to perform this action","2001");return a(this,is).grantAccess(e)}denyAccess(e){if(!a(this,de).roomJoined)throw new P("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!a(this,de).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new P("Stage is disabled","2003");if(!a(this,de).permissions.acceptStageRequests)throw this.logger.error("Stage::deny_access::permission_denied"),new P("You do not have permission to perform this action","2001");return a(this,is).denyAccess(e)}get peerId(){return a(this,Ke).getValue("peerId")}async join(){const e=a(this,Ke).getValue("viewType");if(this.status==="ON_STAGE")throw new P("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||a(this,de).permissions.stageAccess===G.NotAllowed)throw new P(`Unable to join stage you are currently ${this.status}`,"2006");if(a(this,Ke).setValue("stageStatus","ON_STAGE",!1),await a(this,is).joinStage(),e===Ys.Livestream){await a(this,Ke).getValue("selfController").joinRoom();return}a(this,Ke).notify("stageStatus"),a(this,de).audioEnabled&&a(this,$o,Pp).shareMic(a(this,de).audioTrack),a(this,de).videoEnabled&&a(this,$o,Pp).shareWebcam(a(this,de).videoTrack)}async leave(){if(!a(this,de).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new P("Stage is disabled","2003");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new P(`Unable to leave stage you are currently ${this.status}`,"2006");a(this,de).setIsPinned(!1),a(this,Ke).setValue("stageStatus","OFF_STAGE",!1),await a(this,is).leaveStage(a(this,de).userId);try{await a(this,Ke).getValue("peerSessionStore").emitAsync(_.LEAVE_MEDIA_ROOM,"stageLeft")}catch(e){this.logger.error("Stage::leave::emitAsync::failed",{error:e})}a(this,Ke).notify("stageStatus")}async kick(e){if(!a(this,de).roomJoined)throw new P("Can`t kick participant without joining room","2005");if(!a(this,de).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new P("Stage is disabled","2003");if(!a(this,de).permissions.acceptStageRequests)throw this.logger.error("Stage::kick::permission_denied"),new P("You do not have permissions for kick","2001");return a(this,is).kick(e)}}is=new WeakMap,Ol=new WeakMap,de=new WeakMap,Uo=new WeakMap,Ls=new WeakMap,Ke=new WeakMap,$o=new WeakSet,Pp=function(){return a(this,Ke).getValue("roomNodeClient")},sa=new WeakSet,Iu=async function(e){this.status!==e&&a(this,Ke).setValue("stageStatus",e)},ki([y.trace("Stage.getStageRequests")],$r.prototype,"getAccessRequests",1),ki([y.trace("Stage.requestAccess")],$r.prototype,"requestAccess",1),ki([y.trace("Stage.cancelRequestAccess")],$r.prototype,"cancelRequestAccess",1),ki([y.trace("Stage.grantAccess")],$r.prototype,"grantAccess",1),ki([y.trace("Stage.denyAccess")],$r.prototype,"denyAccess",1),ki([nr.executeWithLock({methodName:"joinStage",lockName:"Stage.join",timeout:5e3}),y.trace("Stage.joinStage")],$r.prototype,"join",1),ki([y.trace("Stage.leaveStage")],$r.prototype,"leave",1);function HO(s){return!(s.viewType==="LIVESTREAM"||s.viewType==="CHAT")}function $h(s){switch(s){case er.UNSPECIFIED:return"OFF_STAGE";case er.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case er.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case er.OFF_STAGE:return"OFF_STAGE";case er.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var qO=Object.defineProperty,jO=Object.getOwnPropertyDescriptor,GO=(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};class iS{constructor(t,e,r,i,n){p(this,"stage");m(this,Yr,void 0);m(this,ys,void 0);m(this,Qr,void 0);m(this,Bo,0);m(this,vt,void 0);g(this,vt,t),this.stage=new $r(t,i,n,e,r),g(this,Qr,e),g(this,Yr,i),g(this,ys,n),this.setupEvents()}get telemetry(){return a(this,vt).getValue("telemetry")}get logger(){return a(this,vt).getValue("logger")}setupEvents(){a(this,vt).subscribe("stageStatus",t=>{this.stage.emit("stageStatusUpdate",t)}),a(this,Qr).on($.grantStageAccess,()=>{a(this,Yr).permissions.stageAccess!==G.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),a(this,Qr).on($.peerStageStatusUpdate,t=>{t!==void 0&&(t.peerId===a(this,Yr).id?this.selfStageStatusHandler(t):this.peerStageStatusHandler(t))}),a(this,Qr).on($.denyStageAccess,()=>{a(this,Yr).permissions.stageAccess!==G.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),a(this,Qr).on($.getStageRequests,async t=>{var r;if(a(this,Yr).permissions.stageAccess!==G.Allowed)return;const e=(r=t==null?void 0:t.stageRequests)!=null?r:[];await a(this,vt).getValue("peerSessionStore").emitAsync(_.GET_STAGE_REQUESTS,e),a(this,Bo)<e.length&&e.length>0&&this.stage.emit("newStageRequest",{count:e.length}),g(this,Bo,e.length),this.stage.emit("stageAccessRequestUpdate",e)})}getCurrentStageRequests(){return a(this,ys).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,vt).setValue("stageStatus",t)}selfStageStatusHandler(t){const e=$h(t.stageType),r=a(this,vt).getValue("stageStatus");if(r!==e)switch(t.stageType){case 1:a(this,vt).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,vt).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}async peerStageStatusHandler(t){const e=a(this,ys).joined.get(t.peerId),r=a(this,ys).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,vt).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:a(this,ys).viewMode,page:a(this,ys).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,vt).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:a(this,ys).viewMode,page:a(this,ys).currentPage});break}a(this,vt).getValue("peerSessionStore").emit(_.UPDATE_PEER_STAGE_STATUS,{id:e.id,status:e.stageStatus})}}Yr=new WeakMap,ys=new WeakMap,Qr=new WeakMap,Bo=new WeakMap,vt=new WeakMap,GO([y.trace("Stage.setupEvents")],iS.prototype,"setupEvents",1);var WO=Object.defineProperty,JO=Object.getOwnPropertyDescriptor,Bh=(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&&WO(t,e,i),i};let mo=(vv=class extends In{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,Fi,void 0);m(this,mr,void 0);m(this,Fo,void 0);m(this,Ho,void 0);m(this,Hi,void 0);p(this,"active");p(this,"enabledBy");g(this,Fo,t);const o=t.getValue("meetingId");this.id=`${o}:${e.id}`,this.name=e.name,this.icon=e.icon,g(this,Ho,e.component),this.permissions=e.permissions,g(this,Fi,i),g(this,mr,r),this.active=!1,this.enabledBy=""}get component(){return a(this,Ho)}get telemetry(){return a(this,Fo).getValue("telemetry")}set activePluginsStore(t){g(this,mr,t)}activateForSelf(){g(this,Hi,new Date),this.active=!0,this.emit("stateUpdate",{active:this.active,pluginId:this.id}),this.emit("enabled")}deactivateForSelf(){g(this,Hi,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,mr))throw new P("Cannot activate plugin: active plugins store is not available yet.","0604");await a(this,mr).set(this.id,{name:this.name,icon:this.icon,id:this.id,enabledBy:a(this,Fi).id}),this.enabledBy=a(this,Fi).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,Fi).id)return;if(!a(this,mr))throw new P("Cannot deactivate plugin: active plugins store is not available yet.","0604");const t=a(this,Hi)?new Date().getTime()-a(this,Hi).getTime():0;await a(this,mr).set(this.id,null),this.deactivateForSelf(),this.logger.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:t}})}},Fi=new WeakMap,mr=new WeakMap,Fo=new WeakMap,Ho=new WeakMap,Hi=new WeakMap,vv);Bh([y.trace("Plugin.activatePlugin")],mo.prototype,"activate",1),Bh([y.trace("Plugin.deactivatePlugin")],mo.prototype,"deactivate",1),mo=Bh([ct("0600")],mo);class nS extends Map{constructor(e,r=void 0){const{onAddEvent:i,onDeleteEvent:n,onClearEvent:o}=e;super();m(this,Ue,void 0);m(this,qi,void 0);p(this,"onAddEvent");p(this,"onDeleteEvent");p(this,"onClearEvent");g(this,Ue,new In(r)),this.onAddEvent=i,this.onDeleteEvent=n,this.onClearEvent=o,g(this,qi,new Map)}emit(e,...r){return a(this,Ue).emit(e,...r)}on(e,r){return a(this,Ue).on(e,r)}addListener(e,r){return a(this,Ue).addListener(e,r)}off(e,r){return a(this,Ue).off(e,r)}once(e,r){return a(this,Ue).once(e,r)}prependListener(e,r){return a(this,Ue).prependListener(e,r)}prependOnceListener(e,r){return a(this,Ue).prependOnceListener(e,r)}removeListener(e,r){return a(this,Ue).removeListener(e,r)}removeAllListeners(e){return a(this,Ue).removeAllListeners(e)}listeners(e){return a(this,Ue).listeners(e)}listenerCount(e){return a(this,Ue).listenerCount(e)}getMaxListeners(){return a(this,Ue).getMaxListeners()}setMaxListeners(e){return a(this,Ue).setMaxListeners(e)}eventNames(){return a(this,Ue).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,qi).set(e,o),r.on("*",o),i&&a(this,Ue).emit(this.onAddEvent,r),n}delete(e,r=!0,i=!1){const n=this.get(e);if(!n)return!1;n.removeListener("*",a(this,qi).get(e));const o=super.delete(e);return i&&n.removeAllListeners(),r&&a(this,Ue).emit(this.onDeleteEvent,n),o}clear(e=!0,r=!1){this.forEach(n=>{n.removeListener("*",a(this,qi).get(n.id)),r&&n.removeAllListeners()});const i=super.clear();return e&&a(this,Ue).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}Ue=new WeakMap,qi=new WeakMap;class aS extends nS{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 KO=Object.defineProperty,zO=Object.getOwnPropertyDescriptor,YO=(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&&KO(t,e,i),i};let Fh=class{constructor(s){p(this,"all");p(this,"active");this.all=new aS(s),this.active=new aS(s)}};Fh=YO([ct("0600")],Fh);var QO=Object.defineProperty,XO=Object.getOwnPropertyDescriptor,ZO=(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};const oS=(Tv=class{constructor(s,t,e,r){m(this,Dl);m(this,qo);m(this,jo);m(this,Go);p(this,"plugins");m(this,Es,void 0);m(this,ra,void 0);m(this,Xr,void 0);m(this,ji,null);g(this,Xr,s),this.plugins=t,g(this,ra,e),g(this,Es,r),this.setupEvents()}get telemetry(){return a(this,Xr).getValue("telemetry")}get logger(){return a(this,Xr).getValue("logger")}static async init(s,t,e,r){var l,u;const i=s.getValue("logger"),n=s.getValue("connectionHandler"),o=new Fh(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 f=new mo(s,h,c,e);o.all.add(f)});const d=new oS(s,o,r,c);return c?N(l=d,Go,Cp).call(l):N(u=d,Dl,Ov).call(u),d}cleanup(){N(this,qo,_p).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,Xr).getValue("peerSessionStore").onAsync(_.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,Es)){this.logger.warn("Active plugins store not available yet on ROOM_JOINED. Sync will be performed when store is created.");return}await N(this,jo,kp).call(this),this.logger.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to sync active plugins.")})}},Es=new WeakMap,ra=new WeakMap,Xr=new WeakMap,ji=new WeakMap,Dl=new WeakSet,Ov=function(){const s=a(this,Xr).getValue("peerSessionStore"),t=async e=>{if(e.state==="connected"&&!a(this,Es))try{g(this,Es,await a(this,ra).create(dh,!0)),N(this,qo,_p).call(this),this.plugins.all.toArray().forEach(r=>{r.activePluginsStore=a(this,Es)}),N(this,Go,Cp).call(this),this.logger.info("Active plugins store created after socket connected"),await N(this,jo,kp).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(_.SOCKET_STATE_UPDATE,t),g(this,ji,()=>{s.off(_.SOCKET_STATE_UPDATE,t)})},qo=new WeakSet,_p=function(){a(this,ji)&&(a(this,ji).call(this),g(this,ji,null))},jo=new WeakSet,kp=async function(){try{await a(this,ra).refresh(a(this,Es).name)}catch(t){this.logger.error("Failed to refresh active plugins store, syncing from stale data.",{error:t})}const s=a(this,Es).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())})},Go=new WeakSet,Cp=function(){a(this,Es).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())})})},Tv);let cS=oS;ZO([y.trace("PluginController.setupEvents")],cS.prototype,"setupEvents",1);class eD{constructor(t){p(this,"mediaJoined");p(this,"socketJoined");p(this,"socketJoinAttempted");p(this,"mediaJoinAttempted");p(this,"socketState");p(this,"mediaState");m(this,Wo,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},g(this,Wo,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,Wo).getValue("peerSessionStore").emit(_.SOCKET_STATE_UPDATE,r))}}Wo=new WeakMap;var tD=Object.defineProperty,sD=Object.getOwnPropertyDescriptor,go=(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 dS="Cannot start recording: another recording is already in progress.";let Ci=(yv=class extends Nt{constructor(t,e){const r=t.getValue("logger");super(r);m(this,aa);m(this,ia,void 0);m(this,na,void 0);p(this,"recordingPeerIds",[]);p(this,"recordings",[]);g(this,na,t),g(this,ia,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,na).getValue("telemetry")}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}async start(t){if(!a(this,ia).permissions.canRecord)throw this.logger.error("Recording::start::permission_denied"),new P("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 P(dS,"1005");try{const e=Vt(),{recording:r={}}=a(this,na).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 el&&e.status===409?new P(dS,"1005"):new P("Error while starting recording","1000",this.logger)}}async stop(t){await N(this,aa,Au).call(this,"stop",["RECORDING","PAUSED"],t)}async pause(t){await N(this,aa,Au).call(this,"pause",["RECORDING"],t)}async resume(t){await N(this,aa,Au).call(this,"resume",["PAUSED"],t)}},ia=new WeakMap,na=new WeakMap,aa=new WeakSet,Au=async function(t,e,r){if(!a(this,ia).permissions.canRecord)throw this.logger.error("Recording::stop::permission_denied"),new P("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 P("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 Vt().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 P("Error while stopping recording","1000",this.logger)}})},yv);go([y.trace("Recording.start")],Ci.prototype,"start",1),go([y.trace("Recording.stop")],Ci.prototype,"stop",1),go([y.trace("Recording.stop")],Ci.prototype,"pause",1),go([y.trace("Recording.stop")],Ci.prototype,"resume",1),Ci=go([ct("1000")],Ci);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};class lS{constructor(t,e,r){p(this,"recording");p(this,"room");m(this,Gi,void 0);g(this,Gi,t),this.recording=new Ci(t,e),this.room=r,this.setupEvents()}get telemetry(){return a(this,Gi).getValue("telemetry")}get logger(){return a(this,Gi).getValue("logger")}getRecordingTypeFromProtoType(t){let e;switch(t){case _i.BROWSER:e="BROWSER";break;case _i.COMPOSITE:e="COMPOSITE";break;case _i.TRACK:e="TRACK";break;default:e="BROWSER"}return e}setupEvents(){a(this,Gi).getValue("peerSessionStore").on(_.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($.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($.recordingPaused,t=>{const e=[...this.recording.recordings];e.forEach(r=>{r.id===t.recordingId&&(r.state="PAUSED")}),this.recording.updateRecordings(e)}),this.room.on($.recordingStopped,t=>{const e=[...this.recording.recordings.filter(r=>r.id!==t.recordingId)];this.recording.updateRecordings(e)})}}Gi=new WeakMap,nD([y.trace("RecordingController.setupEvents")],lS.prototype,"setupEvents",1);class aD{constructor(t){m(this,Wi,void 0);g(this,Wi,t)}hasFeature(t){return a(this,Wi).getValue("logger").warn("Unimplemented method: meeting.__internals__.hasFeature called"),!1}getFeatureValue(t){return a(this,Wi).getValue("logger").warn("Unimplemented method: meeting.__internals__.getFeatureValue called"),null}getAllFeatures(){return a(this,Wi).getValue("logger").warn("Unimplemented method: meeting.__internals__.getAllFeatures called"),{}}}Wi=new WeakMap;class Hh{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=ye,this.callStats=i}static init(t){return new Hh(t.getValue("authToken"),t.getValue("logger"),new aD(t),t.getValue("callstats"))}}class qh{constructor(t){p(this,"internals");this.internals=t}static async init(t){const e=Hh.init(t);return new qh(e)}}var oD=Object.defineProperty,cD=Object.getOwnPropertyDescriptor,Ut=(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};class Ct extends In{constructor(e,r,i=rl,n=!0){const o=e.getValue("logger");super(o);m(this,He,void 0);m(this,be,void 0);m(this,ve,void 0);m(this,gr,void 0);m(this,ns,void 0);m(this,Jo,void 0);m(this,De,void 0);p(this,"audioUpdateInProgress");p(this,"videoUpdateInProgress");g(this,De,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,g(this,He,new SS(e,r)),g(this,be,new xD(e,a(this,He),void 0,i)),g(this,ve,new jD(e,a(this,He),void 0,i)),g(this,ns,new FD(a(this,De),a(this,He))),g(this,gr,new $D(e,a(this,He))),g(this,Jo,n),a(this,be).on("trackMuted",this.onAudioTrackMuted.bind(this)),a(this,be).on("trackChanged",this.onAudioTrackChanged.bind(this)),a(this,ve).on("trackChanged",this.onVideoTrackChanged.bind(this)),a(this,ve).on("trackEnded",this.onVideoTrackEnded.bind(this)),a(this,ns).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}get telemetry(){return a(this,De).getValue("telemetry")}set context(e){g(this,De,e)}async onVisibilityChange(){a(this,De).getValue("callstats").tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?a(this,De).getValue("callstats").browserBackgrounded():(a(this,De).getValue("callstats").browserForegrounded(),await this.setupSpeaker())}async repopulateAvailableDevices(){return!0}async setupStreams({audio:e,video:r}){var o;e?a(this,De).getValue("callstats").audioOn():a(this,De).getValue("callstats").audioOff(),r?a(this,De).getValue("callstats").videoOn():a(this,De).getValue("callstats").videoOff();let i,n;if(e&&r)try{const c=await a(this,He).getAudioAndVideoTrack(a(this,be).userSelectedDevice,a(this,ve).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,He).getAudioTrack(!1,a(this,be).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!n&&r)try{n=await a(this,He).getVideoTrack(a(this,ve).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get video track",{error:c})}e&&!i&&a(this,De).getValue("callstats").audioOff(),r&&!n&&a(this,De).getValue("callstats").videoOff(),await a(this,be).setMediaTrack(i),await a(this,ve).setMediaTrack(n);try{await this.setupSpeaker()}catch(c){}if(n){const c=await this.getDeviceById(n.getSettings().deviceId);a(this,De).getValue("callstats").selectedDevice("VIDEO",c)}if(i){const c=await this.getDeviceById(i.getSettings().deviceId);a(this,De).getValue("callstats").selectedDevice("AUDIO",c)}(o=a(this,gr).currentDevice)!=null&&o.deviceId&&a(this,De).getValue("callstats").selectedDevice("SPEAKER",a(this,gr).currentDevice),a(this,He).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})}getCurrentDevices(){return{audio:a(this,be).currentDevice,video:a(this,ve).currentDevice,speaker:a(this,gr).currentDevice}}get permissions(){return a(this,He).permissions}getAllDevices(){return a(this,He).getAvailableDevices()}getDeviceById(e,r){return a(this,He).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return a(this,be).mediaTrack}get audioTrack(){return a(this,be).transformedMediaTrack}get audioEnabled(){return a(this,be).trackEnabled}async enableAudio(e){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{e?await a(this,be).enableTrack(!1,e):await a(this,be).unmuteTrack()}catch(r){}finally{this.audioUpdateInProgress=!1}}}disableAudio(){a(this,be).mediaTrack&&!a(this,be).isCustomTrack?a(this,be).muteTrack():a(this,be).disableTrack()}getAudioDevices(e){return a(this,He).getAudioInputDevices(e)}async setAudioDevice(e,{saveDevicePreference:r}){await a(this,be).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,De).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,gr).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,gr).setupSpeaker(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,De).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,ve).mediaTrack}get videoTrack(){return a(this,ve).transformedMediaTrack}get videoEnabled(){return a(this,ve).trackEnabled}async enableVideo(e){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{e?await a(this,ve).enableTrack(!1,e):await a(this,ve).unmuteTrack()}catch(r){}finally{this.videoUpdateInProgress=!1}}}disableVideo(){a(this,ve).disableTrack()}getVideoDevices(e){return a(this,He).getVideoInputDevices(e)}async setVideoDevice(e,{saveDevicePreference:r}){await a(this,ve).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,De).getValue("callstats").selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async updateVideoConstraints(e){await a(this,ve).updateConstraints(e)}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:a(this,ns).audioMediaTrack,video:a(this,ns).videoMediaTrack}}get screenShareEnabled(){return a(this,ns).trackEnabled}async enableScreenShare(){await a(this,ns).enableScreenShare()}async disableScreenShare(){a(this,ns).disableScreenShare()}async updateScreenshareConstraints(e){await a(this,ns).updateConstraints(e)}getSpeakerDevices(e){return a(this,He).getAudioOutputDevices(e)}addAudioMiddleware(e){return a(this,be).addMiddleware(e)}removeAudioMiddleware(e){return a(this,be).removeMiddleware(e)}removeAllAudioMiddlewares(){return a(this,be).removeAllMiddlewares()}addVideoMiddleware(e){return a(this,ve).addMiddleware(e)}removeVideoMiddleware(e){return a(this,ve).removeMiddleware(e)}removeAllVideoMiddlewares(){return a(this,ve).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return a(this,ve).setVideoMiddlewareGlobalConfig(e)}destruct(){a(this,be).disableTrack(),a(this,ve).disableTrack(),a(this,ve).terminateMiddlewareWebWorker(),a(this,ns).disableScreenShare(),a(this,He).destruct()}async onDeviceChange(e,r){var n,o;if(this.emit("DEVICE_LIST_UPDATED",e),r||!a(this,Jo))return;let i=!1;(n=e==null?void 0:e.added)==null||n.reverse().forEach(async c=>{var d;c&&!rl(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,be).disableTrack()}removeVideoTrack(){a(this,ve).disableTrack(),a(this,ve).terminateMiddlewareWebWorker()}async removeDocumentEventListeners(){document.removeEventListener("visibilitychange",this.onVisibilityChange)}}He=new WeakMap,be=new WeakMap,ve=new WeakMap,gr=new WeakMap,ns=new WeakMap,Jo=new WeakMap,De=new WeakMap,Ut([y.trace("MediaHandler.setupStreams")],Ct.prototype,"setupStreams",1),Ut([y.trace("MediaHandler.enableAudio")],Ct.prototype,"enableAudio",1),Ut([y.trace("MediaHandler.disableAudio")],Ct.prototype,"disableAudio",1),Ut([y.trace("MediaHandler.setAudioDevice")],Ct.prototype,"setAudioDevice",1),Ut([y.trace("MediaHandler.enableVideo")],Ct.prototype,"enableVideo",1),Ut([y.trace("MediaHandler.disableVideo")],Ct.prototype,"disableVideo",1),Ut([y.trace("MediaHandler.setVideoDevice")],Ct.prototype,"setVideoDevice",1),Ut([y.trace("MediaHandler.updateVideoConstraints")],Ct.prototype,"updateVideoConstraints",1),Ut([y.trace("MediaHandler.enableScreenShare")],Ct.prototype,"enableScreenShare",1),Ut([y.trace("MediaHandler.disableScreenShare")],Ct.prototype,"disableScreenShare",1),Ut([y.trace("MediaHandler.updateScreenshareConstraints")],Ct.prototype,"updateScreenshareConstraints",1),Ut([y.trace("MediaHandler.destruct")],Ct.prototype,"destruct",1),Ut([y.trace("MediaHandler.onDeviceChange")],Ct.prototype,"onDeviceChange",1);function sl(s,t,e){switch(!0){case ye.isChromiumBased():switch(t){case"NotAllowedError":return e.includes("by system")?"SYSTEM_DENIED":s==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case ye.isSafari():switch(t){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case ye.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 dD=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function rl(s){var e,r;const t=(e=s.label)==null?void 0:e.toLowerCase();return((r=ye._bowser)==null?void 0:r.getOSName())==="macOS"&&t.includes("iphone")?!0:dD.some(i=>t==null?void 0:t.includes(i))}async function lD(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 uD=s=>(t,e)=>(s.set(t,e),e),uS=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,hS=536870912,pS=hS*2,hD=(s,t)=>e=>{const r=t.get(e);let i=r===void 0?e.size:r<pS?r+1:0;if(!e.has(i))return s(e,i);if(e.size<hS){for(;e.has(i);)i=Math.floor(Math.random()*pS);return s(e,i)}if(e.size>uS)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()*uS);return s(e,i)},mS=new WeakMap,pD=uD(mS),il=hD(pD,mS),mD=s=>s.method!==void 0&&s.method==="call",gD=s=>s.error===null&&typeof s.id=="number",nl=((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(mD(l)){const{params:{timerId:u,timerType:h}}=l;if(h==="interval"){const f=t.get(u);if(typeof f=="number"){const S=r.get(f);if(S===void 0||S.timerId!==u||S.timerType!==h)throw new Error("The timer is in an undefined state.")}else if(typeof f!="undefined")f();else throw new Error("The timer is in an undefined state.")}else if(h==="timeout"){const f=e.get(u);if(typeof f=="number"){const S=r.get(f);if(S===void 0||S.timerId!==u||S.timerType!==h)throw new Error("The timer is in an undefined state.")}else if(typeof f!="undefined")f(),e.delete(u);else throw new Error("The timer is in an undefined state.")}}else if(gD(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:f,timerType:S}=h;r.delete(u),S==="interval"?t.delete(f):e.delete(f)}else{const{error:{message:u}}=l;throw new Error(u)}}),{clearInterval:l=>{const u=il(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=il(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=il(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=il(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})}}))})();`),gS=s=>nl().clearInterval(s),fD=s=>nl().clearTimeout(s),fS=(s,t)=>nl().setInterval(s,t),jh=Object.freeze(Object.defineProperty({__proto__:null,clearInterval:gS,clearTimeout:fD,setInterval:fS,setTimeout:(s,t)=>nl().setTimeout(s,t)},Symbol.toStringTag,{value:"Module"}));class SD{constructor(t){m(this,Ji,void 0);m(this,Ko,void 0);g(this,Ko,t)}get logger(){return a(this,Ko).getValue("logger")}terminateMiddlewareWebWorker(){if(a(this,Ji))try{gS(a(this,Ji)),g(this,Ji,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(f=>f({canvas:i,WorkerTimers:jh})));if(r.disablePerFrameCanvasRendering){const S=i.captureStream().getVideoTracks()[0];return Object.defineProperty(S,"originalSettings",{value:e.getSettings()}),S}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 f=0;f<n.length;f+=1)typeof n[f]=="function"&&await n[f](i,d)}catch(f){this.logger.error("getTransformedVideoTrack::middleware_execution_failed",{error:f})}};try{o.play()}catch(f){}o.addEventListener("play",()=>{i.width=o.width||e.getSettings().width,i.height=o.width||e.getSettings().height,g(this,Ji,fS(l,50))},!1);const h=i.captureStream().getVideoTracks()[0];return Object.defineProperty(h,"originalSettings",{value:e.getSettings()}),h}}Ji=new WeakMap,Ko=new WeakMap;const vD={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}}},TD=[[320,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2}]],[640,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2}]],[1280,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]],[1920,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]],[3840,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]]],yD=(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=TD,n=i.map(([h])=>h).sort((h,f)=>h-f);let o=Number.MAX_VALUE,c=0;return n.forEach((h,f)=>{Math.abs(h-r)<o&&(o=Math.abs(h-r),c=f)}),i[c][1]};var Ie=(s=>(s.WEBCAM="webcam",s.WEBCAM_BACKUP="webcam_backup",s.MIC="mic",s.SCREENSHARE_VIDEO="screenshare_video",s.SCREENSHARE_AUDIO="screenshare_audio",s))(Ie||{});const ED=Ak(),xn=Ms(ED.config.media);function bD(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 wD{constructor(t,e){m(this,Ki,void 0);m(this,Nl,void 0);p(this,"getScreenShareConstraints",()=>{var l,u,h,f,S,E,k,I,R;const t=(l=a(this,Ki))==null?void 0:l.screenshare,e=(h=(u=t==null?void 0:t.width)==null?void 0:u.max)!=null?h:1920,r=(S=(f=t==null?void 0:t.height)==null?void 0:f.max)!=null?S:1080,i=(k=(E=t==null?void 0:t.frameRate)==null?void 0:E.max)!=null?k:5,n=(R=(I=t==null?void 0:t.frameRate)==null?void 0:I.ideal)!=null?R: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,Ki))==null?void 0:n.audio,i=r!=null&&r.enableStereo?2:1;return ye.isFirefox()||ye.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,Ki))==null?void 0:o.video,i=WP(vD);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});g(this,Nl,t),g(this,Ki,e)}getUpdatedVideoConstraints(t){return t}}Ki=new WeakMap,Nl=new WeakMap;class Gh extends Error{constructor(e,r,i){super(r);p(this,"constraints");p(this,"name");this.name=e,this.constraints=i}}class PD{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 _D=Object.defineProperty,kD=Object.getOwnPropertyDescriptor,Ss=(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&&_D(t,e,i),i};let $t=(Ev=class extends PD{constructor(t,e){super();m(this,oa,void 0);m(this,as,void 0);m(this,ze,void 0);g(this,ze,t),g(this,as,new wD(t,e)),g(this,oa,new AbortController)}get telemetry(){return a(this,ze).getValue("telemetry")}get logger(){return a(this,ze).getValue("logger")}get constraintsBuilder(){return a(this,as)}async destruct(){var t;(t=a(this,oa))==null||t.abort()}handlePermissionErrors(t,e){const r=sl(t,e.name,e.message);return this.permissions[t]=r,a(this,ze).getValue("peerSessionStore").emit(_.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(R=>R.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(R=>R.deviceId===e));let f;e&&h?f=e:d&&((n=d[0])!=null&&n.deviceId)&&(f=(o=d[0])==null?void 0:o.deviceId);const S={audio:a(this,as).getAudioConstraints(u).audio,video:a(this,as).getVideoConstraints(f).video};this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(S)});const E=await navigator.mediaDevices.getUserMedia(S);this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(S)});const k=E.getAudioTracks()[0];let I=E.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",I.label.includes("OBS Virtual")){const U=(await this.getVideoInputDevices()).find(D=>D.label.includes("OBS Virtual"));I=await this.getVideoTrack(U.deviceId)}return a(this,ze).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),a(this,ze).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:k,videoTrack:I}}catch(c){throw this.logger.error("WebMediaInterface.getAudioAndVideoTrack",{error:c}),new P("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,ze).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new P("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(f=>f.deviceId!==l),u=a(this,as).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 f=sl("audio",h.name,h.message),S=new Gh(h.name,h.message,u);if(f==="COULD_NOT_START"){const E=r.shift();if(!E)throw S;this.logger.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(u),error:h});const k=a(this,as).getAudioConstraints(E.deviceId);return this.logger.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(k)}),o(E.deviceId)}throw S}};try{const l=await o(n);return l.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",a(this,ze).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),l}catch(l){throw l.constraints&&this.handlePermissionErrors("audio",l),new P(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,ze).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new P("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:f}=h;e&&typeof f!="boolean"&&(h={video:{deviceId:f.deviceId}}),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(h)});const[S]=(await navigator.mediaDevices.getUserMedia(h)).getVideoTracks();if(e&&typeof f!="boolean"&&typeof f.width=="object"){const{width:E,height:k}=S.getSettings(),{ideal:I}=f.width;S.applyConstraints({width:{ideal:I},height:{ideal:Math.floor(k*I/E)},frameRate:f.frameRate})}return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(h)}),S}catch(h){const f=sl("video",h.name,h.message),S=new Gh(h.name,h.message,u);if(f==="COULD_NOT_START"){const E=r.shift();if(!E)throw S;this.logger.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(u),error:h});const k=a(this,as).getVideoConstraints(E.deviceId);return this.logger.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(k)}),o({video:k.video})}throw S}};try{const u=a(this,as).getVideoConstraints(n),h=await o(u);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",a(this,ze).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),h}catch(u){throw u.constraints&&this.handlePermissionErrors("video",u),new P(u.message,"1602")}}async getScreenShareTracks(){const t=async e=>{try{this.logger.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),a(this,ze).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 Gh(r.name,r.message,e),o={video:!0};if(ek(e,o))throw n;if(i==="COULD_NOT_START")return t(o);throw n}};try{const e=a(this,as).getScreenShareConstraints(),r=await t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",a(this,ze).getValue("peerSessionStore").emit(_.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 P(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 rl(i)?4:n.includes("airpods")||n.includes("airdopes")||n.includes("bluetooth")||n.includes("wireless")||n.includes("headphones")||n.includes("headset")||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 f=r(i),S=r(n);if(f&&!S)return-1;if(!f&&S)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 P("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 P("Failed to get device","1609")}}async onDeviceChange(t){if(ye.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(f=>f.kind==="audioinput")&&a(this,ze).getValue("callstats").devices("AUDIO",o==null?void 0:o.filter(f=>f.kind==="audioinput")),h.some(f=>f.kind==="videoinput")&&a(this,ze).getValue("callstats").devices("VIDEO",o==null?void 0:o.filter(f=>f.kind==="videoinput")),h.some(f=>f.kind==="audiooutput")&&a(this,ze).getValue("callstats").devices("SPEAKER",o==null?void 0:o.filter(f=>f.kind==="audiooutput")),t(r,d,!1)}},{signal:a(this,oa).signal})}}},oa=new WeakMap,as=new WeakMap,ze=new WeakMap,Ev);Ss([y.trace("WebMediaInterface.destruct")],$t.prototype,"destruct",1),Ss([y.trace("WebMediaInterface.handlePermissionErrors")],$t.prototype,"handlePermissionErrors",1),Ss([y.trace("WebMediaInterface.getAudioAndVideoTrack")],$t.prototype,"getAudioAndVideoTrack",1),Ss([y.trace("WebMediaInterface.getAudioTrack")],$t.prototype,"getAudioTrack",1),Ss([y.trace("WebMediaInterface.getVideoTrack")],$t.prototype,"getVideoTrack",1),Ss([y.trace("WebMediaInterface.getScreenShareTracks")],$t.prototype,"getScreenShareTracks",1),Ss([y.trace("WebMediaInterface.getAvailableDevices")],$t.prototype,"getAvailableDevices",1),Ss([y.trace("WebMediaInterface.getAvailableDevicesByKind")],$t.prototype,"getAvailableDevicesByKind",1),Ss([y.trace("WebMediaInterface.getDevice")],$t.prototype,"getDevice",1),Ss([y.trace("WebMediaInterface.onDeviceChange")],$t.prototype,"onDeviceChange",1),$t=Ss([ct("1600")],$t);const SS=$t,Ri={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}},CD=(s=0)=>new Promise(t=>setTimeout(t,s)),RD=(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):CD().then(d))}return d().then(l=>(i.disconnect(),l),l=>{throw i.disconnect(),l})},ID=typeof AudioContext!="undefined"?AudioContext:null;class Wh{constructor(t){p(this,"_AudioContext");p(this,"audioContext");p(this,"_audioContextRefContainers");const e={AudioContext:ID,...t};Object.defineProperties(this,{_AudioContext:{value:e.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:Wh}})}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 vS=new Wh,AD=3,MD=250;function OD(s){const t={},e=vS.getOrCreate(t);let r=AD;function i(){return r-=1,RD(e,s.srcObject,MD).then(n=>n?r>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{vS.release(t)})}async function TS(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 OD(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 DD=Object.defineProperty,ND=Object.getOwnPropertyDescriptor,yS=(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&&DD(t,e,i),i};let al=class extends In{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=>Ri.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>Ri.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 P("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 P("No device received!","1603");this.userSelectedDevice=t.deviceId,e&&this.setUserPreferredDevice(t.deviceId),await this.onSetDevice(t)}async addMiddleware(t){if(ye.isWebKitBased()&&!(ye.isSafari()&&mk.test(ye.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))}};yS([y.trace("BaseMediaHandler.unmuteTrack")],al.prototype,"unmuteTrack",1),al=yS([ct("1600")],al);const ES=al;var LD=Object.defineProperty,VD=Object.getOwnPropertyDescriptor,Jh=(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&&LD(t,e,i),i};const Kh="[Realtimekit]nonSilentDeviceLabels";class ol extends ES{async onSetDevice(t){if(!t)throw this.logger.warn("AudioMediaHandler.setDevice No device received"),new P("No device received!","1603");if(t.kind!=="audioinput")throw this.logger.warn("AudioMediaHandler.setDevice Received non audio device"),new P("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 P(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 lD(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(Ri.getItem(Kh,this.logger));if(o!=null&&o.devices.some(l=>l.label===r.label))return r;if(!await TS(this.logger,r)){const l=(d=o==null?void 0:o.devices.concat({label:r.label}))!=null?d:[{label:r.label}];return Ri.setItem(Kh,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 TS(this.logger,r)){const h=(u=o==null?void 0:o.devices.concat({label:r.label}))!=null?u:[{label:r.label}];return Ri.setItem(Kh,JSON.stringify({devices:h}),this.logger),this.logger.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return this.logger.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1}),r}}Jh([y.trace("AudioMediaHandler.setTransformedTrack")],ol.prototype,"setTransformedTrack",1),Jh([y.trace("AudioMediaHandler.onTrackEnded")],ol.prototype,"onTrackEnded",1),Jh([y.trace("AudioMediaHandler.conditionallyChangeTrack")],ol.prototype,"conditionallyChangeTrack",1);const xD=ol;class UD{constructor(t,e){m(this,zi,void 0);p(this,"currentDevice");p(this,"userPreferredDeviceKey","Realtimekit::speaker::UserDeviceID");p(this,"logger");p(this,"setUserPreferredDevice",t=>Ri.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>Ri.getItem(this.userPreferredDeviceKey,this.logger));g(this,zi,e),this.logger=t.getValue("logger")}async setPreferredSpeaker(){const t=this.getUserPreferredDevice(),e=await a(this,zi).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,zi)instanceof SS))return;let r=t;if(t||([r]=(await a(this,zi).getAvailableDevicesByKind("audiooutput")).filter(d=>!rl(d))),!r)throw new P("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){}})}}zi=new WeakMap;const $D=UD;class BD extends In{constructor(e,r){const i=e.getValue("logger");super(i);p(this,"mediaInterface");p(this,"audioMediaTrack");p(this,"videoMediaTrack");m(this,zo,void 0);g(this,zo,e),this.mediaInterface=r}get trackEnabled(){return!!this.videoMediaTrack}async enableScreenShare(){var e,r;try{const{audioTrack:i,videoTrack:n}=await this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=i,this.videoMediaTrack=n,this.addMediaTrackListeners(),((r=(e=this.mediaInterface)==null?void 0:e.permissions)==null?void 0:r.screenshare)==="ACCEPTED")return;this.mediaInterface.permissions&&(this.mediaInterface.permissions.screenshare="ACCEPTED",a(this,zo).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch(i){}}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}async updateConstraints(e){if(!this.videoMediaTrack)throw new P("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new P("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.bind(this)),ye.isWebKitBased()&&((r=this.videoMediaTrack)==null||r.addEventListener("mute",this.onTrackEnded.bind(this)))}removeMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded),(r=this.videoMediaTrack)==null||r.removeEventListener("mute",this.onTrackEnded)}onTrackEnded(){this.emit("trackEnded")}}zo=new WeakMap;const FD=BD;var HD=Object.defineProperty,qD=Object.getOwnPropertyDescriptor,cl=(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 fo extends ES{constructor(e,r,i,n){super(e,r,i,n);m(this,ca,void 0);m(this,Yo,{disablePerFrameCanvasRendering:!1});g(this,ca,new SD(e))}async onSetDevice(e){if(!e)throw this.logger.warn("VideoMediaHandler.setDevice No device received"),new P("No device received!","1603");if(e.kind!=="videoinput")throw this.logger.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new P("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 P("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,ca).getTransformedVideoTrack(this.middlewares,this.mediaTrack,a(this,Yo)),this.emit("trackChanged")}catch(i){this.logger.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}}async setVideoMiddlewareGlobalConfig(e){g(this,Yo,e)}async updateConstraints(e){if(!this._mediaTrack)throw new P("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new P("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,ca).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}}ca=new WeakMap,Yo=new WeakMap,cl([y.trace("VideoMediaHandler.setTransformedTrack")],fo.prototype,"setTransformedTrack",1),cl([y.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],fo.prototype,"setVideoMiddlewareGlobalConfig",1),cl([y.trace("VideoMediaHandler.onTrackEnded")],fo.prototype,"onTrackEnded",1),cl([y.trace("VideoMediaHandler.conditionallyChangeTrack")],fo.prototype,"conditionallyChangeTrack",1);const jD=fo,bS=Ms(lh()),la=class{constructor(t){m(this,Tt,void 0);m(this,Yi,void 0);m(this,Qo,void 0);m(this,da,void 0);if(!t)throw new P("Could not load preset.","0904");g(this,Tt,t.config),g(this,Qo,t.name),g(this,Yi,t.ui||Ms(lh().ui)),g(this,da,t.permissions.plugins.config)}static fromResponse(t){return new la(t)}static default(){return new la(bS)}static init(t,e=!0){return!t||e?new la(bS):new la(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,Yi).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return a(this,Tt).viewType}get livestreamViewerQualities(){return a(this,Tt).livestreamViewerQualities||[]}get maxVideoStreams(){return a(this,Tt).maxVideoStreams}get maxScreenShareCount(){return a(this,Tt).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(a(this,da)).filter(t=>a(this,da)[t].disabled)}get designTokens(){return a(this,Yi).designTokens}get configDiff(){return a(this,Yi).configDiff}get isSimulcastEnabled(){var t,e,r,i;return(i=(r=(e=(t=a(this,Tt))==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,f,S,E,k,I,R,U,D,x,B,q,Z,se;return{audio:{enableStereo:(i=(r=(e=(t=a(this,Tt))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?i:xn.audio.enableStereo,enableHighBitrate:(d=(c=(o=(n=a(this,Tt))==null?void 0:n.media)==null?void 0:o.audio)==null?void 0:c.enableHighBitrate)!=null?d:xn.audio.enableHighBitrate},video:{quality:(f=(h=(u=(l=a(this,Tt))==null?void 0:l.media)==null?void 0:u.video)==null?void 0:h.quality)!=null?f:xn.video.quality,frameRate:(I=(k=(E=(S=a(this,Tt))==null?void 0:S.media)==null?void 0:E.video)==null?void 0:k.frameRate)!=null?I:xn.video.frameRate},screenshare:{quality:(x=(D=(U=(R=a(this,Tt))==null?void 0:R.media)==null?void 0:U.screenshare)==null?void 0:D.quality)!=null?x:xn.screenshare.quality,frameRate:(se=(Z=(q=(B=a(this,Tt))==null?void 0:B.media)==null?void 0:q.screenshare)==null?void 0:Z.frameRate)!=null?se:xn.screenshare.frameRate}}}get name(){return a(this,Qo)}};let zh=la;Tt=new WeakMap,Yi=new WeakMap,Qo=new WeakMap,da=new WeakMap;var GD=Object.defineProperty,WD=Object.getOwnPropertyDescriptor,wS=(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&&GD(t,e,i),i};class Yh extends Nt{constructor(e,r){const i=e.getValue("logger");super(i);m(this,ua,void 0);p(this,"state","IDLE");p(this,"playbackUrl");p(this,"ingestionCredentials");p(this,"viewerCount");m(this,Xo,void 0);g(this,ua,r),g(this,Xo,e),this.viewerCount=0}get telemetry(){return a(this,Xo).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,ua).permissions.canLivestream)throw this.logger.error("Livestream::start::permission_denied"),new P("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const r=Vt(),{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 P("Error while starting livestream","1900",this.logger)}}async stop(){if(!a(this,ua).permissions.canLivestream)throw this.logger.error("Livestream::stop::permission_denied"),new P("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 P("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),await Vt().stopLivestreaming()}catch(e){throw this.logger.error("Livestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new P("Error while stopping livestream","1900",this.logger)}}}ua=new WeakMap,Xo=new WeakMap,wS([y.trace("livestream.start")],Yh.prototype,"start",1),wS([y.trace("livestream.stop")],Yh.prototype,"stop",1);var JD=Object.defineProperty,KD=Object.getOwnPropertyDescriptor,zD=(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&&JD(t,e,i),i};class PS{constructor(t,e,r){p(this,"livestream");m(this,ha,void 0);m(this,pa,void 0);m(this,fr,void 0);m(this,Vs,void 0);g(this,Vs,t),g(this,pa,e),this.livestream=new Yh(t,e),g(this,fr,r),this.setupEvents()}get logger(){return a(this,Vs).getValue("logger")}get telemetry(){return a(this,Vs).getValue("telemetry")}async fetchInitialLivestreamingState(){const t=Vt(),{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,fr).on($.startedLivestream,async t=>{this.livestream.playbackUrl=t.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{a(this,pa).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}}),a(this,fr).on($.livestreamingInvoked,async t=>{if(t.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{a(this,pa).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}}),a(this,fr).on($.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),a(this,fr).on($.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),a(this,fr).on($.roomPeerCount,t=>{this.livestream.viewerCount=t.count,this.livestream.emit("viewerCountUpdate",t.count)}),a(this,Vs).getValue("peerSessionStore").on(_.PEER_JOINED_INTERNAL,async t=>{var e;((e=t.flags)==null?void 0:e.hiddenParticipant)===!0&&t.recorderType==="LIVESTREAMER"&&(g(this,ha,t.id),this.livestream.setLivestreamState("LIVESTREAMING"))}),a(this,Vs).getValue("peerSessionStore").on(_.PEER_CLOSED,t=>{t.id===a(this,ha)&&(g(this,ha,void 0),this.livestream.setLivestreamState("IDLE"))}),a(this,Vs).getValue("peerSessionStore").onAsync(_.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,Vs).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,async()=>{try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Error: LivestreamController.fetchLivestream")}})}}ha=new WeakMap,pa=new WeakMap,fr=new WeakMap,Vs=new WeakMap,zD([y.trace("LivestreamController.setupEvents")],PS.prototype,"setupEvents",1);var YD=Object.defineProperty,QD=Object.getOwnPropertyDescriptor,So=(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&&YD(t,e,i),i};class Un{constructor({name:t,socketHandler:e,meetingId:r}){m(this,Ll);p(this,"name","");m(this,it,{});m(this,Zr,"");m(this,ei,void 0);p(this,"rateLimitConfig",{maxInvocations:5,period:1});p(this,"bulkRateLimitConfig",{maxInvocations:5,period:1});p(this,"listeners",{});this.name=t,g(this,ei,e),g(this,Zr,r)}async set(t,e,r=!0,i=!1){a(this,it)[t]=e,r&&this.remoteSet(t,e),i&&(this.listeners[t]&&this.listeners[t].forEach(n=>n({[t]:a(this,it)[t]})),this.listeners["*"]&&this.listeners["*"].forEach(n=>n({[t]:a(this,it)[t]})))}remoteSet(t,e){a(this,ei).storeInsertKeys(a(this,Zr),this.name,[{key:t,payload:e}])}async bulkSet(t){t.forEach(({key:e,payload:r})=>{a(this,it)[e]=r}),a(this,ei).storeInsertKeys(a(this,Zr),this.name,t)}async update(t,e,r=!0){N(this,Ll,Dv).call(this,t,e,r)}async delete(t,e=!0,r=!1){if(a(this,it)[t]&&delete a(this,it)[t],e)return a(this,ei).storeDeleteKeys(a(this,Zr),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,it)[e]&&delete a(this,it)[e]}),a(this,ei).storeDeleteKeys(a(this,Zr),this.name,t)}get(t){if(a(this,it)[t])return a(this,it)[t]}getAll(){return a(this,it)}clear(){g(this,it,{})}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){g(this,it,t)}}it=new WeakMap,Zr=new WeakMap,ei=new WeakMap,Ll=new WeakSet,Dv=function(t,e,r=!0){let i;const n=a(this,it)[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)},So([xt(Ln,"rateLimitConfig")],Un.prototype,"remoteSet",1),So([xt(Ln,"bulkRateLimitConfig")],Un.prototype,"bulkSet",1),So([xt(Ln,"rateLimitConfig")],Un.prototype,"update",1),So([xt(Ln,"rateLimitConfig")],Un.prototype,"delete",1),So([xt(Ln,"bulkRateLimitConfig")],Un.prototype,"bulkDelete",1);class XD{constructor(t,e){m(this,Zo);m(this,Vl);p(this,"stores",new Map);m(this,ti,void 0);m(this,si,"");m(this,ec,void 0);m(this,bs,new Map);g(this,ti,e),g(this,si,t.getValue("meetingId")),g(this,ec,t),N(this,Vl,Nv).call(this)}create(t,e=!1){if(gk.includes(t)&&!e)throw new P(`'${t}' is a reserved store name.`,"0601");const r=new Un({name:t,socketHandler:a(this,ti),meetingId:a(this,si)});return a(this,ti).storeGetKeys(a(this,si),t,[]),new Promise((n,o)=>{const c=setTimeout(()=>{a(this,bs).delete(t),o(Error("Failed"))},3e3);a(this,bs).set(t,{rejectTimeout:c,resolve:n,store:r})})}refresh(t){const e=this.stores.get(t);return e?(e.clear(),a(this,ti).storeGetKeys(a(this,si),t,[]),new Promise((i,n)=>{const o=setTimeout(()=>{a(this,bs).delete(t),n(Error("Store refresh timed out"))},3e3);a(this,bs).set(t,{rejectTimeout:o,resolve:i,store:e})})):Promise.reject(Error(`Store '${t}' does not exist`))}}ti=new WeakMap,si=new WeakMap,Zo=new WeakSet,Rp=function(){return a(this,ec).getValue("peerId")},ec=new WeakMap,bs=new WeakMap,Vl=new WeakSet,Nv=function(){[tr.storeInsertKeys,tr.storeGetKeys,tr.storeDeleteKeys].forEach(t=>{a(this,ti).on(t,async e=>{var n,o;if(e.pluginId!==a(this,si))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===tr.storeGetKeys){const c=a(this,bs).get(e.storeName),d=this.stores.get(e.storeName)||(c==null?void 0:c.store);if(a(this,bs).get(e.storeName)&&(this.stores.set(e.storeName,c.store),c.resolve(d),clearTimeout(c.rejectTimeout),a(this,bs).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,bs).get(e.storeName))==null?void 0:o.store);i!==void 0&&(t===tr.storeInsertKeys&&r.forEach(({key:c,peerId:d,payload:l})=>{d!==a(this,Zo,Rp)&&i.set(c,l,!1,!0)}),t===tr.storeDeleteKeys&&r.forEach(({key:c,peerId:d})=>{d!==a(this,Zo,Rp)&&i.delete(c,!1,!0)}))})})};function Ii(s){var t,e,r,i,n,o,c,d,l,u,h,f,S;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:(S=(f=s.screenShareTracks)==null?void 0:f.video)==null?void 0:S.id}}}}:{}}var ZD=Object.defineProperty,e1=Object.getOwnPropertyDescriptor,$n=(s,t,e,r)=>{for(var i=r>1?void 0:r?e1(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&&ZD(t,e,i),i};const t1=.8,s1=1.2;let ar=(bv=class extends Nt{constructor(t,e,r,i){const n=t.getValue("logger");super(n);m(this,Qi);m(this,ri);m(this,Xi);m(this,xl);m(this,Zi);m(this,sc);m(this,$l);m(this,Bl);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,ma,void 0);p(this,"supportsRemoteControl",!1);m(this,ga,void 0);p(this,"presetName");m(this,Ht,void 0);m(this,Sr,void 0);m(this,tc,void 0);m(this,ii,new Map);m(this,vr,1);m(this,Ul,nh(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>s1&&a(this,vr)===1?(g(this,vr,0),a(this,Ht).getValue("peerSessionStore").emit(_.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,vr)})):d<t1&&a(this,vr)===0&&(g(this,vr,1),a(this,Ht).getValue("peerSessionStore").emit(_.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,vr)}))},2e3));g(this,Ht,t);const{id:o,userId:c,displayName:d,device:l,picture:u,isHost:h,flags:f,stageStatus:S,customParticipantId:E,audioMuted:k,audioTrack:I,videoEnabled:R=!1,videoTrack:U,producers:D,metadata:x}=e;this.id=o,this.userId=c,this.name=d,this.device=l,this.picture=u,this.isHost=h,this.flags=f,this.manualProducerConfig=ck,g(this,ga,S!=null?S:"ON_STAGE"),this.customParticipantId=E,this.audioEnabled=!k,this.audioTrack=I,this.videoEnabled=R,this.videoTrack=U,this.screenShareTracks={audio:void 0,video:void 0},this.producers=D!=null?D:[],this.presetName=x==null?void 0:x.preset_name,g(this,ma,!1),g(this,Sr,r),g(this,tc,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),N(this,sc,Ip).call(this)}get stageStatus(){return a(this,ga)}get telemetry(){return a(this,Ht).getValue("telemetry")}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(this.logger.info("Participant::setVideoEnabled::videoUpdate",{...Ii(this)}),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(this.logger.info("Participant::setAudioEnabled::audioUpdate",{...Ii(this)}),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}))}setScreenShareEnabled(t,e=!0){this.screenShareEnabled=t,e&&this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}setupEvents(){this.on("videoUpdate",N(this,sc,Ip)),a(this,ri,Ga)&&(this.on("audioUpdate",N(this,$l,Vv)),this.on("screenShareUpdate",N(this,Bl,xv)))}async pin(){if(!a(this,Xi,cd))throw new P("Can`t pin participant without joining room","1205");if(!a(this,Sr).permissions.pinParticipant)throw new P("You do not have permission to pin participants.","1201");return a(this,Qi,od).pinPeer(this.id)}async unpin(){if(!a(this,Xi,cd))throw new P("Can`t unpin participant without joining room","1205");if(!a(this,Sr).permissions.pinParticipant)throw new P("You do not have permission to unpin participants.","1201");return a(this,Qi,od).pinPeer(null)}setIsPinned(t,e=!0){var i;g(this,ma,t);const r=t?"pinned":"unpinned";(i=a(this,Zi,dd))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}async disableAudio(){const t=this.id;if(this.logger.info("Participant::disable_audio",{participant:{id:t}}),!a(this,Xi,cd))throw new P("Can`t disable participant audio without joining room","1205");if(a(this,Sr).permissions.canDisableParticipantAudio)return a(this,Qi,od).disableAudio(t);throw this.logger.error("Participant::unauthorized_disable_audio",{participant:{id:t}}),new P("Unauthorized: User does not have permission to disable participant audio.","1201")}async kick(){const t=this.id;if(this.logger.info("Participant::kick",{participant:{id:t}}),!a(this,xl,Lv))throw new P("Can`t kick participant without joining room","1205");if(a(this,Sr).permissions.kickParticipant){await a(this,Ht).getValue("peerSessionStore").emitAsync(_.KICK_PEER,{peerId:t});return}throw this.logger.error("Participant::unauthorized_kick",{participant:{id:t}}),new P("Unauthorized: User does not have permission to kick participants.","1201")}async disableVideo(){const t=this.id;if(this.logger.info("Participant::disable_video",{participant:{id:t}}),!a(this,Xi,cd))throw new P("Can`t disable participant video without joining room","1205");if(a(this,Sr).permissions.canDisableParticipantVideo)return a(this,Qi,od).disableVideo(t);throw this.logger.error("Participant::unauthorized_disable_video",{participant:{id:t}}),new P("Unauthorized: User does not have permission to disable participant video.","1201")}async getPermissions(){return a(this,tc).getUserPermissions(this.userId)}setStageStatus(t){g(this,ga,t),this.emit("stageStatusUpdate",this)}get isPinned(){return a(this,ma)}registerVideoElement(t){var r,i,n,o;if(!t)return;let e;(i=(r=a(this,ii).get(t))==null?void 0:r.observer)==null||i.disconnect(),"ResizeObserver"in window&&(e=new ResizeObserver(()=>a(this,Ul).call(this,t)),e.observe(t)),a(this,ii).set(t,{observer:e}),this.updateVideo(t),(o=a(this,Zi,dd))==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,Zi,dd))==null||e.removeSource(this.id);return}t.srcObject=void 0,(i=(r=a(this,ii).get(t))==null?void 0:r.observer)==null||i.disconnect(),a(this,ii).delete(t),(n=a(this,Zi,dd))==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"}},ma=new WeakMap,ga=new WeakMap,Ht=new WeakMap,Qi=new WeakSet,od=function(){return a(this,Ht).getValue("roomNodeClient")},ri=new WeakSet,Ga=function(){return a(this,Ht).getValue("audioPlayback")},Xi=new WeakSet,cd=function(){return a(this,Ht).getValue("connectionHandler").mediaJoined},xl=new WeakSet,Lv=function(){return a(this,Ht).getValue("connectionHandler").socketJoined},Sr=new WeakMap,tc=new WeakMap,ii=new WeakMap,Zi=new WeakSet,dd=function(){return a(this,Ht).getValue("pip")},vr=new WeakMap,Ul=new WeakMap,sc=new WeakSet,Ip=function(){Array.from(a(this,ii).keys()).forEach(this.updateVideo)},$l=new WeakSet,Vv=function(){var t,e;this.audioEnabled&&this.audioTrack?(t=a(this,ri,Ga))==null||t.addParticipantTrack(this.id,this.audioTrack):(e=a(this,ri,Ga))==null||e.removeParticipantTrack(this.id)},Bl=new WeakSet,xv=function(){var t,e;this.screenShareEnabled&&this.screenShareTracks.audio?(t=a(this,ri,Ga))==null||t.addParticipantTrack(`screenshare-${this.id}`,this.screenShareTracks.audio):(e=a(this,ri,Ga))==null||e.removeParticipantTrack(`screenshare-${this.id}`)},bv);$n([y.trace("Participant.disableAudio")],ar.prototype,"disableAudio",1),$n([y.trace("Participant.kick")],ar.prototype,"kick",1),$n([y.trace("Participant.disableVideo")],ar.prototype,"disableVideo",1),$n([y.trace("Participant.getPermissions")],ar.prototype,"getPermissions",1),$n([y.trace("Participant.setStageStatus")],ar.prototype,"setStageStatus",1),ar=$n([ct("1200")],ar);class vo extends nS{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 r1 extends In{constructor(e){super(e);m(this,ni,void 0);g(this,ni,new Map)}__set(e,r){return a(this,ni).set(e,r)}__clear(){return a(this,ni).clear()}get(e){return a(this,ni).get(e)}toArray(){return Array.from(a(this,ni).values())}}ni=new WeakMap;class i1{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 n1{constructor(){p(this,"_activeSpeakerPeers");p(this,"_compulsoryPeers");this._activeSpeakerPeers=new i1,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)}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 _S=new n1;var a1=Object.defineProperty,o1=Object.getOwnPropertyDescriptor,Ns=(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};const c1=["ACTIVE_GRID","PAGINATED","MANUAL"];let ts=(wv=class extends Nt{constructor(t,e,r){const i=t.getValue("logger");super(i);m(this,rc);m(this,en);m(this,fa);p(this,"waitlisted");p(this,"joined");p(this,"active");p(this,"videoSubscribed");p(this,"audioSubscribed");p(this,"pinned");p(this,"all");m(this,Ne,void 0);m(this,tn,void 0);m(this,It,void 0);p(this,"rateLimitConfig",{maxInvocations:5,period:1});p(this,"viewMode");p(this,"currentPage");p(this,"lastActiveSpeaker");p(this,"selectedPeers",_S);g(this,Ne,t),g(this,tn,e),g(this,It,r),this.waitlisted=new vo(i),this.joined=new vo(i),this.videoSubscribed=new vo(i),this.audioSubscribed=new vo(i),this.active=this.videoSubscribed,this.pinned=new vo(i),this.all=new r1(i),this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return a(this,Ne).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get telemetry(){return a(this,Ne).getValue("telemetry")}setupEvents(){a(this,Ne).getValue("peerSessionStore").on(_.E2EE_ACTIVE_CONSUMER,({peerId:e})=>{var r;((r=a(this,Ne).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,Ne).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,Ne))==null?void 0:t.getValue("maxPreferredStreams")}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new P("0 <= Max active participants count limit <= 24","1203");a(this,Ne).setValue("maxPreferredStreams",t),a(this,fa,Mu)&&a(this,Ne).getValue("peerSessionStore").emit(_.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,en,ld))throw new P("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,It).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,It).acceptWaitingRoomRequest(e)}async rejectWaitingRoomRequest(t){var r,i;if(!a(this,en,ld))throw new P("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,It).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=>c1.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 P(`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,Ne).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="ACTIVE_GRID"?(this.currentPage=0,a(this,Ne).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="MANUAL"&&(this.currentPage=0,a(this,Ne).getValue("peerSessionStore").emit(_.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 P("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,Ne).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}async unsubscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new P("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,Ne).getValue("peerSessionStore").emit(_.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 P(`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,Ne).getValue("peerSessionStore").emit(_.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,fa,Mu))throw new P("Can`t disable all audio without joining room","1205");if(a(this,tn).permissions.canAllowParticipantAudio)return a(this,rc,Ap).muteAll(t);throw this.logger.error("Participants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new P("Unauthorized: User does not have permission to disable peer audio.","1201")}async disableAllVideo(){if(this.logger.info("Participants::disable_all_video"),!a(this,fa,Mu))throw new P("Can`t disable all video without joining room","1205");if(a(this,tn).permissions.canAllowParticipantVideo)return a(this,rc,Ap).muteAllVideo();throw this.logger.error("Participants::unauthorized_disable_all_video"),new P("Unauthorized: User does not have permission to disable peer video.","1201")}async kickAll(){if(this.logger.info("Participants::kick_all"),a(this,Ne).getValue("viewType")!=="LIVESTREAM"&&!a(this,en,ld))throw new P("Can`t kick all without joining room","1205");if(!a(this,tn).permissions.kickParticipant)throw this.logger.error("Participants::unauthorized_kick_all"),new P("Unauthorized: User does not have permission to kick peers.","1201");const e=!0;a(this,It).kickAll(e)}async broadcastMessage(t,e,r){if(this.logger.info("Participants::broadcastMessage"),!a(this,en,ld))throw new P("Can`t broadcast message without joining room","1205");if(!(t!=null&&t.trim()))throw new P("`type` must be a non-empty string.","1209");if(r)if("meetingIds"in r)await a(this,It).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,It).broadcastToPeers(t,i,e)}else await a(this,It).broadcastMessage(t,e)}async getAllJoinedPeers(t,e,r){return(await a(this,It).getRoomPeers(t,e,r)).peers.map(or.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 P("Cannot update permissions, no valid userIDs found","1204");a(this,It).updatePermissions(i,e)}async getParticipantsInMeetingPreJoin(){return a(this,It).getRoomPeersNonPaginated()}},Ne=new WeakMap,rc=new WeakSet,Ap=function(){return a(this,Ne).getValue("roomNodeClient")},en=new WeakSet,ld=function(){var t;return((t=a(this,Ne).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},fa=new WeakSet,Mu=function(){var t;return((t=a(this,Ne).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},tn=new WeakMap,It=new WeakMap,wv);Ns([y.trace("Participants.setViewMode")],ts.prototype,"setViewMode",1),Ns([y.trace("Participants.setPage")],ts.prototype,"setPage",1),Ns([y.trace("Participants.disableAllAudio")],ts.prototype,"disableAllAudio",1),Ns([y.trace("Participants.disableAllVideo")],ts.prototype,"disableAllVideo",1),Ns([y.trace("Participants.kickAll")],ts.prototype,"kickAll",1),Ns([y.trace("Participants.broadcastMessage"),xt(Ln,"rateLimitConfig")],ts.prototype,"broadcastMessage",1),Ns([y.trace("Participants.getAllJoinedPeers"),xt({maxInvocations:10,period:60})],ts.prototype,"getAllJoinedPeers",1),Ns([y.trace("Participant.updatePermissions"),xt({maxInvocations:1e3,period:60})],ts.prototype,"updatePermissions",1),Ns([y.trace("Participants.getParticipantsInMeetingPreJoin")],ts.prototype,"getParticipantsInMeetingPreJoin",1),ts=Ns([ct("1200")],ts);var d1=Object.defineProperty,l1=Object.getOwnPropertyDescriptor,Ai=(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&&d1(t,e,i),i};const kS=(Pv=class{constructor(s,t,e){p(this,"participants");p(this,"self");p(this,"selectedPeers",_S);p(this,"maxSpatialLayerUpdates",new Map);p(this,"consumerPeerMap");p(this,"events");p(this,"roomSocketHandler");p(this,"context");p(this,"videoPeerConsumerMap",new Map);m(this,os,{mode:"ACTIVE_GRID",page:0});m(this,ws,!1);m(this,ai,!1);p(this,"updateConsumerSpatialLayers",nh(()=>{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,e=[])=>{this.logger.info(`updateConsumers: Starting consumer updates - AddProducers: ${s.length}, RemoveProducers: ${t.length}, RemoveStaleConsumers: ${e.length}, ConsumersSyncing: ${a(this,ws)}`);try{s.length!==0&&(this.logger.info(`updateConsumers: Creating consumers for ${s.length} producers: [${s.map(r=>r.producerId).join(", ")}]`),await this.roomNodeClient.createConsumers(s),this.logger.info("updateConsumers: Successfully created consumers."))}catch(r){this.logger.error("updateConsumers: Error creating consumers",{error:r})}try{t.length!==0&&(this.logger.info(`updateConsumers: Closing consumers for ${t.length} producers: [${t.map(r=>r.producerId).join(", ")}]`),await this.roomNodeClient.closeConsumers(t),this.logger.info("updateConsumers: Successfully closed consumers."))}catch(r){this.logger.error("updateConsumers: Error closing consumers",{error:r})}try{e.length!==0&&(this.logger.info(`updateConsumers: Closing ${e.length} stale consumers: [${e.join(", ")}]`),await this.roomNodeClient.closeConsumersById(e),this.logger.info("updateConsumers: Successfully closed stale consumers."))}catch(r){this.logger.error("updateConsumers: Error closing stale consumers",{error:r})}this.logger.info("updateConsumers: Completed consumer updates.")});this.context=s,this.roomSocketHandler=e,this.participants=new ts(s,t,this.roomSocketHandler),this.self=t,this.consumerPeerMap=new Map,this.events=fs,t.config.viewType!=="CHAT"&&this.setupEventsGlobal(),this.setupEvents()}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")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}setupEvents(){this.roomSocketHandler.on($.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),this.context.getValue("peerSessionStore").on(_.SOCKET_PEERS,s=>{const t=this.participants.joined.size>0;this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear(),this.participants.pinned.clear(),this.participants.joined.clear(),this.participants.currentPage=0,this.participants.viewMode="ACTIVE_GRID",t&&this.participants.emit("viewModeChanged",{viewMode:"ACTIVE_GRID",currentPage:this.participants.currentPage,pageCount:this.participants.pageCount}),s==null||s.forEach(e=>{e.waitlisted||this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(e))})}),this.roomSocketHandler.on(this.events.peerJoinedBroadcast,({participant:s})=>{this.logger.info("PEER_INFO:::MEDIA_JOIN",{participant:{id:s.peerId,maskedName:[...(s==null?void 0:s.displayName)||""].map((t,e)=>e%2?"*":t).join("")}}),this.onParticipantMediaJoined(s.peerId,s.producerStates)}),this.roomSocketHandler.on(this.events.selfJoinComplete,({participants:s,selectedPeers:t,roomState:e})=>{s.forEach(({peerId:n,producerStates:o})=>this.onParticipantMediaJoined(n,o));const{audioPeers:r,compulsoryPeers:i}=t!=null?t:{};e.pinnedPeerIds.length!==0&&this.onParticipantPinned(e.pinnedPeerIds[0]),this.computeActivateParticipants(r!=null?r:[],i),this.logger.info("selfJoinComplete: Emitting UPDATE_ACTIVE with createAllConsumers=true"),this.context.getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{createAllConsumers:!0})}),this.context.getValue("peerSessionStore").on(_.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(_.NEW_PRODUCER,({peerId:s,producer:t})=>{const e=this.participants.joined.get(s);if(!e){this.logger.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:t==null?void 0:t.producerId,kind:t==null?void 0:t.kind,status:"not_initialized",appData:{screenShare:t==null?void 0:t.screenShare}},participant:{id:s}});return}e.producers.push(t),this.logger.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:t==null?void 0:t.producerId,peerId:s,kind:t==null?void 0:t.kind,status:"not_initialized",appData:{screenShare:t==null?void 0:t.screenShare}}}),(t==null?void 0:t.kind)==="audio"&&this.participants.audioSubscribed.get(s)||(t==null?void 0:t.kind)==="video"&&this.participants.videoSubscribed.get(s)||t!=null&&t.screenShare?(this.logger.info(`NEW_PRODUCER: scheduling syncConsumer (AUTO mode) - Producer: ${t.producerId}, Peer: ${s}, Kind: ${t.kind}, ScreenShare: ${t.screenShare}, ConsumersSyncing: ${a(this,ws)}, VideoSub: ${t.kind==="video"?this.participants.videoSubscribed.has(s):"N/A"}, AudioSub: ${t.kind==="audio"?this.participants.audioSubscribed.has(s):"N/A"}`),this.scheduleSyncConsumers({source:"NEW_PRODUCER_AUTO"})):this.logger.info("ParticipantController::NEW_PRODUCER::not_consuming_producer_auto",{producer:{id:t==null?void 0:t.producerId,peerId:s,kind:t==null?void 0:t.kind,status:"UNKNOWN",appData:{screenShare:t==null?void 0:t.screenShare}}})}),this.context.getValue("peerSessionStore").on(_.PRODUCER_CLOSED,({peerId:s,producerId:t})=>{const e=this.participants.joined.get(s);if(!e){this.logger.warn("ParticipantController::NEW_PRODUCER::participant not found",{participant:{id:s}});return}e.producers=e.producers.filter(r=>r.producerId!==t)}),this.context.getValue("peerSessionStore").on(_.PRODUCER_TOGGLE,({peerId:s,producerId:t,paused:e,kind:r})=>{const i=this.participants.joined.get(s);if(i){r==="audio"&&i.setAudioEnabled(!e);const n=i.producers.find(o=>o.producerId===t);n&&(n.pause=e),r==="video"&&this.context.getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}}),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,ws)}, 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){const t=s.requests.filter(r=>!this.participants.waitlisted.toArray().find(i=>i.userId===r.userId)),e=this.participants.waitlisted.toArray().filter(r=>!s.requests.find(i=>i.userId===r.userId));t.forEach(r=>this.participants.waitlisted.add(new ar(this.context,{id:r.peerId,displayName:r.displayName,audioMuted:!0,videoEnabled:!1,audioTrack:void 0,videoTrack:void 0,stageStatus:"OFF_STAGE",userId:r.userId,flags:{},isHost:!1,customParticipantId:r.customParticipantId,picture:r.picture,metadata:{preset_name:r.presetName}},this.self,this.roomSocketHandler))),e.forEach(r=>this.participants.waitlisted.delete(r.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,os).mode!==s&&(a(this,os).mode=s),e&&a(this,os).page!==e&&(a(this,os).page=e);const{mode:r,page:i}=a(this,os);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":break;default:throw new Error(`View mode ${s} not supported`)}}async scheduleSyncConsumers({source:s}){var e,r,i;const t=((e=a(this,os))==null?void 0:e.mode)==="PAGINATED"&&!a(this,ws)?200:0;this.logger.info(`scheduleSyncConsumers():: Source: ${s}, ViewMode: ${(r=a(this,os))==null?void 0:r.mode}, ConsumersSyncing: ${a(this,ws)}, Delay: ${t}, Page: ${(i=a(this,os))==null?void 0:i.page}`),setTimeout(()=>this.syncConsumers(),t)}async syncConsumers(){var S,E,k,I,R,U;const s=this.context.getValue("connectionHandler");if((S=s==null?void 0:s.socketState)!=null&&S.state&&s.socketState.state!=="connected"){this.logger.info("syncConsumers: Socket not connected, deferring sync.");return}if(((k=(E=s==null?void 0:s.mediaState)==null?void 0:E.recv)==null?void 0:k.state)!=="connected"){this.logger.info("syncConsumers: Connection not ready, exiting.");return}if(a(this,ws)){g(this,ai,!0),this.logger.info("syncConsumers: Sync in progress, marking resyncRequired=true and exiting.");return}this.logger.info("syncConsumers: Starting sync operation."),g(this,ws,!0),g(this,ai,!1);let t=[];this.participants.videoSubscribed.forEach(D=>{var q,Z;const x=this.participants.joined.get(D.id),B=(Z=(q=D.producers)==null?void 0:q.filter(se=>se.kind==="video"))!=null?Z:[];x&&(B!=null&&B.length)&&B.forEach(se=>{var Kt,A,T,w;const at=((A=(Kt=x.manualProducerConfig)==null?void 0:Kt.video)!=null?A:!0)&&se.kind==="video"&&!se.screenShare,kt=((w=(T=x.manualProducerConfig)==null?void 0:T.screenshareVideo)!=null?w:!0)&&se.kind==="video"&&se.screenShare;(at||kt)&&(se.pause||t.push(se))})}),this.participants.audioSubscribed.forEach(D=>{var q,Z;const x=this.participants.joined.get(D.id),B=(Z=(q=D.producers)==null?void 0:q.filter(se=>se.kind==="audio"))!=null?Z:[];x&&(B!=null&&B.length)&&B.forEach(se=>{var Kt,A,T,w;const at=((A=(Kt=x.manualProducerConfig)==null?void 0:Kt.audio)!=null?A:!0)&&se.kind==="audio"&&!se.screenShare,kt=((w=(T=x.manualProducerConfig)==null?void 0:T.screenshareAudio)!=null?w:!0)&&se.kind==="audio"&&se.screenShare;(at||kt)&&t.push(se)})}),t=ok(t,D=>D.producerId);const e=new Map;t.forEach(D=>{e.set(D.producerId,D)});const r=(R=(I=this.roomNodeClient)==null?void 0:I.getConsumers())!=null?R:new Map,i=new Map(Array.from(r.values()).map(D=>[D.producerId,D]));let n=t.filter(D=>!i.has(D.producerId));t.filter(D=>!D.consumer&&i.has(D.producerId)).forEach(D=>{const x=i.get(D.producerId);x&&(this.logger.info(`syncConsumers: remapping existing consumer ${x.id} to producer ${D.producerId}`),this.processNewConsumer(x.id))});let c=[],d=Array.from(r.values()).filter(D=>!this.participants.joined.has(D.peerId)).map(D=>D.id),l=Array.from(r.values()).filter(D=>this.participants.joined.has(D.peerId)).map(D=>D.peerId);l=ak(l),l==null||l.forEach(D=>{var B;const x=this.participants.joined.get(D);if(!x){this.logger.warn(`Peer with ${D} doesn't exist in joined list but producers of it are being consumed.`);return}(B=x.producers)!=null&&B.length&&x.producers.forEach(q=>{const Z=q.consumer&&r.has(q.consumer.id);!e.has(q.producerId)&&(i.has(q.producerId)||Z)&&c.push(q)})}),this.logger.info(`syncConsumers: Computed changes - AddProducers: ${n.length} [${n.map(D=>D.producerId).join(", ")}], RemoveProducers: ${c.length} [${c.map(D=>D.producerId).join(", ")}], RemoveStaleConsumers: ${d.length} [${d.join(", ")}]`.substring(0,5e3));const u=35,h=35;n.length>u&&(this.logger.warn(`syncConsumers: Too many remote producers to create consumers: ${n.length}. Only adding ${u} in this run.`),n=n.slice(0,u),this.scheduleSyncConsumers({source:"SOFT_CAPPED_CREATE_CONSUMERS"}));const f=d.length+c.length;f>h&&(this.logger.warn(`syncConsumers: Too many remote consumers to close: ${f}. Only removing ${h} in this run.`),d=d.slice(0,h),c=c.slice(0,h-d.length),this.scheduleSyncConsumers({source:"SOFT_CAPPED_REMOVE_CONSUMERS"}));try{n.length>0||c.length>0||d.length>0?(this.logger.info(`syncConsumers: Calling updateConsumers with changes. Adding ${n.length}, removing ${c.length}, and removing ${d.length} stale consumers.`),await this.updateConsumers(n,c,d),this.logger.info("syncConsumers: updateConsumers completed successfully.")):this.logger.info("syncConsumers: No changes needed, skipping updateConsumers.")}catch(D){this.logger.error("syncConsumers: updateConsumers failed with error.",{error:D})}finally{this.logger.info("syncConsumers: Setting consumersSyncing=false and completing sync."),g(this,ws,!1),(U=s==null?void 0:s.socketState)!=null&&U.state&&s.socketState.state!=="connected"&&g(this,ai,!0)}a(this,ai)&&(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=kS.formatSocketPeerMessage(s);return new ar(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("PEER_INFO:::SOCKET_ON_MEDIA_JOIN",{participant:{id:e.id,maskedName:[...(e==null?void 0:e.name)||""].map((r,i)=>i%2?"*":r).join("")}}),this.logger.info(`onParticipantMediaJoined: peer ${s} has joined media room. Processing.`),t.forEach(r=>{r.kind===Zs.AUDIO&&!r.screenShare?e.setAudioEnabled(!r.pause):r.kind===Zs.VIDEO&&!r.screenShare&&(e.setVideoEnabled(!r.pause),this.updatePipSource(e.id,!r.pause)),e.producers.push({...r,producingTransportId:r.producingTransportId,kind:r.kind===Zs.AUDIO?"audio":"video",producingPeerId:s,mimeType:r.mimeType})}),this.logger.info(`onParticipantMediaJoined: Emitting UPDATE_ACTIVE for peer ${s}`),this.context.getValue("peerSessionStore").emit(_.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=>{if(!this.participants.joined.get(o)){this.logger.warn("updateActiveParticipants::participant_not_in_joined_list",{participant:{id:o}});return}s.add(this.participants.joined.get(o),!r.get(o))}),s.emit("participantsUpdate")}updateParticipantsMap(s,t){Array.from(s.keys()).forEach(r=>{t.includes(r)||s.delete(r,!0)}),t.forEach(r=>{s.get(r)||s.add(this.participants.joined.get(r),!0)}),s.emit("participantsUpdate")}updatePinnedParticipants(){this.participants.pinned.forEach(s=>{s.setIsPinned(!1),this.participants.pinned.delete(s.id)})}setupEventsGlobal(){this.roomSocketHandler.on($.joinRoom,({peer:s})=>{s.waitlisted||(this.logger.info("Processing socket join",{peers:s.peerId}),this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(s)),this.logger.info("Processed socket join",{peers:s.peerId}))}),this.roomSocketHandler.on($.leaveRoom,s=>{const{peerId:t}=s.peer;this.selectedPeers.delete(t,this.context),this.onParticipantLeave(t)}),this.context.getValue("peerSessionStore").on(_.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(_.SOCKET_SERVICE_DISCONNECTED,()=>{g(this,ai,!0),this.logger.info("Socket disconnected — keeping participants visible for seamless reconnection")}),this.context.getValue("peerSessionStore").on(_.CONSUMER_PAUSED,({id:s})=>{this.processConsumerPaused(s)}),this.context.getValue("peerSessionStore").on(_.CONSUMER_RESUMED,({id:s})=>{this.processConsumerResumed(s)}),this.context.getValue("peerSessionStore").on(_.NEW_CONSUMER_CREATED,({id:s})=>{this.processNewConsumer(s)}),this.context.getValue("peerSessionStore").on(_.CONSUMER_CLOSED,({id:s})=>{this.processConsumerClosed(s)}),this.context.getValue("peerSessionStore").on(_.ROOM_MESSAGE,async({payload:s,type:t,timestamp:e})=>{this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(_.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(_.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(_.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(_.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(_.UPDATE_ACTIVE,({viewMode:s,page:t,createAllConsumers:e}={})=>{this.logger.info(`UPDATE_ACTIVE event received - viewMode: ${a(this,os).mode}, page: ${t}, CreateAllConsumers: ${e}`),e&&(this.logger.info(`UPDATE_ACTIVE viewMode: ${s}, Page: ${t}, Removing existing subscriptions.`),this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear()),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.logger.info(`onParticipantSocketJoined: peer ${s.id} has joined socket edge. Processing.`),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.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(_.UPDATE_STAGE_REQUESTS,{request:{displayName:s.name,userId:s.userId,peerId:s.id},add:!0})),this.context.getValue("peerSessionStore").emit(_.PEER_JOINED_INTERNAL,s)}async onParticipantLeave(s){this.logger.info(`peer ${s} has left. Deleting peer from maps and closing consumers.`);const t=this.participants.joined.get(s);this.participants.joined.delete(s,!0,!0),this.participants.pinned.delete(s,!0,!0),this.participants.waitlisted.delete(s,!0,!0),this.roomNodeClient&&this.roomNodeClient.closeConsumers(t==null?void 0:t.producers),t&&t.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&this.context.getValue("peerSessionStore").emit(_.UPDATE_STAGE_REQUESTS,{request:{displayName:t.name,userId:t.userId,peerId:t.id},add:!1});const{currentPage:e}=this.participants,r=this.maxPreferredStreams*(e-1),i=this.participants.videoSubscribed.get(s);this.participants.viewMode==="MANUAL"?this.context.getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:e}):r===0?this.participants.setViewMode("ACTIVE_GRID"):this.participants.joined.size<=r?e===2?this.participants.setViewMode("ACTIVE_GRID"):this.participants.setPage(e-1):i&&this.context.getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:e})}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}),{peerId:e,kind:r,appData:u,remotelyPaused:d,track:n,producerId:o,rtpReceiver:c,localId:l}}processConsumerClosed(s){const{peerId:t,type:e,appData:r,remotelyPaused:i,producerId:n}=this.consumerPeerMap.get(s)||{},o=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.screenShare!==!0&&this.videoPeerConsumerMap.delete(t),!o)return;const c=o.producers.find(l=>l.producerId===n);c&&(c.consumer={id:s,peerId:t,kind:void 0,appData:r,paused:i,producerId:n,rtpReceiver:void 0,localId:void 0});const d=[];r&&r.screenShare?(o.setScreenShareEnabled(!1),this.context.getValue("callstats").consumerSharedMediaState(s,{screen:!1}),o.screenShareTracks.video&&d.push(o.screenShareTracks.video.id),o.screenShareTracks.audio&&d.push(o.screenShareTracks.audio.id),o.screenShareTracks={audio:void 0,video:void 0}):e==="audio"?(o.setAudioEnabled(!1),o.audioTrack&&d.push(o.audioTrack.id),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:!1}),o.audioTrack=void 0):e==="video"&&(o.setVideoEnabled(!1),this.updatePipSource(o.id,!1),o.videoTrack&&d.push(o.videoTrack.id),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!1}),o.videoTrack=void 0),r.e2ee&&d.forEach(l=>{this.context.getValue("peerSessionStore").emit(_.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:l})})}processConsumerResumed(s){var f;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(S=>S.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(_.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),(f=this.context)==null||f.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(_.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(_.E2EE_ACTIVE_CONSUMER,{peerId:t,rtpReceiver:c,track:i}),this.context.getValue("peerSessionStore").emit(_.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=$h(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(_.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}},os=new WeakMap,ws=new WeakMap,ai=new WeakMap,Pv);let or=kS;Ai([y.trace("ParticipantController.setupEvents")],or.prototype,"setupEvents",1),Ai([y.trace("ParticipantController.setupEvents")],or.prototype,"setupEventsGlobal",1),Ai([y.trace("ParticipantController.processMedia")],or.prototype,"processMedia",1),Ai([y.trace("ParticipantController.processConsumerClosed")],or.prototype,"processConsumerClosed",1),Ai([y.trace("ParticipantController.processConsumerResumed")],or.prototype,"processConsumerResumed",1),Ai([y.trace("ParticipantController.processConsumerPaused")],or.prototype,"processConsumerPaused",1),Ai([y.trace("ParticipantController.processNewConsumer")],or.prototype,"processNewConsumer",1);const Ae=Ms(lh().permissions),Hl=class extends Nt{constructor(e,r,i,n=!1){const o=e.getValue("logger");super(o);m(this,yt);m(this,Y,void 0);m(this,Sa,void 0);m(this,va,void 0);m(this,Fl,e=>{var l,u,h;const{chat:r,connectedMeetings:i,plugins:n,polls:o,media:c,...d}=e;if(r&&(r.private&&Mr(a(this,Y).chat.private,r.private),r.public&&Mr(a(this,Y).chat.public,r.public),this.emit("chatUpdate")),i&&Mr(a(this,Y).connectedMeetings,i),c){const f=E=>{switch(E){case Dr.NONE:return G.Allowed;case Dr.ALLOWED:return G.Allowed;case Dr.NOT_ALLOWED:return G.NotAllowed;case Dr.CAN_REQUEST:return G.CanRequest;default:return}},S={audio:void 0,video:void 0,screenshare:void 0};(l=c.audio)!=null&&l.canProduce&&(S.audio={canProduce:f(c.audio.canProduce)}),(u=c.video)!=null&&u.canProduce&&(S.video={canProduce:f(c.video.canProduce)}),(h=c.screenshare)!=null&&h.canProduce&&(S.screenshare={canProduce:f(c.screenshare.canProduce)}),Mr(a(this,Y).media,S)}n&&(Mr(a(this,Y).plugins,n),this.emit("pluginsUpdate")),o&&(Mr(a(this,Y).polls,o),this.emit("pollsUpdate")),Object.keys(d).length!==0&&Mr(a(this,Y),d),this.emit("permissionsUpdate",e)});if(!r)throw this.logger.error("PermissionPreset::load_preset_permissions_failed"),new P("Could not load preset permissions.","0904");g(this,va,e),g(this,Sa,i),g(this,Y,r),n&&this.setupEvents()}setupEvents(){a(this,va).getValue("peerSessionStore").on(_.UPDATE_PERMISSIONS,a(this,Fl))}static init(e,r,i){let n;return i?n=new Hl(e,i,r,!0):n=new Hl(e,Ae,r),n}get mediaRoomType(){return"CF"}get stageEnabled(){var e;return((e=a(this,Y))==null?void 0:e.stageEnabled)||a(this,Sa)===Ys.Webinar||a(this,Sa)===Ys.Livestream}get acceptStageRequests(){var e,r;return this.stageEnabled?((e=a(this,Y))==null?void 0:e.acceptStageRequests)||((r=a(this,Y))==null?void 0:r.canAcceptProductionRequests):!1}get stageAccess(){var e,r,i;return((e=a(this,Y))==null?void 0:e.stageAccess)===G.NotAllowed?G.NotAllowed:((r=a(this,Y))==null?void 0:r.stageAccess)===G.CanRequest?G.CanRequest:((i=a(this,Y))==null?void 0:i.stageAccess)===G.Allowed||a(this,Y).media.audio.canProduce===G.Allowed||a(this,Y).media.video.canProduce===G.Allowed||a(this,Y).media.screenshare.canProduce===G.Allowed?G.Allowed:a(this,Y).media.audio.canProduce===G.CanRequest||a(this,Y).media.video.canProduce===G.CanRequest||a(this,Y).media.screenshare.canProduce===G.CanRequest?G.CanRequest:G.NotAllowed}get acceptWaitingRequests(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.acceptWaitingRequests)!=null?r:Ae.acceptWaitingRequests}get requestProduceVideo(){var e,r,i;return((i=(r=(e=a(this,Y))==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,Y))==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,Y))==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,Y))==null?void 0:e.disableParticipantAudio)!=null?r:Ae.disableParticipantAudio}get canAllowParticipantScreensharing(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.canAcceptProductionRequests)!=null?r:Ae.canAcceptProductionRequests}get canAllowParticipantVideo(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.disableParticipantVideo)!=null?r:Ae.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.kickParticipant)!=null?r:Ae.kickParticipant}get pinParticipant(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.pinParticipant)!=null?r:Ae.pinParticipant}get canRecord(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.canRecord)!=null?r:Ae.canRecord}get waitingRoomBehaviour(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.waitingRoomType)!=null?r:Ae.waitingRoomType}get plugins(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.plugins)!=null?r:Ae.plugins}get polls(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.polls)!=null?r:Ae.polls}get canProduceVideo(){var r;const e=(r=a(this,Y).media.video.canProduce)!=null?r:Ae.media.video.canProduce;return this.stageEnabled&&(a(this,yt,zt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,yt,zt)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,yt,zt)==="OFF_STAGE"||a(this,yt,zt)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get canProduceScreenshare(){var r;const e=(r=a(this,Y).media.screenshare.canProduce)!=null?r:Ae.media.screenshare.canProduce;return this.stageEnabled&&(a(this,yt,zt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,yt,zt)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,yt,zt)==="OFF_STAGE"||a(this,yt,zt)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get canProduceAudio(){var r;const e=(r=a(this,Y).media.audio.canProduce)!=null?r:Ae.media.audio.canProduce;return this.stageEnabled&&(a(this,yt,zt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,yt,zt)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,yt,zt)==="OFF_STAGE"||a(this,yt,zt)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get chatPublic(){var e,r,i;return(i=(r=(e=a(this,Y))==null?void 0:e.chat)==null?void 0:r.public)!=null?i:Ae.chat.public}get chatPrivate(){var e,r,i;return(i=(r=(e=a(this,Y))==null?void 0:e.chat)==null?void 0:r.private)!=null?i:Ae.chat.private}get connectedMeetings(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.connectedMeetings)!=null?r:Ae==null?void 0:Ae.connectedMeetings}get hiddenParticipant(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.hiddenParticipant)!=null?r:Ae.hiddenParticipant}get showParticipantList(){var e;return(e=a(this,Y).showParticipantList)!=null?e:Ae.showParticipantList}get canChangeParticipantPermissions(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.canChangeParticipantPermissions)!=null?r:Ae.canChangeParticipantPermissions}get canEditDisplayName(){var e;return(e=a(this,Y).canEditDisplayName)!=null?e:!1}get isRecorder(){return a(this,Y).isRecorder}get canSpotlight(){return a(this,Y).canSpotlight}get canLivestream(){return a(this,Y).canLivestream}get transcriptionEnabled(){return a(this,Y).transcriptionEnabled}};let Qh=Hl;Y=new WeakMap,Sa=new WeakMap,va=new WeakMap,Fl=new WeakMap,yt=new WeakSet,zt=function(){return a(this,va).getValue("stageStatus")};class CS extends Nt{constructor(e,r){super(r);p(this,"localMediaHandler");m(this,qt,void 0);g(this,qt,e)}async updatePermission(){var d,l;const e=(u,h)=>{this.mediaPermissions[u]=h;const f={message:this.mediaPermissions[u],kind:u};h==="DENIED"?a(this,qt).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_ERROR,f):a(this,qt).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,f)};if(ye.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,qt))==null||i.getValue("callstats").mediaPermission("AUDIO",e),(n=a(this,qt))==null||n.getValue("callstats").mediaPermission("SPEAKER",e);break}case"video":{(o=a(this,qt))==null||o.getValue("callstats").mediaPermission("VIDEO",e);break}case"screenshare":{(c=a(this,qt))==null||c.getValue("callstats").mediaPermission("SCREENSHARE",e);break}}}get peerId(){var e;return(e=a(this,qt))==null?void 0:e.getValue("peerId")}async init(e={},r=!1,i=null){var n,o,c,d,l,u,h;if(ye.init(),i&&g(this,qt,i),!this.localMediaHandler)try{let f=!0;if((n=i==null?void 0:i.getValue("defaults"))!=null&&n.mediaHandler)f=!1,this.localMediaHandler=i.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:S}=navigator;this.localMediaHandler=await S.init(e)}else this.localMediaHandler=new Ct(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(_.MEDIA_PERMISSION_UPDATE,async S=>{if(this.populateMediaPermissionsInCallstats({message:S.message,kind:S.kind}),S.message==="NOT_REQUESTED")switch(S==null?void 0:S.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",S)}),i==null||i.getValue("peerSessionStore").on(_.MEDIA_PERMISSION_ERROR,async S=>{const{kind:E,message:k,constraints:I}=S;this.populateMediaPermissionsInCallstats({message:k,kind:E}),E==="audio"?(this.logger.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):E==="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:E,message:k}}),this.emit("mediaPermissionError",S),this.emit("mediaPermissionUpdate",{message:k,kind:E})}),f){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 S=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 S}}catch(f){this.logger.error("Self::init::Failed To Setup Streams",{error:{name:f.name,message:f.message}})}}set context(e){g(this,qt,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.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableVideo(){await this.localMediaHandler.enableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}async disableAudio(){this.localMediaHandler.disableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableScreenShare(){await this.localMediaHandler.enableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableScreenShare(){await this.localMediaHandler.disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableVideo(){await this.localMediaHandler.disableVideo(),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.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.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})}}qt=new WeakMap;var u1=Object.defineProperty,h1=Object.getOwnPropertyDescriptor,ft=(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&&u1(t,e,i),i};let We=(_v=class extends CS{constructor(t,e,r,i,n){const o=t.getValue("logger");super(t,o);m(this,Tr);m(this,Qe);m(this,Ea);m(this,$e);m(this,ic);p(this,"name");p(this,"picture");p(this,"customParticipantId");p(this,"waitlistStatus");m(this,Ta,void 0);m(this,Et,void 0);m(this,ya,void 0);p(this,"role");p(this,"userId");p(this,"organizationId");p(this,"supportsRemoteControl",!1);p(this,"device");m(this,Ye,void 0);p(this,"hidden",!1);p(this,"presetName");p(this,"roomState","init");m(this,ba,new Set);m(this,wa,new Set);g(this,Ye,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=e.customParticipantId,this.waitlistStatus="none",g(this,Et,r),g(this,Ta,i),this.hidden=!1,g(this,ya,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=ye.isElectron(),this.device=ye.getDeviceInfo(),this.presetName=n,this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),N(this,ic,Mp).call(this)}get telemetry(){return a(this,Ye).getValue("telemetry")}get stageStatus(){return a(this,Ye).getValue("stageStatus")}get producers(){var t,e;return Array.from((e=(t=a(this,Qe,pt).getProducers())==null?void 0:t.values())!=null?e:[])}get id(){return this.peerId}get peerId(){return a(this,Ye).getValue("peerId")}static async __init__(t,e,r,i,n,o=!1){var f,S,E,k,I,R;let c=(S=(f=t.getValue("defaults"))==null?void 0:f.audio)!=null?S:!0,d=(k=(E=t.getValue("defaults"))==null?void 0:E.video)!=null?k:!0;r.canProduceAudio!=="ALLOWED"&&(c=!1),r.canProduceVideo!=="ALLOWED"&&(d=!1);const l=new We(t,e,r,i,n),u=bD(i.mediaConstraints);Mr(u,(I=t.getValue("defaults"))==null?void 0:I.mediaConfiguration);const h=(R=t.getValue("defaults"))==null?void 0:R.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,Et).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",N(this,ic,Mp));const t=a(this,Ea,Ou);t&&t.onError(e=>{this.emit("autoplayError",e)}),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::AUDIO_TRACK_CHANGE",{...Ii(this)}),a(this,$e,je)&&this.audioEnabled)try{await a(this,Qe,pt).shareMic(this.audioTrack)}catch(e){this.logger.error("Self::setupEvents::Error while sharing mic",{error:e}),this.localMediaHandler.disableAudio()}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",{...Ii(this)}),a(this,$e,je)&&this.rawVideoTrack===void 0)this.logger.info("Self::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&a(this,$e,je))try{await a(this,Qe,pt).shareWebcam(this.videoTrack)}catch(e){this.logger.error("Self::setupEvents::failed shareWebcam",{error:e}),this.videoEnabled&&await this.localMediaHandler.disableVideo()}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,Ea,Ou))==null||r.setSpeakerDevice(e.deviceId))}),this.localMediaHandler.on("DEVICE_LIST_UPDATED",e=>{this.emit("deviceListUpdate",e)}),this.localMediaHandler.on("SCREENSHARE_TRACK_CHANGE",async()=>{if(!a(this,$e,je)){this.logger.error("Self.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{await a(this,Qe,pt).shareScreen(this.screenShareTracks)}catch(e){this.logger.error("Self::setupEvents::Error while sharing screen",{error:e}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.logger.info("Self::setupEvents::SCREENSHARE_TRACK_CHANGE",{...Ii(this)}),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",{...Ii(this)})}),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{var e;(e=a(this,Ye))==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,$e,je)&&await a(this,Qe,pt).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(e=a(this,Ye))==null||e.getValue("callstats").videoOff()}),a(this,Et).on("permissionsUpdate",e=>{var r,i,n;(r=e==null?void 0:e.media)!=null&&r.audio&&a(this,Et).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,Et).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,Et).canProduceScreenshare!==G.Allowed&&(this.disableScreenShare(),this.logger.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return a(this,Et)}get config(){return a(this,Ta)}get roomJoined(){var t;return a(this,Ta).viewType===Ys.Livestream&&this.stageStatus!=="ON_STAGE"?((t=a(this,Ye).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:a(this,$e,je)}setName(t){if(!t)throw new P("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,Et).canProduceAudio===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if((e=a(this,Ye))==null||e.getValue("callstats").audioOn(),await this.localMediaHandler.enableAudio(t),a(this,$e,je)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{await a(this,Qe,pt).shareMic(this.audioTrack)}catch(r){this.logger.error("Self::enableAudio::Error while sharing mic",{error:r}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}}async enableVideo(t){var e;if(a(this,Et).canProduceVideo!==G.NotAllowed&&!(a(this,Et).canProduceVideo===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if((e=a(this,Ye))==null||e.getValue("callstats").videoOn(),await this.localMediaHandler.enableVideo(t),a(this,$e,je)&&this.stageStatus==="ON_STAGE")try{await a(this,Qe,pt).shareWebcam(this.videoTrack)}catch(r){this.logger.error("Self::enableVideo::Error while sharing video",{error:r}),this.videoEnabled&&this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),this.logger.info("Self.enableVideo",{...Ii(this)})}}async updateVideoConstraints(t){if(!this.localMediaHandler.updateVideoConstraints)throw new P("Unsupported","1102");await this.localMediaHandler.updateVideoConstraints(t)}async enableScreenShare(){if(!a(this,$e,je))throw new P("Can`t enable screenshare without joining room","1105");if(a(this,Et).canProduceScreenshare!==G.NotAllowed&&!(a(this,Et).canProduceScreenshare===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.screenShareEnabled&&(await this.localMediaHandler.enableScreenShare(),this.screenShareTracks.audio||this.screenShareTracks.video)){try{await a(this,Qe,pt).shareScreen(this.screenShareTracks)}catch(t){this.logger.error("Self::enableScreenShare::Error while sharing screen",{error:t}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}}async updateScreenshareConstraints(t){if(!this.localMediaHandler.updateScreenshareConstraints)throw new P("Unsupported","1102");await this.localMediaHandler.updateScreenshareConstraints(t)}async disableAudio(){var t;this.audioEnabled&&(this.localMediaHandler.disableAudio(),a(this,$e,je)&&a(this,Qe,pt).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),(t=a(this,Ye))==null||t.getValue("callstats").audioOff())}async disableVideo(){var t;this.videoEnabled&&(await this.localMediaHandler.disableVideo(),a(this,$e,je)&&await a(this,Qe,pt).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(t=a(this,Ye))==null||t.getValue("callstats").videoOff())}async disableScreenShare(){this.screenShareEnabled&&(await this.localMediaHandler.disableScreenShare(),a(this,$e,je)&&await a(this,Qe,pt).disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var i;g(this,ya,t);const r=t?"pinned":"unpinned";(i=a(this,Tr,_n))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}get isPinned(){return a(this,ya)}async pin(){if(!a(this,$e,je))throw new P("Can`t pin participants without joining room","1105");return this.show(),a(this,Qe,pt).pinPeer(this.id)}async unpin(){if(!a(this,$e,je))throw new P("Can`t unpin participants without joining room","1105");return a(this,Qe,pt).pinPeer(null)}async hide(){if(!a(this,$e,je))throw new P("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})}show(){if(!a(this,$e,je))throw new P("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 P("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,$e,je)&&await a(this,Qe,pt).muteSelf(),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,$e,je)&&await a(this,Qe,pt).pauseWebcam(),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,Ea,Ou))==null?void 0:t.play()}registerVideoElement(t,e=!1){var r,i;t&&(e?a(this,ba).add(t):a(this,wa).add(t),this.updateVideo(t),e||(i=a(this,Tr,_n))==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,Tr,_n).removeSource(this.id);return}t.srcObject=void 0,e?a(this,ba).delete(t):(a(this,wa).delete(t),a(this,Tr,_n).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,Tr,_n))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(n=a(this,Tr,_n))==null||n.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},Ta=new WeakMap,Et=new WeakMap,ya=new WeakMap,Ye=new WeakMap,Tr=new WeakSet,_n=function(){return a(this,Ye).getValue("pip")},Qe=new WeakSet,pt=function(){return a(this,Ye).getValue("roomNodeClient")},Ea=new WeakSet,Ou=function(){return a(this,Ye).getValue("audioPlayback")},$e=new WeakSet,je=function(){var t;return((t=a(this,Ye).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},ba=new WeakMap,wa=new WeakMap,ic=new WeakSet,Mp=function(){Array.from(a(this,wa)).forEach(t=>this.updateVideo(t,!1)),Array.from(a(this,ba)).forEach(t=>this.updateVideo(t,!0))},_v);ft([y.trace("Self.cleanupEvents")],We.prototype,"cleanupEvents",1),ft([y.trace("Self.setupEvents")],We.prototype,"setupEvents",1),ft([y.trace("Self.setupTracks")],We.prototype,"setupTracks",1),ft([y.trace("Self.destructMediaHandler")],We.prototype,"destructMediaHandler",1),ft([y.trace("Self.removeDocumentEventListeners")],We.prototype,"removeDocumentEventListeners",1),ft([nr.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"Self.toggleAudio",timeout:3e3}),y.trace("Self.enableAudio")],We.prototype,"enableAudio",1),ft([nr.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"Self.toggleVideo",timeout:3e3}),y.trace("Self.enableVideo")],We.prototype,"enableVideo",1),ft([y.trace("Self.updateVideoConstraints")],We.prototype,"updateVideoConstraints",1),ft([y.trace("Self.enableScreenShare"),nr.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3})],We.prototype,"enableScreenShare",1),ft([y.trace("Self.updateScreenshareConstraints")],We.prototype,"updateScreenshareConstraints",1),ft([nr.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"Self.toggleAudio",timeout:3e3}),y.trace("Self.disableAudio")],We.prototype,"disableAudio",1),ft([nr.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"Self.toggleVideo",timeout:3e3}),y.trace("Self.disableVideo")],We.prototype,"disableVideo",1),ft([nr.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3}),y.trace("Self.disableScreenShare")],We.prototype,"disableScreenShare",1),ft([y.trace("Self.setDevice")],We.prototype,"setDevice",1),We=ft([ct("1100")],We);class Xh extends Error{constructor(t){super(t!=null?t:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Xh)}}class Zh extends Error{constructor(t){super(t!=null?t:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Zh)}}class ep{constructor(t,e=!1){p(this,"pendingTasks",new Map);p(this,"nextTaskId",0);p(this,"stopping",!1);m(this,nc,void 0);this.log=e,g(this,nc,{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 Xh);this.stopping=!1}remove(t){const e=Array.from(this.pendingTasks.values())[t];e&&e.reject(new Zh)}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,nc).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)}}}nc=new WeakMap;class To extends Error{constructor(t){super(t),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,To):this.stack=new Error(t).stack}}class Rt extends Error{constructor(t){super(t),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Rt):this.stack=new Error(t).stack}}class Br extends Error{constructor(t){super(t),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Rt):this.stack=new Error(t).stack}}const RS=s=>new Promise(t=>setTimeout(t,s));async function IS(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)})}function p1(s){return s.map(t=>({channels:t.channels,clockRate:t.clockRate,mimeType:t.mimeType,sdpFmtpLine:t.sdpFmtpLine}))}function m1(s){return s.map(t=>({uri:t.uri}))}function dl(s){return{codecs:p1(s.codecs),headerExtensions:m1(s.headerExtensions?s.headerExtensions:[])}}function g1(s){const t=RTCRtpReceiver.getCapabilities("audio"),e=RTCRtpReceiver.getCapabilities("video"),r=RTCRtpSender.getCapabilities("audio"),i=RTCRtpSender.getCapabilities("video");s&&(e.codecs=e.codecs.filter(({mimeType:d})=>s===d),i.codecs=i.codecs.filter(({mimeType:d})=>s===d));const n={audio:dl(t),video:dl(e)};return{sender:{audio:dl(r),video:dl(i)},receiver:n}}class f1{constructor(t){m(this,Xe,void 0);p(this,"events");g(this,Xe,t),this.events=fs}async joinRoom(t,e,r,i=!1){const n={roomUuid:t,displayName:e,prejoined:i,capabilities:r};return(await a(this,Xe).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:HC.toBinary(n),timeout:5e3})).payload}async connectTransport(t){const e=(await a(this,Xe).sendMessagePromise(this.events.createWebRTCTransport,fC.toBinary(t))).payload,{transportId:r,description:i,producerIds:n}=Sf.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,Xe).sendMessagePromise(this.events.produce,rR.toBinary(t))).payload,r=UR.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,Xe).sendMessagePromise(this.events.consume,QC.toBinary(t))).payload,{consumerIdsMap:{map:r},description:i}=VR.fromBinary(e);return{consumerStateMap:r,sessionDescription:i}}async closeProducer(t){const e=(await a(this,Xe).sendMessagePromise(this.events.closeProducer,lR.toBinary(t))).payload,{description:r}=GR.fromBinary(e);return r}async closeConsumer(t){return(await a(this,Xe).sendMessagePromise(this.events.closeConsumer,hR.toBinary(t))).payload}async updateConsumersSimulcastConfig(t){return(await a(this,Xe).sendMessagePromise(this.events.updateConsumersSimulcastConfig,tR.toBinary(t))).payload}async hostControlForPeer(t,e){const r={audio:e==="audio",screeShare:!1,video:e==="video",participantId:t},i=(await a(this,Xe).sendMessagePromise(this.events.hostControlPeer,vR.toBinary(r))).payload;if(!i)return!1;const{status:n}=XR.fromBinary(i);return n==="success"}async hostControlForAll(t){const e={audio:t==="audio",screenShare:!1,video:t==="video"},r=(await a(this,Xe).sendMessagePromise(this.events.hostControlAllPeers,yR.toBinary(e))).payload;if(!r)return!1;const{status:i}=eI.fromBinary(r);return i==="success"}async kickAll(){const t={propagateKickAcrossRooms:!1};a(this,Xe).sendMessagePromise($.kickAll,wf.toBinary(t))}async kickPeer(t){a(this,Xe).sendMessagePromise($.kick,xf.toBinary(t))}async changeDisplayName(t){const e=(await a(this,Xe).sendMessagePromise(this.events.changeDisplayName,fR.toBinary(t))).payload;if(!e)return!1;const{status:r}=sI.fromBinary(e);return r==="success"}async notifySelfJoinComplete(){const t={},e=(await a(this,Xe).sendMessagePromise(this.events.selfJoinComplete,jC.toBinary(t))).payload;return Th.fromBinary(e)}async audioActivity(t){a(this,Xe).sendMessage(this.events.audioActivity,vC.toBinary(t))}}Xe=new WeakMap;var Fr=(s=>(s.NEW="new",s.CONNECTING="connecting",s.RECONNECTING="reconnecting",s.DISCONNECTED="disconnected",s.CONNECTED="connected",s.FAILED="failed",s.CLOSED="closed",s))(Fr||{});class ll extends gt.EventEmitter{constructor(e){super();m(this,ac,void 0);g(this,ac,e),this.setMaxListeners(1/0)}get logger(){return a(this,ac).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)}})}}ac=new WeakMap;class tp extends ll{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 sp extends tp{static createFactory(t){return()=>new sp(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=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e});if(!navigator.isReactNative){this.logger.debug("creating new transceiver");const d=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`senders available params: ${JSON.stringify(d)}`);const l=[];r&&r.length&&r.forEach(u=>{var f;const h=d.codecs.find(S=>S.mimeType.includes(u.name));if(u.parameters){this.logger.debug(`codecOption.parameters:${JSON.stringify(u.parameters)}`);const S=((f=h.sdpFmtpLine)==null?void 0:f.split(";"))||[];S.push(...u.parameters);const E=Array.from(new Set(S).values());h.sdpFmtpLine=E.join(";")}l.push(h)}),this.logger.info(`selected codecs: ${JSON.stringify(l)}`),n.setCodecPreferences(l)}const o=await this.pc.createOffer();if(await this.pc.setLocalDescription(o),r&&r.findIndex(({name:d})=>d==="opus")>=0){const{enableDtx:d,enableStereo:l}=this,u=this.enableHighBitrate?l?128e3:64e3:l?64e3:32e3;o.sdp=o.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${d?"usedtx=1;":""}${l?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${u}`),o.sdp+=`a=rtcp-fb:111 nack\r
|
|
15
|
-
`}this.midTransceiverMap.set(n.mid,n);const c=async d=>(this.logger.debug(`[SDP] send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),await this.pc.setRemoteDescription(d),n.mid);return this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(o,void 0,2)}]`),{offerSdp:o,callback:c,sender:n.sender,mid:n.mid}}}var AS={},ul={},S1={get exports(){return ul},set exports(s){ul=s}},MS=S1.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(MS).forEach(function(s){var t=MS[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=ul,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 f=h[0],S=h.slice(2);f==="m"&&(l.push({rtp:[],fmtp:[]}),u=l[l.length-1]);for(var E=0;E<(i[f]||[]).length;E+=1){var k=i[f][E];if(k.reg.test(S))return r(k,u,S)}}),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}})})}}(AS);var rp=ul,v1=/%[sdv%]/g,T1=function(s){var t=1,e=arguments,r=e.length;return s.replace(v1,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""}})},yo=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 T1.apply(null,i)},y1=["v","o","s","i","u","e","p","c","b","t","r","z","a"],E1=["i","c","b","a"],b1=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||y1,r=t.innerOrder||E1,i=[];return e.forEach(function(n){rp[n].forEach(function(o){o.name in s&&s[o.name]!=null?i.push(yo(n,o,s)):o.push in s&&s[o.push]!=null&&s[o.push].forEach(function(c){i.push(yo(n,o,c))})})}),s.media.forEach(function(n){i.push(yo("m",rp.m[0],n)),r.forEach(function(o){rp[o].forEach(function(c){c.name in n&&n[c.name]!=null?i.push(yo(o,c,n)):c.push in n&&n[c.push]!=null&&n[c.push].forEach(function(d){i.push(yo(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 Om extends ft{constructor(e){super();p(this,"call");p(this,"timeOut");this.call=new Ks(e)}start(e=1e4){this.call.establishConnection(),this.timeOut=setTimeout(this.testFailed.bind(this),e)}testComplete(e){clearTimeout(this.timeOut),this.call.close(),this.emit("done",e)}testFailed(e){this.call.close(),this.emit("failed",e)}}const ny=8,ay=1/1e3;class oy extends Om{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(Ks.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)*ny/(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*ay)})}}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 Fu extends Om{constructor(e,r=Ks.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 cy extends Fu{constructor(t){super(t,Ks.isHost)}}class dy extends Fu{constructor(t){super(t,Ks.isRelay)}}class ly extends Fu{constructor(t){super(t,Ks.isReflexive)}}class uy{constructor(){p(this,"ipInformation",null)}async getIPDetails({peerId:t,apiHostnames:e,logger:r}){var i,n,o;if(!this.ipInformation){try{const c=`https://${e.location}`,l=await(await fetch(c)).json();if(((i=l.loc)==null?void 0:i.length)>5)return this.ipInformation=l,(n=this.ipInformation)!=null&&n.ip&&(this.ipInformation.ip=Mr(this.ipInformation.ip)),l;throw Error("Insufficient data")}catch(c){r.error("callstats::ipDetails:: failed to fetch ip using location service",{error:c})}try{const c=await fetch(`https://${e.locationLegacy}/?token=3c493932b0624c&peerId=${t}`,{method:"POST"});this.ipInformation=await c.json(),(o=this.ipInformation)!=null&&o.ip&&(this.ipInformation.ip=Mr(this.ipInformation.ip))}catch(c){r.error("callstats::ipDetails:: failed to fetch ip using legacy location service",{error:c})}}return this.ipInformation}resetCache(){this.ipInformation=null}}const Dm=new uy,Nm=[{urls:"turn:turn.dyte.in:443?transport=tcp",username:"dyte",credential:"dytein",credentialType:"password"},{urls:"turn:turn.dyte.in:3478?transport=udp",username:"dyte",credential:"dytein",credentialType:"password"}];function Lm(s){const[t,e]=s.split(",");return{coords:{latitude:Number(t),longitude:Number(e)}}}class Vm{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 xm extends ft{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,"ipDetails");p(this,"callStatsInstance");this.observer=new ft}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 C,I,R,U,N,x,B,q,Z,se,at,Ct,zt;const c=e,d=new Vm,l=r.length?new Set(r):void 0,u=[],h=[],f=[],S=new Map,E=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:T}=A,{selected:w}=A,F=A,ke={nominated:T!=null?T:w,currentRoundTripTime:F.currentRoundTripTime,totalRoundTripTime:F.totalRoundTripTime,bytesReceived:F.bytesReceived,bytesSent:F.bytesSent,availableOutgoingBitrate:F.availableOutgoingBitrate,availableIncomingBitrate:F.availableIncomingBitrate,lastPacketReceivedTimestamp:F.lastPacketReceivedTimestamp,lastPacketSentTimestamp:F.lastPacketSentTimestamp,localCandidateId:F.localCandidateId,remoteCandidateId:F.remoteCandidateId,bytesDiscardedOnSend:F.bytesDiscardedOnSend,packetsSent:F.packetsSent,packetsReceived:F.packetsReceived,packetsDiscardedOnSend:F.packetsDiscardedOnSend};f.push(ke),(A.nominated===!0||A.selected===!0)&&(d.candidatePair=ke);break}case"transport":{const T=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:T.bytesReceived,bytesSent:T.bytesSent,packetsSent:T.packetsSent,packetsReceived:T.packetsReceived,dtlsCipher:T.dtlsCipher,dtlsState:T.dtlsState,iceRole:T.iceRole};if(d.transport=w,o){if(o.producing){const F=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,F,w)}if(o.consuming){const F=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,F,w)}}break}case"remote-inbound-rtp":{const T=A,w={jitter:T.jitter,fractionLost:T.fractionLost,roundTripTime:T.roundTripTime,roundTripTimeMeasurements:T.roundTripTimeMeasurements,totalRoundTripTime:T.totalRoundTripTime,packetsLost:T.packetsLost};d.remoteInboundRtp.set(T.localId,w);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(A.id))break;const T=A,w=n||this.outboundProducerMap.get(A.id),F=this.pausedProducerMap.get(w);if(F){if(F.lastReportCalculated===!0)break;this.pausedProducerMap.set(w,{lastReportCalculated:!0})}this.overallProducersStatsMap[w]||(this.overallProducersStatsMap[w]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const ke=this.overallProducersStatsMap[w];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.outboundProducerMap.has(A.id)){d.staleProducerStreamMap=!0;break}const Le=this.callStatsInstance.producers.get(w);if(((C=Le==null?void 0:Le.track)==null?void 0:C.readyState)==="ended")break;d.producerStreamMap.has(w)||d.producerStreamMap.set(w,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const V={bytesSent:T.bytesSent,packetsSent:T.packetsSent,nackCount:T.nackCount,ssrc:T.ssrc,mid:T.mid,active:T.active,codecId:T.codecId,headerBytesSent:T.headerBytesSent||0,totalPacketSendDelay:T.totalPacketSendDelay||0};if(T.mediaType==="video"||T.kind==="video"){const k=T,Be={frameHeight:k.frameHeight,frameWidth:k.frameWidth,framesEncoded:k.framesEncoded,framesDropped:k.framesDropped,framesPerSecond:k.framesPerSecond,framesSent:k.framesSent,keyFramesEncoded:k.keyFramesEncoded,firCount:k.firCount,encoderImplementation:k.encoderImplementation,hugeFramesSent:k.hugeFramesSent,pliCount:k.pliCount,qpSum:k.qpSum,qualityLimitationDurations:k.qualityLimitationDurations,qualityLimitationReason:k.qualityLimitationReason,qualityLimitationResolutionChanges:k.qualityLimitationResolutionChanges,totalEncodeTime:k.targetBitrate,totalPacketSendDelay:k.totalPacketSendDelay,retransmittedBytesSent:k.retransmittedBytesSent,retransmittedPacketsSent:k.retransmittedPacketsSent,scalabilityMode:k.scalabilityMode,powerEfficientEncoder:k.powerEfficientEncoder,...V};d.outboundVideoRtp.set(A.id,Be),d.producerStreamMap.get(w).outboundVideoRtpId.push(A.id),this.processOutboundProducerVideoStats(w,ke,Be)}else if(T.mediaType==="audio"||T.kind==="audio"){const k=T,Be={retransmittedBytesSent:k.retransmittedBytesSent,retransmittedPacketsSent:k.retransmittedPacketsSent,...V};d.outboundAudioRtp.set(A.id,Be),d.producerStreamMap.get(w).outboundAudioRtpId.push(A.id),this.processOutboundProducerAudioStats(w,ke,Be)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(A.id))break;const T=A,w=n||this.inboundConsumerMap.get(A.id),F=this.pausedConsumerMap.get(w);if(F){if(F.lastReportCalculated===!0)break;this.pausedConsumerMap.set(w,{lastReportCalculated:!0})}if(T.ssrc===1234)break;this.overallConsumersStatsMap[w]||(this.overallConsumersStatsMap[w]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const ke=this.overallConsumersStatsMap[w];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.inboundConsumerMap.has(A.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(w)||d.consumerStreamMap.set(w,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Le={bytesReceived:T.bytesReceived,packetsReceived:T.packetsReceived,packetsLost:T.packetsLost>=0?T.packetsLost:0,jitter:T.jitter,nackCount:T.nackCount,jitterBufferDelay:T.jitterBufferDelay,jitterBufferEmittedCount:T.jitterBufferEmittedCount,lastPacketReceivedTimestamp:T.lastPacketReceivedTimestamp,ssrc:T.ssrc,mid:T.mid,codecId:T.codecId,headerBytesReceived:T.headerBytesReceived||0,packetsDiscarded:T.packetsDiscarded||0,jitterBufferMinimumDelay:T.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:T.jitterBufferTargetDelay||0};if(T.mediaType==="video"||T.kind==="video"){const V=T,k={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,...Le};k.score=Mm({frameWidth:k.frameWidth||0,framesDecoded:(k.framesDecoded||0)-(((I=this.videoConsumerToStatsMap.get(w))==null?void 0:I.framesDecoded)||0),framesPerSecond:k.framesPerSecond||0,packetsLost:(k.packetsLost||0)-(((R=this.videoConsumerToStatsMap.get(w))==null?void 0:R.packetsLost)||0),packetsReceived:(k.packetsReceived||0)-(((U=this.videoConsumerToStatsMap.get(w))==null?void 0:U.packetsReceived)||0),jitter:k.jitter||0,isScreenShare:this.screenShareConsumers.has(w)}),E.set(w,{score:+(k.score*10).toFixed(),frameWidth:k.frameWidth||0,frameHeight:k.frameHeight||0,framesPerSecond:k.framesPerSecond||0,packetsLostPercentage:yd({packetsLost:(k.packetsLost||0)-(((N=this.videoConsumerToStatsMap.get(w))==null?void 0:N.packetsLost)||0),packetsReceived:(k.packetsReceived||0)-(((x=this.videoConsumerToStatsMap.get(w))==null?void 0:x.packetsReceived)||0)}),jitter:k.jitter||0,isScreenShare:this.screenShareConsumers.has(w),bitrate:((k.bytesReceived||0)-(((B=this.videoConsumerToStatsMap.get(w))==null?void 0:B.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(w,k),d.inboundVideoRtp.set(A.id,k),d.consumerStreamMap.get(w).inboundVideoRtpId.push(A.id),this.processInboundConsumerVideoStats(w,ke,k)}else if(T.mediaType==="audio"||T.kind==="audio"){const V=T,k={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,...Le};k.score=Am({concealmentEvents:(k.concealmentEvents||0)-(((q=this.audioConsumerToStatsMap.get(w))==null?void 0:q.concealmentEvents)||0),packetsLost:(k.packetsLost||0)-(((Z=this.audioConsumerToStatsMap.get(w))==null?void 0:Z.packetsLost)||0),packetsReceived:(k.packetsReceived||0)-(((se=this.audioConsumerToStatsMap.get(w))==null?void 0:se.packetsReceived)||0),jitter:k.jitter||0}),E.set(w,{score:+(k.score*10).toFixed(),packetsLostPercentage:yd({packetsLost:(k.packetsLost||0)-(((at=this.audioConsumerToStatsMap.get(w))==null?void 0:at.packetsLost)||0),packetsReceived:(k.packetsReceived||0)-(((Ct=this.audioConsumerToStatsMap.get(w))==null?void 0:Ct.packetsReceived)||0)}),jitter:k.jitter||0,isScreenShare:this.screenShareConsumers.has(w),bitrate:((k.bytesReceived||0)-(((zt=this.audioConsumerToStatsMap.get(w))==null?void 0:zt.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(w,k),d.inboundAudioRtp.set(A.id,k),d.consumerStreamMap.get(w).inboundAudioRtpId.push(A.id),this.processInboundConsumerAudioStats(w,ke,k)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}}}if(d.producerStreamMap.forEach((A,T)=>{var w,F,ke,Le,V,k,Be,Wc,Jc,Kc,zc,Yc,Qc,Xc,Zc,ed,td,sd,rd,id,nd,ad,od;if(A.outboundVideoRtpId.length>0){const fe=[];A.outboundVideoRtpId.forEach(_p=>{fe.push(d.outboundVideoRtp.get(_p))});const ee=this.getWorkingSimulcastVideoStats(fe);ee.score=Rm({frameWidth:ee.frameWidth||0,framesPerSecond:ee.framesPerSecond||0,jitter:((w=ee.remoteData)==null?void 0:w.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsSent:(ee.packetsSent||0)-(((F=this.videoProducerToStatsMap.get(T))==null?void 0:F.packetsSent)||0),packetsLost:(((ke=ee.remoteData)==null?void 0:ke.packetsLost)||0)-(((V=(Le=this.videoProducerToStatsMap.get(T))==null?void 0:Le.remoteData)==null?void 0:V.packetsLost)||0),framesEncoded:(ee.framesEncoded||0)-(((k=this.videoProducerToStatsMap.get(T))==null?void 0:k.framesEncoded)||0)}),S.set(T,{score:+(ee.score*10).toFixed(),frameWidth:ee.frameWidth||0,frameHeight:ee.frameHeight||0,framesPerSecond:ee.framesPerSecond||0,jitter:((Be=ee.remoteData)==null?void 0:Be.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsLostPercentage:Td({packetsSent:(ee.packetsSent||0)-(((Wc=this.videoProducerToStatsMap.get(T))==null?void 0:Wc.packetsSent)||0),packetsLost:(((Jc=ee.remoteData)==null?void 0:Jc.packetsLost)||0)-(((zc=(Kc=this.videoProducerToStatsMap.get(T))==null?void 0:Kc.remoteData)==null?void 0:zc.packetsLost)||0)}),bitrate:((ee.bytesSent||0)-(((Yc=this.videoProducerToStatsMap.get(T))==null?void 0:Yc.bytesSent)||0))*8/7,cpuLimitations:ee.qualityLimitationReason==="cpu",bandwidthLimitations:ee.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(T,ee)}else if(A.outboundAudioRtpId.length>0){const fe=d.outboundAudioRtp.get(A.outboundAudioRtpId[0]);fe.score=Cm({packetsSent:(fe.packetsSent||0)-(((Qc=this.audioProducerToStatsMap.get(T))==null?void 0:Qc.packetsSent)||0),packetsLost:(((Xc=fe.remoteData)==null?void 0:Xc.packetsLost)||0)-(((ed=(Zc=this.audioProducerToStatsMap.get(T))==null?void 0:Zc.remoteData)==null?void 0:ed.packetsLost)||0),jitter:((td=fe.remoteData)==null?void 0:td.jitter)||0}),S.set(T,{score:+(fe.score*10).toFixed(),bitrate:((fe.bytesSent||0)-(((sd=this.audioProducerToStatsMap.get(T))==null?void 0:sd.bytesSent)||0))*8/7,packetsLostPercentage:Td({packetsSent:(fe.packetsSent||0)-(((rd=this.audioProducerToStatsMap.get(T))==null?void 0:rd.packetsSent)||0),packetsLost:(((id=fe.remoteData)==null?void 0:id.packetsLost)||0)-(((ad=(nd=this.audioProducerToStatsMap.get(T))==null?void 0:nd.remoteData)==null?void 0:ad.packetsLost)||0)}),jitter:((od=fe.remoteData)==null?void 0:od.jitter)||0,isScreenShare:this.screenShareProducers.has(T)}),this.audioProducerToStatsMap.set(T,fe)}}),f.forEach(A=>{const T=u.find(F=>F.id===A.localCandidateId?(A.localCandidateId=F.id,F):null),w=h.find(F=>F.id===A.remoteCandidateId?(A.remoteCandidateId=F.id,F):null);T&&(A.localCandidateType=T.type,A.localCandidateAddress=Mr(T.address),A.localCandidatePort=T.port,A.localCandidateProtocol=T.protocol,A.localCandidateUrl=T.url,A.localCandidateNetworkType=T.networkType,A.localCandidateRelatedAddress=Mr(T.relatedAddress),A.localCandidateRelatedPort=T.relatedPort),w&&(A.remoteCandidateType=w.type,A.remoteCandidateAddress=Mr(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=f),d.transport&&!d.transport.roundTripTime){let A=0,T=0;d.remoteInboundRtp.forEach((w,F)=>{w.roundTripTime&&w.roundTripTime>A&&(A=w.roundTripTime,T=w.totalRoundTripTime)}),d.transport.roundTripTime=A,d.transport.totalRoundTripTime=T}if(E.size>0)try{this.observer.emit("consumer_score",E)}catch(A){}if(S.size>0)try{this.observer.emit("producer_score",S)}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||Nm},i=new Promise((u,h)=>{try{const f=new cy(r);f.addListener("done",u),f.addListener("failed",()=>{u({connectivity:!1})}),f.start(2e3)}catch(f){h(f)}}),n=new Promise((u,h)=>{try{const f=new dy(r);f.addListener("done",u),f.addListener("failed",()=>{u({connectivity:!1})}),f.start(2e3)}catch(f){h(f)}}),o=new Promise((u,h)=>{try{const f=new ly(r);f.addListener("done",u),f.addListener("failed",()=>{u({connectivity:!1})}),f.start(2e3)}catch(f){h(f)}}),[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||Nm},d=new oy(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 getIPDetails(){var e,r;try{return this.ipDetails||(this.ipDetails=await Dm.getIPDetails({peerId:(e=this.callStatsInstance)==null?void 0:e.peerId,apiHostnames:(r=this.callStatsInstance)==null?void 0:r.apiHostnames,logger:this.callStatsInstance.logger})),this.ipDetails}catch(i){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 c,d;if(r){const l=await this.getIPDetails();return{ipDetails:l,effectiveNetworkType:(c=navigator.connection)==null?void 0:c.effectiveType,location:l!=null&&l.loc?Lm(l==null?void 0:l.loc):void 0}}const[i,n,o]=await Promise.all([this.getConnectivity(e),this.getThroughput(e),this.getIPDetails()]);return{ipDetails:o,effectiveNetworkType:(d=navigator.connection)==null?void 0:d.effectiveType,location:o!=null&&o.loc?Lm(o==null?void 0:o.loc):void 0,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 hy extends xm{}class Um extends xm{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 C,I,R,U,N,x,B,q,Z,se,at,Ct,zt;const c=e,d=new Vm,l=r.length?new Set(r):void 0,u=[],h=[],f=[],S=new Map,E=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:T}=A,{selected:w}=A,F=A,ke={nominated:T!=null?T:w,currentRoundTripTime:F.currentRoundTripTime,totalRoundTripTime:F.totalRoundTripTime,bytesReceived:F.bytesReceived,bytesSent:F.bytesSent,availableOutgoingBitrate:F.availableOutgoingBitrate,availableIncomingBitrate:F.availableIncomingBitrate,lastPacketReceivedTimestamp:F.lastPacketReceivedTimestamp,lastPacketSentTimestamp:F.lastPacketSentTimestamp,localCandidateId:F.localCandidateId,remoteCandidateId:F.remoteCandidateId,bytesDiscardedOnSend:F.bytesDiscardedOnSend,packetsSent:F.packetsSent,packetsReceived:F.packetsReceived,packetsDiscardedOnSend:F.packetsDiscardedOnSend};f.push(ke),(A.nominated===!0||A.selected===!0)&&(d.candidatePair=ke);break}case"transport":{const T=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:T.bytesReceived,bytesSent:T.bytesSent,packetsSent:T.packetsSent,packetsReceived:T.packetsReceived,dtlsCipher:T.dtlsCipher,dtlsState:T.dtlsState,iceRole:T.iceRole};if(d.transport=w,o){if(o.producing){const F=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,F,w)}if(o.consuming){const F=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,F,w)}}break}case"remote-inbound-rtp":{const T=A,w={jitter:T.jitter,fractionLost:T.fractionLost,roundTripTime:T.roundTripTime,roundTripTimeMeasurements:T.roundTripTimeMeasurements,totalRoundTripTime:T.totalRoundTripTime,packetsLost:T.packetsLost};d.remoteInboundRtp.set(T.localId,w);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(A.id))break;const T=A,w=n||this.outboundProducerMap.get(A.id),F=this.pausedProducerMap.get(w);if(F){if(F.lastReportCalculated===!0)break;this.pausedProducerMap.set(w,{lastReportCalculated:!0})}this.overallProducersStatsMap[w]||(this.overallProducersStatsMap[w]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const ke=this.overallProducersStatsMap[w];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.outboundProducerMap.has(A.id)){d.staleProducerStreamMap=!0;break}const Le=this.callStatsInstance.producers.get(w);if(((C=Le==null?void 0:Le.track)==null?void 0:C.readyState)==="ended")break;d.producerStreamMap.has(w)||d.producerStreamMap.set(w,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const V={bytesSent:T.bytesSent,packetsSent:T.packetsSent,nackCount:T.nackCount,ssrc:T.ssrc,mid:T.mid,active:T.active,codecId:T.codecId,headerBytesSent:T.headerBytesSent||0,totalPacketSendDelay:T.totalPacketSendDelay||0};if(T.mediaType==="video"||T.kind==="video"){const k=T,Be={frameHeight:k.frameHeight,frameWidth:k.frameWidth,framesEncoded:k.framesEncoded,framesDropped:k.framesDropped?k.framesDropped:k.droppedFrames,framesPerSecond:k.framesPerSecond?k.framesPerSecond:k.framerateMean,framesSent:k.framesSent,keyFramesEncoded:k.keyFramesEncoded,firCount:k.firCount,encoderImplementation:k.encoderImplementation,hugeFramesSent:k.hugeFramesSent,pliCount:k.pliCount,qpSum:k.qpSum,qualityLimitationReason:k.qualityLimitationReason,qualityLimitationDurations:k.qualityLimitationDurations,qualityLimitationResolutionChanges:k.qualityLimitationResolutionChanges,totalEncodeTime:k.totalEncodeTime,totalPacketSendDelay:k.totalEncodeTime,retransmittedBytesSent:k.retransmittedBytesSent,retransmittedPacketsSent:k.retransmittedPacketsSent,scalabilityMode:k.scalabilityMode,powerEfficientEncoder:k.powerEfficientEncoder,...V};d.outboundVideoRtp.set(A.id,Be),d.producerStreamMap.get(w).outboundVideoRtpId.push(A.id),this.processOutboundProducerVideoStats(w,ke,Be)}else if(T.mediaType==="audio"||T.kind==="audio"){const k=T,Be={retransmittedBytesSent:k.retransmittedBytesSent,retransmittedPacketsSent:k.retransmittedPacketsSent,...V};d.outboundAudioRtp.set(A.id,Be),d.producerStreamMap.get(w).outboundAudioRtpId.push(A.id),this.processOutboundProducerAudioStats(w,ke,Be)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(A.id))break;const T=A,w=n||this.inboundConsumerMap.get(A.id),F=this.pausedConsumerMap.get(w);if(F){if(F.lastReportCalculated===!0)break;this.pausedConsumerMap.set(w,{lastReportCalculated:!0})}if(T.ssrc===1234)break;this.overallConsumersStatsMap[w]||(this.overallConsumersStatsMap[w]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const ke=this.overallConsumersStatsMap[w];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.inboundConsumerMap.has(A.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(w)||d.consumerStreamMap.set(w,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Le={bytesReceived:T.bytesReceived,packetsReceived:T.packetsReceived,packetsLost:T.packetsLost>=0?T.packetsLost:0,jitter:T.jitter,nackCount:T.nackCount,jitterBufferDelay:T.jitterBufferDelay,jitterBufferEmittedCount:T.jitterBufferEmittedCount,lastPacketReceivedTimestamp:T.lastPacketReceivedTimestamp,ssrc:T.ssrc,mid:T.mid,codecId:T.codecId,headerBytesReceived:T.headerBytesReceived||0,packetsDiscarded:T.packetsDiscarded||0,jitterBufferMinimumDelay:T.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:T.jitterBufferTargetDelay||0};if(T.mediaType==="video"||T.kind==="video"){const V=T,k={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,...Le};k.score=Mm({frameWidth:k.frameWidth||0,framesDecoded:(k.framesDecoded||0)-(((I=this.videoConsumerToStatsMap.get(w))==null?void 0:I.framesDecoded)||0),framesPerSecond:k.framesPerSecond||0,packetsLost:(k.packetsLost||0)-(((R=this.videoConsumerToStatsMap.get(w))==null?void 0:R.packetsLost)||0),packetsReceived:(k.packetsReceived||0)-(((U=this.videoConsumerToStatsMap.get(w))==null?void 0:U.packetsReceived)||0),jitter:k.jitter||0,isScreenShare:this.screenShareConsumers.has(w)}),E.set(w,{score:+(k.score*10).toFixed(),frameWidth:k.frameWidth||0,frameHeight:k.frameHeight||0,framesPerSecond:k.framesPerSecond||0,packetsLostPercentage:yd({packetsLost:(k.packetsLost||0)-(((N=this.videoConsumerToStatsMap.get(w))==null?void 0:N.packetsLost)||0),packetsReceived:(k.packetsReceived||0)-(((x=this.videoConsumerToStatsMap.get(w))==null?void 0:x.packetsReceived)||0)}),jitter:k.jitter||0,isScreenShare:this.screenShareConsumers.has(w),bitrate:((k.bytesReceived||0)-(((B=this.videoConsumerToStatsMap.get(w))==null?void 0:B.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(w,k),d.inboundVideoRtp.set(A.id,k),d.consumerStreamMap.get(w).inboundVideoRtpId.push(A.id),this.processInboundConsumerVideoStats(w,ke,k)}else if(T.mediaType==="audio"||T.kind==="audio"){const V=T,k={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,...Le};k.score=Am({concealmentEvents:(k.concealmentEvents||0)-(((q=this.audioConsumerToStatsMap.get(w))==null?void 0:q.concealmentEvents)||0),packetsLost:(k.packetsLost||0)-(((Z=this.audioConsumerToStatsMap.get(w))==null?void 0:Z.packetsLost)||0),packetsReceived:(k.packetsReceived||0)-(((se=this.audioConsumerToStatsMap.get(w))==null?void 0:se.packetsReceived)||0),jitter:k.jitter||0}),E.set(w,{score:+(k.score*10).toFixed(),packetsLostPercentage:yd({packetsLost:(k.packetsLost||0)-(((at=this.audioConsumerToStatsMap.get(w))==null?void 0:at.packetsLost)||0),packetsReceived:(k.packetsReceived||0)-(((Ct=this.audioConsumerToStatsMap.get(w))==null?void 0:Ct.packetsReceived)||0)}),jitter:k.jitter||0,isScreenShare:this.screenShareConsumers.has(w),bitrate:((k.bytesReceived||0)-(((zt=this.audioConsumerToStatsMap.get(w))==null?void 0:zt.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(w,k),d.inboundAudioRtp.set(A.id,k),d.consumerStreamMap.get(w).inboundAudioRtpId.push(A.id),this.processInboundConsumerAudioStats(w,ke,k)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}}}if(d.producerStreamMap.forEach((A,T)=>{var w,F,ke,Le,V,k,Be,Wc,Jc,Kc,zc,Yc,Qc,Xc,Zc,ed,td,sd,rd,id,nd,ad,od;if(A.outboundVideoRtpId.length>0){const fe=[];A.outboundVideoRtpId.forEach(_p=>{fe.push(d.outboundVideoRtp.get(_p))});const ee=this.getWorkingSimulcastVideoStats(fe);ee.score=Rm({frameWidth:ee.frameWidth||0,framesPerSecond:ee.framesPerSecond||0,jitter:((w=ee.remoteData)==null?void 0:w.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsSent:(ee.packetsSent||0)-(((F=this.videoProducerToStatsMap.get(T))==null?void 0:F.packetsSent)||0),packetsLost:(((ke=ee.remoteData)==null?void 0:ke.packetsLost)||0)-(((V=(Le=this.videoProducerToStatsMap.get(T))==null?void 0:Le.remoteData)==null?void 0:V.packetsLost)||0),framesEncoded:(ee.framesEncoded||0)-(((k=this.videoProducerToStatsMap.get(T))==null?void 0:k.framesEncoded)||0)}),S.set(T,{score:+(ee.score*10).toFixed(),frameWidth:ee.frameWidth||0,frameHeight:ee.frameHeight||0,framesPerSecond:ee.framesPerSecond||0,jitter:((Be=ee.remoteData)==null?void 0:Be.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsLostPercentage:Td({packetsSent:(ee.packetsSent||0)-(((Wc=this.videoProducerToStatsMap.get(T))==null?void 0:Wc.packetsSent)||0),packetsLost:(((Jc=ee.remoteData)==null?void 0:Jc.packetsLost)||0)-(((zc=(Kc=this.videoProducerToStatsMap.get(T))==null?void 0:Kc.remoteData)==null?void 0:zc.packetsLost)||0)}),bitrate:((ee.bytesSent||0)-(((Yc=this.videoProducerToStatsMap.get(T))==null?void 0:Yc.bytesSent)||0))*8/7,cpuLimitations:ee.qualityLimitationReason==="cpu",bandwidthLimitations:ee.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(T,ee)}else if(A.outboundAudioRtpId.length>0){const fe=d.outboundAudioRtp.get(A.outboundAudioRtpId[0]);fe.score=Cm({packetsSent:(fe.packetsSent||0)-(((Qc=this.audioProducerToStatsMap.get(T))==null?void 0:Qc.packetsSent)||0),packetsLost:(((Xc=fe.remoteData)==null?void 0:Xc.packetsLost)||0)-(((ed=(Zc=this.audioProducerToStatsMap.get(T))==null?void 0:Zc.remoteData)==null?void 0:ed.packetsLost)||0),jitter:((td=fe.remoteData)==null?void 0:td.jitter)||0}),S.set(T,{score:+(fe.score*10).toFixed(),bitrate:((fe.bytesSent||0)-(((sd=this.audioProducerToStatsMap.get(T))==null?void 0:sd.bytesSent)||0))*8/7,packetsLostPercentage:Td({packetsSent:(fe.packetsSent||0)-(((rd=this.audioProducerToStatsMap.get(T))==null?void 0:rd.packetsSent)||0),packetsLost:(((id=fe.remoteData)==null?void 0:id.packetsLost)||0)-(((ad=(nd=this.audioProducerToStatsMap.get(T))==null?void 0:nd.remoteData)==null?void 0:ad.packetsLost)||0)}),jitter:((od=fe.remoteData)==null?void 0:od.jitter)||0,isScreenShare:this.screenShareProducers.has(T)}),this.audioProducerToStatsMap.set(T,fe)}}),f.forEach(A=>{const T=u.find(F=>F.id===A.localCandidateId?(A.localCandidateId=F.id,F):null),w=h.find(F=>F.id===A.remoteCandidateId?(A.remoteCandidateId=F.id,F):null);T&&(A.localCandidateType=T.type,A.localCandidateAddress=Mr(T.address),A.localCandidatePort=T.port,A.localCandidateProtocol=T.protocol,A.localCandidateUrl=T.url,A.localCandidateNetworkType=T.networkType,A.localCandidateRelatedAddress=Mr(T.relatedAddress),A.localCandidateRelatedPort=T.relatedPort),w&&(A.remoteCandidateType=w.type,A.remoteCandidateAddress=Mr(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=f),d.transport&&!d.transport.roundTripTime){let A=0,T=0;d.remoteInboundRtp.forEach((w,F)=>{w.roundTripTime&&w.roundTripTime>A&&(A=w.roundTripTime,T=w.totalRoundTripTime)}),d.transport.roundTripTime=A,d.transport.totalRoundTripTime=T}if(E.size>0)try{this.observer.emit("consumer_score",E)}catch(A){}if(S.size>0)try{this.observer.emit("producer_score",S)}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 f=this.consumerMap.get(i).track.getSettings(),S=e.inboundVideoRtp.get(u);return S.frameHeight||(S.frameHeight=f.height,S.frameWidth=f.width,S.framesPerSecond=f.frameRate),S});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 py extends Um{}function Pd(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 $m(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=>{Pd(this,t,e,o)}):n}catch(n){Pd(this,t,e,n)}return null},s}const z=(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=>{Pd(this,s,t,d)}):c}catch(c){Pd(this,s,t,c)}return null},i},my=(s,t)=>(e,r,i)=>{if(i)return $m(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,$m(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 j=class extends ft{constructor(e="https://api.testingv3.dyte.in",r="Blink",i=Tm.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 XT({logger:o,peerId:c,apiHostnames:d,authToken:l}),this.logger.debug("callStats::engineName: ",{engineName:r}),r){case"Blink":this.measurements=new hy;break;case"Gecko":this.measurements=new Um;break;case"WebKit":this.measurements=new py;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 ft,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&&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===Xt.AUDIO&&L.AUDIO_DEVICES_UPDATES||e===Xt.VIDEO&&L.VIDEO_DEVICES_UPDATES||e===Xt.SPEAKER&&L.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:r},timestamp:i})}selectedDevice(e,r,i){this.eventHandler.callEvent({event:e===Xt.AUDIO&&L.SELECTED_MICROHPONE_UPDATE||e===Xt.VIDEO&&L.SELECTED_CAMERA_UPDATE||e===Xt.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===Xt.AUDIO&&L.AUDIO_PLAY_FAILED||e===Xt.VIDEO&&L.VIDEO_PLAY_FAILED,metaData:{deviceType:e},timestamp:r})}mediaTrackMuted(e,r){this.eventHandler.callEvent({event:e===Xt.AUDIO&&L.AUDIO_TRACK_MUTED||e===Xt.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&&(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 l=await this.measurements.getConsumersReport([...this.consumers.values()]);n&&l?n.consumerReport=l:(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([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"registerIceServers",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"registerConsumer",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"registerProducer",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendConsumerSharedMediaStateEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"registerProducingTransport",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"registerConsumingTransport",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"deRegisterConsumer",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"deRegisterProducer",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"disconnectConsumingTransport",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"disconnectProducingTransport",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendPreCallTestBeginEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendScreenShareToggleEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendScreenShareRequestedEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendActiveSpeakerEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"devices",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"selectedDevice",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"mediaPermission",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"mediaPlaybackFailed",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"mediaTrackMuted",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"tabChanged",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"browserBackgrounded",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"browserForegrounded",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"legacySwitch",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"getPreCallTestResults",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendCallJoinBeginEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendNetworkQualityTestBeginEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendWebSocketConnectedEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendTransportConnectedEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendAudioToggleEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendVideoToggleEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendParticipantRoleToggleEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"startPingStats",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"stopPingStats",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendPingStatsEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerRebufferEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerAudioBlockEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerPlaybackBlockedEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerNetworkUnavailableEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerInitializedEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerWorkerErrorEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerErrorEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerRecoverableErrorEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerAnalyticsEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerQualityChanged",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendPlayerLiveLatency",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendDisconnectEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendReconnectEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"expectedVideoResolution",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"expectedScreenshareResolution",null),j=J([my(TypeError,(s,t)=>K.error(t,s))],j);const gy=j;class Bm extends ft{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,"ipInformation");p(this,"logger")}async initialize({peerId:e,engineName:r,env:i=Tm.PROD,iceServers:n,apiBase:o="https://api.cluster.dyte.in",flags:c,logger:d=console,apiHostnames:l,skipConnectivityChecks:u=!1,authToken:h}){var f,S,E;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.ipInformation=await Dm.getIPDetails({peerId:e,apiHostnames:l,logger:d}),this.backend=new gy(o,r,i,c,d,e,l,h),this.iceServers=n,(f=this.backend)==null||f.registerIceServers(this.iceServers),this.initialized=!0,(E=(S=this.backend)==null?void 0:S.eventHandler)==null||E.emit("initialized",this.ipInformation),this.emit("initialized",this.ipInformation),this.startPreCallTest(u)}catch(C){this.logger.error("callStats::CallStatsIntegration",{peerId:this.peerId,error:C instanceof Error?C.message:String(C),stack:C instanceof Error?C.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;(r=this.backend)==null||r.eventHandler.once("precall_end",e)}),e}onReceivingConsumerAudioStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_audio_status",e)})}onReceivingConsumerVideoStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_video_status",e)})}onReceivingProducerAudioStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_audio_status",e)})}onReceivingProducerVideoStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_video_status",e)})}onReceivingProducingTransportStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producing_transport_status",e)})}onReceivingConsumingTransportStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consuming_transport_status",e)})}onProducerScore(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_score",e)})}onConsumerScore(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_score",e)})}onSafeInitialization(e){if(this.initialized)e(this.ipInformation,!1);else if(!this.stalled){const r=i=>{e(i,!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,f,S,E,C;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":(f=this.backend)==null||f.sendIVSPlayerRecoverableErrorEvent(r,i);break;case"PlayerAnalyticsEvent":(S=this.backend)==null||S.sendIVSPlayerAnalyticsEvent(r,i);break;case"PlayerPlaybackRateChanged":(E=this.backend)==null||E.sendIVSPlayerPlaybackRateChangedEvent(r,i);break;case"PlayerQualityChanged":(C=this.backend)==null||C.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 Bm().setMaxListeners(30);class fy{constructor(){m(this,Do,void 0)}get telemetry(){var t;return(t=a(this,Do))==null?void 0:t.getValue("telemetry")}init(t){g(this,Do,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)}}Do=new WeakMap;function Fm(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 Ya(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=>Fm(s,r,t,c))}catch(o){Fm(s,r,t,o)}}),i.length>0}class Mn extends ft.EventEmitter{constructor(e){super();p(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return Ya(this,"*",[e,...r],this.logger),Ya(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 Lt extends ft.EventEmitter{constructor(e){super();p(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return Ya(this,"*",[e,...r],this.logger),Ya(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 Sy extends ft.EventEmitter{constructor(e){super();m(this,ur,void 0);m(this,hr,void 0);p(this,"asyncPromiseTimeout");p(this,"logger");this.logger=e,g(this,ur,new Map),g(this,hr,new Map),this.asyncPromiseTimeout=8e3}emit(e,...r){return Ya(this,e,r,this.logger)}async emitAsync(e,...r){a(this,ur).set(e,[]);const i=a(this,hr).get(e).map(()=>new Promise(n=>{a(this,ur).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,ur).delete(e)}onAsync(e,r){const i=a(this,ur),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,hr).get(e)||a(this,hr).set(e,[]),a(this,hr).get(e).push(n),super.on(e,n)}reset(){g(this,ur,new Map),g(this,hr,new Map),super.removeAllListeners()}}ur=new WeakMap,hr=new WeakMap;var vy=typeof global=="object"&&global&&global.Object===Object&&global;const Hm=vy;var Ty=typeof self=="object"&&self&&self.Object===Object&&self,yy=Hm||Ty||Function("return this")();const hs=yy;var Ey=hs.Symbol;const Rs=Ey;var qm=Object.prototype,by=qm.hasOwnProperty,wy=qm.toString,Qa=Rs?Rs.toStringTag:void 0;function Py(s){var t=by.call(s,Qa),e=s[Qa];try{s[Qa]=void 0;var r=!0}catch(n){}var i=wy.call(s);return r&&(t?s[Qa]=e:delete s[Qa]),i}var _y=Object.prototype,ky=_y.toString;function Cy(s){return ky.call(s)}var Ry="[object Null]",Iy="[object Undefined]",jm=Rs?Rs.toStringTag:void 0;function Ti(s){return s==null?s===void 0?Iy:Ry:jm&&jm in Object(s)?Py(s):Cy(s)}function Is(s){return s!=null&&typeof s=="object"}var Ay="[object Symbol]";function _d(s){return typeof s=="symbol"||Is(s)&&Ti(s)==Ay}function My(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 Oy=Array.isArray;const Vt=Oy;var Dy=1/0,Gm=Rs?Rs.prototype:void 0,Wm=Gm?Gm.toString:void 0;function Jm(s){if(typeof s=="string")return s;if(Vt(s))return My(s,Jm)+"";if(_d(s))return Wm?Wm.call(s):"";var t=s+"";return t=="0"&&1/s==-Dy?"-0":t}var Ny=/\s/;function Ly(s){for(var t=s.length;t--&&Ny.test(s.charAt(t)););return t}var Vy=/^\s+/;function xy(s){return s&&s.slice(0,Ly(s)+1).replace(Vy,"")}function Zt(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var Km=0/0,Uy=/^[-+]0x[0-9a-f]+$/i,$y=/^0b[01]+$/i,By=/^0o[0-7]+$/i,Fy=parseInt;function zm(s){if(typeof s=="number")return s;if(_d(s))return Km;if(Zt(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=Zt(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=xy(s);var e=$y.test(s);return e||By.test(s)?Fy(s.slice(2),e?2:8):Uy.test(s)?Km:+s}function Hu(s){return s}var Hy="[object AsyncFunction]",qy="[object Function]",jy="[object GeneratorFunction]",Gy="[object Proxy]";function qu(s){if(!Zt(s))return!1;var t=Ti(s);return t==qy||t==jy||t==Hy||t==Gy}var Wy=hs["__core-js_shared__"];const ju=Wy;var Ym=function(){var s=/[^.]+$/.exec(ju&&ju.keys&&ju.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function Jy(s){return!!Ym&&Ym in s}var Ky=Function.prototype,zy=Ky.toString;function yi(s){if(s!=null){try{return zy.call(s)}catch(t){}try{return s+""}catch(t){}}return""}var Yy=/[\\^$.*+?()[\]{}|]/g,Qy=/^\[object .+?Constructor\]$/,Xy=Function.prototype,Zy=Object.prototype,eE=Xy.toString,tE=Zy.hasOwnProperty,sE=RegExp("^"+eE.call(tE).replace(Yy,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function rE(s){if(!Zt(s)||Jy(s))return!1;var t=qu(s)?sE:Qy;return t.test(yi(s))}function iE(s,t){return s==null?void 0:s[t]}function Ei(s,t){var e=iE(s,t);return rE(e)?e:void 0}var nE=Ei(hs,"WeakMap");const Gu=nE;var Qm=Object.create,aE=function(){function s(){}return function(t){if(!Zt(t))return{};if(Qm)return Qm(t);s.prototype=t;var e=new s;return s.prototype=void 0,e}}();const oE=aE;function cE(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 dE(){}function Xm(s,t){var e=-1,r=s.length;for(t||(t=Array(r));++e<r;)t[e]=s[e];return t}var lE=800,uE=16,hE=Date.now;function pE(s){var t=0,e=0;return function(){var r=hE(),i=uE-(r-e);if(e=r,i>0){if(++t>=lE)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}function mE(s){return function(){return s}}var gE=function(){try{var s=Ei(Object,"defineProperty");return s({},"",{}),s}catch(t){}}();const kd=gE;var fE=kd?function(s,t){return kd(s,"toString",{configurable:!0,enumerable:!1,value:mE(t),writable:!0})}:Hu,SE=pE(fE);const vE=SE;function TE(s,t){for(var e=-1,r=s==null?0:s.length;++e<r&&t(s[e],e,s)!==!1;);return s}function yE(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 EE(s){return s!==s}function bE(s,t,e){for(var r=e-1,i=s.length;++r<i;)if(s[r]===t)return r;return-1}function wE(s,t,e){return t===t?bE(s,t,e):yE(s,EE,e)}function PE(s,t){var e=s==null?0:s.length;return!!e&&wE(s,t,0)>-1}var _E=9007199254740991,kE=/^(?:0|[1-9]\d*)$/;function Wu(s,t){var e=typeof s;return t=t==null?_E:t,!!t&&(e=="number"||e!="symbol"&&kE.test(s))&&s>-1&&s%1==0&&s<t}function Ju(s,t,e){t=="__proto__"&&kd?kd(s,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):s[t]=e}function Xa(s,t){return s===t||s!==s&&t!==t}var CE=Object.prototype,RE=CE.hasOwnProperty;function Zm(s,t,e){var r=s[t];(!(RE.call(s,t)&&Xa(r,e))||e===void 0&&!(t in s))&&Ju(s,t,e)}function Za(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?Ju(e,c,d):Zm(e,c,d)}return e}var eg=Math.max;function IE(s,t,e){return t=eg(t===void 0?s.length-1:t,0),function(){for(var r=arguments,i=-1,n=eg(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),cE(s,this,c)}}function AE(s,t){return vE(IE(s,t,Hu),s+"")}var ME=9007199254740991;function Ku(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=ME}function eo(s){return s!=null&&Ku(s.length)&&!qu(s)}function OE(s,t,e){if(!Zt(e))return!1;var r=typeof t;return(r=="number"?eo(e)&&Wu(t,e.length):r=="string"&&t in e)?Xa(e[t],s):!1}function DE(s){return AE(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&&OE(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 NE=Object.prototype;function Cd(s){var t=s&&s.constructor,e=typeof t=="function"&&t.prototype||NE;return s===e}function LE(s,t){for(var e=-1,r=Array(s);++e<s;)r[e]=t(e);return r}var VE="[object Arguments]";function tg(s){return Is(s)&&Ti(s)==VE}var sg=Object.prototype,xE=sg.hasOwnProperty,UE=sg.propertyIsEnumerable,$E=tg(function(){return arguments}())?tg:function(s){return Is(s)&&xE.call(s,"callee")&&!UE.call(s,"callee")};const to=$E;function BE(){return!1}var rg=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ig=rg&&typeof module=="object"&&module&&!module.nodeType&&module,FE=ig&&ig.exports===rg,ng=FE?hs.Buffer:void 0,HE=ng?ng.isBuffer:void 0,qE=HE||BE;const On=qE;var jE="[object Arguments]",GE="[object Array]",WE="[object Boolean]",JE="[object Date]",KE="[object Error]",zE="[object Function]",YE="[object Map]",QE="[object Number]",XE="[object Object]",ZE="[object RegExp]",eb="[object Set]",tb="[object String]",sb="[object WeakMap]",rb="[object ArrayBuffer]",ib="[object DataView]",nb="[object Float32Array]",ab="[object Float64Array]",ob="[object Int8Array]",cb="[object Int16Array]",db="[object Int32Array]",lb="[object Uint8Array]",ub="[object Uint8ClampedArray]",hb="[object Uint16Array]",pb="[object Uint32Array]",be={};be[nb]=be[ab]=be[ob]=be[cb]=be[db]=be[lb]=be[ub]=be[hb]=be[pb]=!0,be[jE]=be[GE]=be[rb]=be[WE]=be[ib]=be[JE]=be[KE]=be[zE]=be[YE]=be[QE]=be[XE]=be[ZE]=be[eb]=be[tb]=be[sb]=!1;function mb(s){return Is(s)&&Ku(s.length)&&!!be[Ti(s)]}function zu(s){return function(t){return s(t)}}var ag=typeof exports=="object"&&exports&&!exports.nodeType&&exports,so=ag&&typeof module=="object"&&module&&!module.nodeType&&module,gb=so&&so.exports===ag,Yu=gb&&Hm.process,fb=function(){try{var s=so&&so.require&&so.require("util").types;return s||Yu&&Yu.binding&&Yu.binding("util")}catch(t){}}();const Dn=fb;var og=Dn&&Dn.isTypedArray,Sb=og?zu(og):mb;const Rd=Sb;var vb=Object.prototype,Tb=vb.hasOwnProperty;function cg(s,t){var e=Vt(s),r=!e&&to(s),i=!e&&!r&&On(s),n=!e&&!r&&!i&&Rd(s),o=e||r||i||n,c=o?LE(s.length,String):[],d=c.length;for(var l in s)(t||Tb.call(s,l))&&!(o&&(l=="length"||i&&(l=="offset"||l=="parent")||n&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||Wu(l,d)))&&c.push(l);return c}function dg(s,t){return function(e){return s(t(e))}}var yb=dg(Object.keys,Object);const Eb=yb;var bb=Object.prototype,wb=bb.hasOwnProperty;function lg(s){if(!Cd(s))return Eb(s);var t=[];for(var e in Object(s))wb.call(s,e)&&e!="constructor"&&t.push(e);return t}function Id(s){return eo(s)?cg(s):lg(s)}function Pb(s){var t=[];if(s!=null)for(var e in Object(s))t.push(e);return t}var _b=Object.prototype,kb=_b.hasOwnProperty;function Cb(s){if(!Zt(s))return Pb(s);var t=Cd(s),e=[];for(var r in s)r=="constructor"&&(t||!kb.call(s,r))||e.push(r);return e}function ro(s){return eo(s)?cg(s,!0):Cb(s)}var Rb=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ib=/^\w*$/;function Qu(s,t){if(Vt(s))return!1;var e=typeof s;return e=="number"||e=="symbol"||e=="boolean"||s==null||_d(s)?!0:Ib.test(s)||!Rb.test(s)||t!=null&&s in Object(t)}var Ab=Ei(Object,"create");const io=Ab;function Mb(){this.__data__=io?io(null):{},this.size=0}function Ob(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var Db="__lodash_hash_undefined__",Nb=Object.prototype,Lb=Nb.hasOwnProperty;function Vb(s){var t=this.__data__;if(io){var e=t[s];return e===Db?void 0:e}return Lb.call(t,s)?t[s]:void 0}var xb=Object.prototype,Ub=xb.hasOwnProperty;function $b(s){var t=this.__data__;return io?t[s]!==void 0:Ub.call(t,s)}var Bb="__lodash_hash_undefined__";function Fb(s,t){var e=this.__data__;return this.size+=this.has(s)?0:1,e[s]=io&&t===void 0?Bb:t,this}function bi(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])}}bi.prototype.clear=Mb,bi.prototype.delete=Ob,bi.prototype.get=Vb,bi.prototype.has=$b,bi.prototype.set=Fb;function Hb(){this.__data__=[],this.size=0}function Ad(s,t){for(var e=s.length;e--;)if(Xa(s[e][0],t))return e;return-1}var qb=Array.prototype,jb=qb.splice;function Gb(s){var t=this.__data__,e=Ad(t,s);if(e<0)return!1;var r=t.length-1;return e==r?t.pop():jb.call(t,e,1),--this.size,!0}function Wb(s){var t=this.__data__,e=Ad(t,s);return e<0?void 0:t[e][1]}function Jb(s){return Ad(this.__data__,s)>-1}function Kb(s,t){var e=this.__data__,r=Ad(e,s);return r<0?(++this.size,e.push([s,t])):e[r][1]=t,this}function zs(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])}}zs.prototype.clear=Hb,zs.prototype.delete=Gb,zs.prototype.get=Wb,zs.prototype.has=Jb,zs.prototype.set=Kb;var zb=Ei(hs,"Map");const no=zb;function Yb(){this.size=0,this.__data__={hash:new bi,map:new(no||zs),string:new bi}}function Qb(s){var t=typeof s;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?s!=="__proto__":s===null}function Md(s,t){var e=s.__data__;return Qb(t)?e[typeof t=="string"?"string":"hash"]:e.map}function Xb(s){var t=Md(this,s).delete(s);return this.size-=t?1:0,t}function Zb(s){return Md(this,s).get(s)}function ew(s){return Md(this,s).has(s)}function tw(s,t){var e=Md(this,s),r=e.size;return e.set(s,t),this.size+=e.size==r?0:1,this}function Ys(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])}}Ys.prototype.clear=Yb,Ys.prototype.delete=Xb,Ys.prototype.get=Zb,Ys.prototype.has=ew,Ys.prototype.set=tw;var sw="Expected a function";function Xu(s,t){if(typeof s!="function"||t!=null&&typeof t!="function")throw new TypeError(sw);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(Xu.Cache||Ys),e}Xu.Cache=Ys;var rw=500;function iw(s){var t=Xu(s,function(r){return e.size===rw&&e.clear(),r}),e=t.cache;return t}var nw=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,aw=/\\(\\)?/g,ow=iw(function(s){var t=[];return s.charCodeAt(0)===46&&t.push(""),s.replace(nw,function(e,r,i,n){t.push(i?n.replace(aw,"$1"):r||e)}),t});const cw=ow;function dw(s){return s==null?"":Jm(s)}function ug(s,t){return Vt(s)?s:Qu(s,t)?[s]:cw(dw(s))}var lw=1/0;function Od(s){if(typeof s=="string"||_d(s))return s;var t=s+"";return t=="0"&&1/s==-lw?"-0":t}function hg(s,t){t=ug(t,s);for(var e=0,r=t.length;s!=null&&e<r;)s=s[Od(t[e++])];return e&&e==r?s:void 0}function uw(s,t,e){var r=s==null?void 0:hg(s,t);return r===void 0?e:r}function pg(s,t){for(var e=-1,r=t.length,i=s.length;++e<r;)s[i+e]=t[e];return s}var hw=dg(Object.getPrototypeOf,Object);const Zu=hw;var pw="[object Object]",mw=Function.prototype,gw=Object.prototype,mg=mw.toString,fw=gw.hasOwnProperty,Sw=mg.call(Object);function vw(s){if(!Is(s)||Ti(s)!=pw)return!1;var t=Zu(s);if(t===null)return!0;var e=fw.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&mg.call(e)==Sw}function Tw(){this.__data__=new zs,this.size=0}function yw(s){var t=this.__data__,e=t.delete(s);return this.size=t.size,e}function Ew(s){return this.__data__.get(s)}function bw(s){return this.__data__.has(s)}var ww=200;function Pw(s,t){var e=this.__data__;if(e instanceof zs){var r=e.__data__;if(!no||r.length<ww-1)return r.push([s,t]),this.size=++e.size,this;e=this.__data__=new Ys(r)}return e.set(s,t),this.size=e.size,this}function ps(s){var t=this.__data__=new zs(s);this.size=t.size}ps.prototype.clear=Tw,ps.prototype.delete=yw,ps.prototype.get=Ew,ps.prototype.has=bw,ps.prototype.set=Pw;function _w(s,t){return s&&Za(t,Id(t),s)}function kw(s,t){return s&&Za(t,ro(t),s)}var gg=typeof exports=="object"&&exports&&!exports.nodeType&&exports,fg=gg&&typeof module=="object"&&module&&!module.nodeType&&module,Cw=fg&&fg.exports===gg,Sg=Cw?hs.Buffer:void 0,vg=Sg?Sg.allocUnsafe:void 0;function Tg(s,t){if(t)return s.slice();var e=s.length,r=vg?vg(e):new s.constructor(e);return s.copy(r),r}function Rw(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 yg(){return[]}var Iw=Object.prototype,Aw=Iw.propertyIsEnumerable,Eg=Object.getOwnPropertySymbols,Mw=Eg?function(s){return s==null?[]:(s=Object(s),Rw(Eg(s),function(t){return Aw.call(s,t)}))}:yg;const eh=Mw;function Ow(s,t){return Za(s,eh(s),t)}var Dw=Object.getOwnPropertySymbols,Nw=Dw?function(s){for(var t=[];s;)pg(t,eh(s)),s=Zu(s);return t}:yg;const bg=Nw;function Lw(s,t){return Za(s,bg(s),t)}function wg(s,t,e){var r=t(s);return Vt(s)?r:pg(r,e(s))}function th(s){return wg(s,Id,eh)}function Vw(s){return wg(s,ro,bg)}var xw=Ei(hs,"DataView");const sh=xw;var Uw=Ei(hs,"Promise");const rh=Uw;var $w=Ei(hs,"Set");const Nn=$w;var Pg="[object Map]",Bw="[object Object]",_g="[object Promise]",kg="[object Set]",Cg="[object WeakMap]",Rg="[object DataView]",Fw=yi(sh),Hw=yi(no),qw=yi(rh),jw=yi(Nn),Gw=yi(Gu),wi=Ti;(sh&&wi(new sh(new ArrayBuffer(1)))!=Rg||no&&wi(new no)!=Pg||rh&&wi(rh.resolve())!=_g||Nn&&wi(new Nn)!=kg||Gu&&wi(new Gu)!=Cg)&&(wi=function(s){var t=Ti(s),e=t==Bw?s.constructor:void 0,r=e?yi(e):"";if(r)switch(r){case Fw:return Rg;case Hw:return Pg;case qw:return _g;case jw:return kg;case Gw:return Cg}return t});const Ln=wi;var Ww=Object.prototype,Jw=Ww.hasOwnProperty;function Kw(s){var t=s.length,e=new s.constructor(t);return t&&typeof s[0]=="string"&&Jw.call(s,"index")&&(e.index=s.index,e.input=s.input),e}var zw=hs.Uint8Array;const Dd=zw;function ih(s){var t=new s.constructor(s.byteLength);return new Dd(t).set(new Dd(s)),t}function Yw(s,t){var e=t?ih(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.byteLength)}var Qw=/\w*$/;function Xw(s){var t=new s.constructor(s.source,Qw.exec(s));return t.lastIndex=s.lastIndex,t}var Ig=Rs?Rs.prototype:void 0,Ag=Ig?Ig.valueOf:void 0;function Zw(s){return Ag?Object(Ag.call(s)):{}}function Mg(s,t){var e=t?ih(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.length)}var eP="[object Boolean]",tP="[object Date]",sP="[object Map]",rP="[object Number]",iP="[object RegExp]",nP="[object Set]",aP="[object String]",oP="[object Symbol]",cP="[object ArrayBuffer]",dP="[object DataView]",lP="[object Float32Array]",uP="[object Float64Array]",hP="[object Int8Array]",pP="[object Int16Array]",mP="[object Int32Array]",gP="[object Uint8Array]",fP="[object Uint8ClampedArray]",SP="[object Uint16Array]",vP="[object Uint32Array]";function TP(s,t,e){var r=s.constructor;switch(t){case cP:return ih(s);case eP:case tP:return new r(+s);case dP:return Yw(s,e);case lP:case uP:case hP:case pP:case mP:case gP:case fP:case SP:case vP:return Mg(s,e);case sP:return new r;case rP:case aP:return new r(s);case iP:return Xw(s);case nP:return new r;case oP:return Zw(s)}}function Og(s){return typeof s.constructor=="function"&&!Cd(s)?oE(Zu(s)):{}}var yP="[object Map]";function EP(s){return Is(s)&&Ln(s)==yP}var Dg=Dn&&Dn.isMap,bP=Dg?zu(Dg):EP;const wP=bP;var PP="[object Set]";function _P(s){return Is(s)&&Ln(s)==PP}var Ng=Dn&&Dn.isSet,kP=Ng?zu(Ng):_P;const CP=kP;var RP=1,IP=2,AP=4,Lg="[object Arguments]",MP="[object Array]",OP="[object Boolean]",DP="[object Date]",NP="[object Error]",Vg="[object Function]",LP="[object GeneratorFunction]",VP="[object Map]",xP="[object Number]",xg="[object Object]",UP="[object RegExp]",$P="[object Set]",BP="[object String]",FP="[object Symbol]",HP="[object WeakMap]",qP="[object ArrayBuffer]",jP="[object DataView]",GP="[object Float32Array]",WP="[object Float64Array]",JP="[object Int8Array]",KP="[object Int16Array]",zP="[object Int32Array]",YP="[object Uint8Array]",QP="[object Uint8ClampedArray]",XP="[object Uint16Array]",ZP="[object Uint32Array]",Se={};Se[Lg]=Se[MP]=Se[qP]=Se[jP]=Se[OP]=Se[DP]=Se[GP]=Se[WP]=Se[JP]=Se[KP]=Se[zP]=Se[VP]=Se[xP]=Se[xg]=Se[UP]=Se[$P]=Se[BP]=Se[FP]=Se[YP]=Se[QP]=Se[XP]=Se[ZP]=!0,Se[NP]=Se[Vg]=Se[HP]=!1;function ao(s,t,e,r,i,n){var o,c=t&RP,d=t&IP,l=t&AP;if(e&&(o=i?e(s,r,i,n):e(s)),o!==void 0)return o;if(!Zt(s))return s;var u=Vt(s);if(u){if(o=Kw(s),!c)return Xm(s,o)}else{var h=Ln(s),f=h==Vg||h==LP;if(On(s))return Tg(s,c);if(h==xg||h==Lg||f&&!i){if(o=d||f?{}:Og(s),!c)return d?Lw(s,kw(o,s)):Ow(s,_w(o,s))}else{if(!Se[h])return i?s:{};o=TP(s,h,c)}}n||(n=new ps);var S=n.get(s);if(S)return S;n.set(s,o),CP(s)?s.forEach(function(I){o.add(ao(I,t,e,I,s,n))}):wP(s)&&s.forEach(function(I,R){o.set(R,ao(I,t,e,R,s,n))});var E=l?d?Vw:th:d?ro:Id,C=u?void 0:E(s);return TE(C||s,function(I,R){C&&(R=I,I=s[R]),Zm(o,R,ao(I,t,e,R,s,n))}),o}var e_=4;function t_(s){return ao(s,e_)}var s_=1,r_=4;function nh(s){return ao(s,s_|r_)}var i_="__lodash_hash_undefined__";function n_(s){return this.__data__.set(s,i_),this}function a_(s){return this.__data__.has(s)}function oo(s){var t=-1,e=s==null?0:s.length;for(this.__data__=new Ys;++t<e;)this.add(s[t])}oo.prototype.add=oo.prototype.push=n_,oo.prototype.has=a_;function o_(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 Ug(s,t){return s.has(t)}var c_=1,d_=2;function $g(s,t,e,r,i,n){var o=e&c_,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,f=!0,S=e&d_?new oo:void 0;for(n.set(s,t),n.set(t,s);++h<c;){var E=s[h],C=t[h];if(r)var I=o?r(C,E,h,t,s,n):r(E,C,h,s,t,n);if(I!==void 0){if(I)continue;f=!1;break}if(S){if(!o_(t,function(R,U){if(!Ug(S,U)&&(E===R||i(E,R,e,r,n)))return S.push(U)})){f=!1;break}}else if(!(E===C||i(E,C,e,r,n))){f=!1;break}}return n.delete(s),n.delete(t),f}function l_(s){var t=-1,e=Array(s.size);return s.forEach(function(r,i){e[++t]=[i,r]}),e}function ah(s){var t=-1,e=Array(s.size);return s.forEach(function(r){e[++t]=r}),e}var u_=1,h_=2,p_="[object Boolean]",m_="[object Date]",g_="[object Error]",f_="[object Map]",S_="[object Number]",v_="[object RegExp]",T_="[object Set]",y_="[object String]",E_="[object Symbol]",b_="[object ArrayBuffer]",w_="[object DataView]",Bg=Rs?Rs.prototype:void 0,oh=Bg?Bg.valueOf:void 0;function P_(s,t,e,r,i,n,o){switch(e){case w_:if(s.byteLength!=t.byteLength||s.byteOffset!=t.byteOffset)return!1;s=s.buffer,t=t.buffer;case b_:return!(s.byteLength!=t.byteLength||!n(new Dd(s),new Dd(t)));case p_:case m_:case S_:return Xa(+s,+t);case g_:return s.name==t.name&&s.message==t.message;case v_:case y_:return s==t+"";case f_:var c=l_;case T_:var d=r&u_;if(c||(c=ah),s.size!=t.size&&!d)return!1;var l=o.get(s);if(l)return l==t;r|=h_,o.set(s,t);var u=$g(c(s),c(t),r,i,n,o);return o.delete(s),u;case E_:if(oh)return oh.call(s)==oh.call(t)}return!1}var __=1,k_=Object.prototype,C_=k_.hasOwnProperty;function R_(s,t,e,r,i,n){var o=e&__,c=th(s),d=c.length,l=th(t),u=l.length;if(d!=u&&!o)return!1;for(var h=d;h--;){var f=c[h];if(!(o?f in t:C_.call(t,f)))return!1}var S=n.get(s),E=n.get(t);if(S&&E)return S==t&&E==s;var C=!0;n.set(s,t),n.set(t,s);for(var I=o;++h<d;){f=c[h];var R=s[f],U=t[f];if(r)var N=o?r(U,R,f,t,s,n):r(R,U,f,s,t,n);if(!(N===void 0?R===U||i(R,U,e,r,n):N)){C=!1;break}I||(I=f=="constructor")}if(C&&!I){var x=s.constructor,B=t.constructor;x!=B&&"constructor"in s&&"constructor"in t&&!(typeof x=="function"&&x instanceof x&&typeof B=="function"&&B instanceof B)&&(C=!1)}return n.delete(s),n.delete(t),C}var I_=1,Fg="[object Arguments]",Hg="[object Array]",Nd="[object Object]",A_=Object.prototype,qg=A_.hasOwnProperty;function M_(s,t,e,r,i,n){var o=Vt(s),c=Vt(t),d=o?Hg:Ln(s),l=c?Hg:Ln(t);d=d==Fg?Nd:d,l=l==Fg?Nd:l;var u=d==Nd,h=l==Nd,f=d==l;if(f&&On(s)){if(!On(t))return!1;o=!0,u=!1}if(f&&!u)return n||(n=new ps),o||Rd(s)?$g(s,t,e,r,i,n):P_(s,t,d,e,r,i,n);if(!(e&I_)){var S=u&&qg.call(s,"__wrapped__"),E=h&&qg.call(t,"__wrapped__");if(S||E){var C=S?s.value():s,I=E?t.value():t;return n||(n=new ps),i(C,I,e,r,n)}}return f?(n||(n=new ps),R_(s,t,e,r,i,n)):!1}function Ld(s,t,e,r,i){return s===t?!0:s==null||t==null||!Is(s)&&!Is(t)?s!==s&&t!==t:M_(s,t,e,r,Ld,i)}var O_=1,D_=2;function N_(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 ps;if(r)var f=r(l,u,d,s,t,h);if(!(f===void 0?Ld(u,l,O_|D_,r,h):f))return!1}}return!0}function jg(s){return s===s&&!Zt(s)}function L_(s){for(var t=Id(s),e=t.length;e--;){var r=t[e],i=s[r];t[e]=[r,i,jg(i)]}return t}function Gg(s,t){return function(e){return e==null?!1:e[s]===t&&(t!==void 0||s in Object(e))}}function V_(s){var t=L_(s);return t.length==1&&t[0][2]?Gg(t[0][0],t[0][1]):function(e){return e===s||N_(e,s,t)}}function x_(s,t){return s!=null&&t in Object(s)}function U_(s,t,e){t=ug(t,s);for(var r=-1,i=t.length,n=!1;++r<i;){var o=Od(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&&Ku(i)&&Wu(o,i)&&(Vt(s)||to(s)))}function $_(s,t){return s!=null&&U_(s,t,x_)}var B_=1,F_=2;function H_(s,t){return Qu(s)&&jg(t)?Gg(Od(s),t):function(e){var r=uw(e,s);return r===void 0&&r===t?$_(e,s):Ld(t,r,B_|F_)}}function q_(s){return function(t){return t==null?void 0:t[s]}}function j_(s){return function(t){return hg(t,s)}}function G_(s){return Qu(s)?q_(Od(s)):j_(s)}function W_(s){return typeof s=="function"?s:s==null?Hu:typeof s=="object"?Vt(s)?H_(s[0],s[1]):V_(s):G_(s)}function J_(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 K_=J_();const z_=K_;var Y_=function(){return hs.Date.now()};const ch=Y_;var Q_="Expected a function",X_=Math.max,Z_=Math.min;function dh(s,t,e){var r,i,n,o,c,d,l=0,u=!1,h=!1,f=!0;if(typeof s!="function")throw new TypeError(Q_);t=zm(t)||0,Zt(e)&&(u=!!e.leading,h="maxWait"in e,n=h?X_(zm(e.maxWait)||0,t):n,f="trailing"in e?!!e.trailing:f);function S(q){var Z=r,se=i;return r=i=void 0,l=q,o=s.apply(se,Z),o}function E(q){return l=q,c=setTimeout(R,t),u?S(q):o}function C(q){var Z=q-d,se=q-l,at=t-Z;return h?Z_(at,n-se):at}function I(q){var Z=q-d,se=q-l;return d===void 0||Z>=t||Z<0||h&&se>=n}function R(){var q=ch();if(I(q))return U(q);c=setTimeout(R,C(q))}function U(q){return c=void 0,f&&r?S(q):(r=i=void 0,o)}function N(){c!==void 0&&clearTimeout(c),l=0,r=d=i=c=void 0}function x(){return c===void 0?o:U(ch())}function B(){var q=ch(),Z=I(q);if(r=arguments,i=this,d=q,Z){if(c===void 0)return E(d);if(h)return clearTimeout(c),c=setTimeout(R,t),S(d)}return c===void 0&&(c=setTimeout(R,t)),o}return B.cancel=N,B.flush=x,B}function lh(s,t,e){(e!==void 0&&!Xa(s[t],e)||e===void 0&&!(t in s))&&Ju(s,t,e)}function ek(s){return Is(s)&&eo(s)}function uh(s,t){if(!(t==="constructor"&&typeof s[t]=="function")&&t!="__proto__")return s[t]}function tk(s){return Za(s,ro(s))}function sk(s,t,e,r,i,n,o){var c=uh(s,e),d=uh(t,e),l=o.get(d);if(l){lh(s,e,l);return}var u=n?n(c,d,e+"",s,t,o):void 0,h=u===void 0;if(h){var f=Vt(d),S=!f&&On(d),E=!f&&!S&&Rd(d);u=d,f||S||E?Vt(c)?u=c:ek(c)?u=Xm(c):S?(h=!1,u=Tg(d,!0)):E?(h=!1,u=Mg(d,!0)):u=[]:vw(d)||to(d)?(u=c,to(c)?u=tk(c):(!Zt(c)||qu(c))&&(u=Og(d))):h=!1}h&&(o.set(d,u),i(u,d,r,n,o),o.delete(d)),lh(s,e,u)}function Wg(s,t,e,r,i){s!==t&&z_(t,function(n,o){if(i||(i=new ps),Zt(n))sk(s,t,o,e,Wg,r,i);else{var c=r?r(uh(s,o),n,o+"",s,t,i):void 0;c===void 0&&(c=n),lh(s,o,c)}},ro)}function rk(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 ik="[object Map]",nk="[object Set]",ak=Object.prototype,ok=ak.hasOwnProperty;function ck(s){if(s==null)return!0;if(eo(s)&&(Vt(s)||typeof s=="string"||typeof s.splice=="function"||On(s)||Rd(s)||to(s)))return!s.length;var t=Ln(s);if(t==ik||t==nk)return!s.size;if(Cd(s))return!lg(s).length;for(var e in s)if(ok.call(s,e))return!1;return!0}function dk(s,t){return Ld(s,t)}var lk=DE(function(s,t,e){Wg(s,t,e)});const Or=lk;var uk=1/0,hk=Nn&&1/ah(new Nn([,-0]))[1]==uk?function(s){return new Nn(s)}:dE;const pk=hk;var mk=200;function Jg(s,t,e){var r=-1,i=PE,n=s.length,o=!0,c=[],d=c;if(e)o=!1,i=rk;else if(n>=mk){var l=t?null:pk(s);if(l)return ah(l);o=!1,i=Ug,d=new oo}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 f=d.length;f--;)if(d[f]===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 gk(s){return s&&s.length?Jg(s):[]}function fk(s,t){return s&&s.length?Jg(s,W_(t)):[]}function Vd(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 Sk={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},Kg={STAGING:"staging",PROD:"prod"},vk={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 co(s,t){const e=s.getValue("overrides");return e&&e[t]?e[t]:!1}function Tk({baseURI:s}){return s.includes("staging.realtime")?Kg.STAGING:Kg.PROD}function xd({servicePrefix:s,baseURI:t}){return`${s}.${t}`}function hh({servicePrefix:s,baseURI:t}){const e=s==="ws"?"wss":"https",r=xd({servicePrefix:"api",baseURI:t});return`${e}://${r}/${s}`}function yk(s){const t=s.getValue("baseURI");return{location:xd({servicePrefix:"location",baseURI:t}),locationLegacy:xd({servicePrefix:"location-legacy",baseURI:t}),daCollector:hh({servicePrefix:"telemetry",baseURI:t}).replace("https://","")}}const Ek='<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>',bk='<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>',Ud=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})},Pi={logs:"https://api.realtime.cloudflare.com/logs/otel/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"}},wk=/\b(?:1[7-9](?:\.\d+)?|[2-9]\d(?:\.\d+)?|[1-9]\d{2,}(?:\.\d+)?)\b/,ph="__rtk_plugins__",Pk=[ph];function zg(s){var r,i,n;const t=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((r=window.location.host)==null?void 0:r.includes(Pi.baseURI.staging)),e=!!((n=(i=s==null?void 0:s.getValue("modules"))==null?void 0:i.devTools)!=null&&n.logs);return t||e}function _k(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 Yg(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"?Yg(s[r],i,e):["number","string","boolean"].includes(typeof s[r])&&(e[i]=s[r])}),e}function Qg(s,t,e={},r=""){const i={};try{const n=JSON.stringify(e),o=JSON.parse(n),c=Yg(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 zg(s)&&console.error(u,{log:e,flattened:d}),new Error(u)}return JSON.parse(d)}catch(n){const o=Vd(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 y{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=Dr.getContext(this.meetingMetadata.peerId);return`${hh({servicePrefix:"logs",baseURI:t.getValue("baseURI")})}/otel/logs`}get logsBatchSize(){return this.isCompressionSupported()?50:25}resetPeerId(t){this.meetingMetadata.peerId=t}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");const{RNDeviceInfoImpl:o}=navigator;this.meetingMetadata.deviceInfo=navigator.isReactNative?o==null?void 0:o.getDeviceInfo():Ee.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 f=performance.now();f-u>10&&l.addLogInCurrentSpan("info",`${t}_timing`,{execTime:f-u})}).catch(()=>{const f=performance.now();l.addLogInCurrentSpan("info",`${t}_timing`,{execTime:f-u})}),h},n}}injectContext(t){var i;const e=In().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:Vd(r.error)});const n=Dr.getContext(this.meetingMetadata.peerId);if(zg(n)&&(ck(r)?console[t]("InternalLogs:: ",t,e):console[t]("InternalLogs:: ",t,e,r)),!!_k(n,t))try{const c=Qg(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:Vd(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=Dr.getContext(this.meetingMetadata.peerId),o=JSON.stringify({meetingMetadata:Qg(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:Vd(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 kk(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(f){}})};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 Ck{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 y,i=new fy;this.contexts.set(t,kk(e)),this.contexts.get(t).setValue("peerSessionStore",new Sy(i));const n=new Bm;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 Dr=new Ck,Rk={"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"},$d={"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($d).forEach(s=>{$d[s]=`{${Rk[s.slice(0,2)]}} ${$d[s]}`});class P extends Error{constructor(e,r,i=void 0,n=!1){super(e);p(this,"code");this.code=r,this.name="ClientError";const o=this.code?`[ERR${this.code}]`:"[ERR]",c=this.code?$d[this.code]:"";this.message=`${o}: ${c}
|
|
11
|
+
${this.message}`;try{let d=n&&!!i;r&&r.endsWith("00")&&i&&(d=!0),d&&i.error("ClientError",{error:{message:this.message,name:this.name,code:r}});const l=Dr.getContext(Dr.getMostRecentPeerId());if(l){const u=l.getValue("onError");try{u(this)}catch(h){}}typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("ClientError",{detail:this}))}catch(d){}}}function Bd(s,t,e,r){if(r instanceof P)throw r;if(r instanceof t){const i=new P(r.message,e);throw i.stack=r.stack,i}else throw r}function Xg(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){Bd(this,t,e,o)}}),n&&(s.set=function(o){try{return n.apply(this,[o])}catch(c){Bd(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=>{Bd(this,t,e,o)}):n}catch(n){Bd(this,t,e,n)}},s}function Ik(s,t){return(e,r,i)=>{if(i)return Xg(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,Xg(o,s,t))}}}const ct=s=>Ik(Error,s);var Qs=(s=>(s.GroupCall="GROUP_CALL",s.Webinar="WEBINAR",s.AudioRoom="AUDIO_ROOM",s.Livestream="LIVESTREAM",s.Chat="CHAT",s))(Qs||{}),G=(s=>(s.Allowed="ALLOWED",s.NotAllowed="NOT_ALLOWED",s.CanRequest="CAN_REQUEST",s))(G||{});typeof process!="undefined"&&(vv=process==null?void 0:process.env)!=null&&vv.FLAGSMITH_ENVIRONMENT_KEY&&process.env.FLAGSMITH_ENVIRONMENT_KEY;var Zg=[-2,-1,0,1,2],Ak=[0,1,2,3,4];function Mk(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 Ok=(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)]},Dk=(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]},Nk=(s,t,e)=>{const r=i=>i.toString(16).padStart(2,"0");return`#${r(s)}${r(t)}${r(e)}`},ef=(s,t=Zg,e=.4)=>{const r=[],[i,n,o]=Mk(s),[c,d,l]=Dk(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 f=5-h,S=h+1,E=(100-u)/f,C=u/S;for(const I of t){let R;I<0?R=u+I*C*e:I>0?R=u+I*E*e:R=u;const[U,N,x]=Ok(c,d,R/100);r.push(Nk(U,N,x))}return r},tf={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"}},Lk=s=>{const[t,e,r,i,n]=ef(s,Zg);return{300:t,400:e,500:r,600:i,700:n}},Vk=s=>{if(s==="#FFFFFF")return tf.light.background;if(s==="#000000")return tf.dark.background;const[t,e,r,i,n]=ef(s,Ak);return{1e3:t,900:e,800:r,700:i,600:n}},xk={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:Lk("#2160FD"),background:Vk("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function sf(){return nh(xk)}var Uk={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:sf(),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 $k(){return nh(Uk)}var Bk={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:sf(),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 mh(){return nh(Bk)}function Fk(){Ee.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 _=(s=>(s.NEW_PRODUCER="NEW_PRODUCER",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.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))(_||{});function Hk(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 rf=1080,nf=1920,qk=(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,f=l*u,S,E,C,I,R=1;return h<e&&(R=e/h),Math.abs(R-1)<1e-14&&f<r&&(R=r/f),h*=R,f*=R,C=d/(h/e),I=l/(f/r),S=(d-C)*o,E=(l-I)*c,S<0&&(S=0),E<0&&(E=0),C>d&&(C=d),I>l&&(I=l),[S,E,C,I,s,t,e,r]},bp=class extends Lt{constructor(e,r,i,n){const o=e.getValue("logger");super(o);m(this,rs,void 0);m(this,Vi,void 0);m(this,lt,void 0);m(this,is,void 0);m(this,Oe,{height:rf,width:nf});m(this,Ts,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"});m(this,pr,void 0);m(this,vt,{});m(this,xe,void 0);m(this,Kn,void 0);m(this,zn,void 0);m(this,mr,void 0);m(this,Yn,!1);p(this,"cleanupEventListeners",()=>{a(this,Vi).unsubscribe("stageStatus",this.handlePipMediaControls),a(this,xe).removeListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,xe).removeListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,xe).removeListener("roomLeft",()=>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,xe).videoEnabled?a(this,xe).disableVideo():a(this,xe).enableVideo(),this.emit("cameraToggled")),e==="MIC"&&(a(this,xe).audioEnabled?a(this,xe).disableAudio():a(this,xe).enableAudio(),this.emit("micToggled")),e==="END"&&(a(this,Vi).getValue("peerSessionStore").emit(_.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,mr)==="active"){this.disable(!0);return}a(this,vt)!==void 0&&this.paintCanvas(),a(this,pr)!==void 0&&g(this,pr,requestAnimationFrame(()=>this.animate()))});p(this,"disable",(e=!1)=>{g(this,mr,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(a(this,pr)),e!==!0&&document.body.removeChild(a(this,lt)),g(this,pr,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()});g(this,Vi,e),g(this,mr,"idle"),g(this,xe,r),g(this,Ts,{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){let i,n;try{i=await Ud(Ek),n=await Ud(bk)}catch(o){}return new bp(e,r,i,n)}async setupIcon(e,r){switch(e){case"handRaise":g(this,zn,r);break;case"pin":g(this,Kn,r);break}}async overrideIcon(e,r){switch(e){case"handRaise":g(this,zn,await Ud(r));break;case"pin":g(this,Kn,await Ud(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(){g(this,lt,document.createElement("div")),a(this,lt).style.width="0.1px",a(this,lt).style.height="0.1px",a(this,lt).style.overflow="hidden",a(this,lt).style.position="absolute",a(this,lt).style.bottom="0",a(this,lt).style.right="0",a(this,lt).style.opacity="0",a(this,lt).appendChild(a(this,is))}setupEventListeners(){a(this,Vi).subscribe("stageStatus",this.handlePipMediaControls),a(this,xe).addListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,xe).addListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,xe).addListener("roomLeft",()=>this.disable())}createCanvas(){const e=document.createElement("canvas");e.height=a(this,Oe).height,e.width=a(this,Oe).width,g(this,rs,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,xe).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||a(this,xe).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const r=Object.values(a(this,vt)).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,rs)===void 0)return;const o=a(this,rs).getContext("2d"),c=a(this,rs).width,d=0,l=0,u=r-d*2,h=i-d*2,f=Math.floor(c/u),S=Math.floor(e/f),C=e%f*(u+d)+d,I=S*(h+d)+d,{displayText:R,image:U}=n!=null?n:{};o.fillStyle=R||U?a(this,Ts).videoBackground:a(this,Ts).background,o.strokeStyle=a(this,Ts).brand,o.beginPath(),o.moveTo(C+l,I),o.arcTo(C+u,I,C+u,I+l,l),o.arcTo(C+u,I+h,C+u-l,I+h,l),o.arcTo(C,I+h,C,I+h-l,l),o.arcTo(C,I,C+l,I,l),o.closePath(),o.fill(),o.stroke();const N=u/6,x=u/2+C,B=h/2+I;o.save(),(R||U)&&(o.beginPath(),o.arc(x,B,N,0,Math.PI*2),o.fillStyle=a(this,Ts).brand,o.fill(),U?(o.clip(),o.drawImage(U,x-N,B-N,N*2,N*2),o.restore()):R&&(o.fillStyle=a(this,Ts).textOnBrand,o.font=`${N/2}px sans-serif`,o.textAlign="center",o.textBaseline="middle",o.fillText(R,x,B)),this.drawIcons(n,C,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=f=>{const S=a(this,rs).getContext("2d");S.save(),S.fillStyle=a(this,Ts).background,S.beginPath(),S.moveTo(l+d,u),S.arcTo(l+o,u,l+o,u+d,d),S.arcTo(l+o,u+o,l+o-d,u+o,d),S.arcTo(l,u+o,l,u+o-d,d),S.arcTo(l,u,l+d,u,d),S.closePath(),S.fill(),typeof f=="string"?(S.font=`${o/1.5}px sans-serif`,S.fillStyle=a(this,Ts).text,S.textAlign="center",S.textBaseline="top",S.fillText(f,o/2+l,u+c)):S.drawImage(f,l+c,u+c,o-c*2,o-c*2),l+=o+c,S.restore()};e.pinned&&h(a(this,Kn)),e.handRaised&&h(a(this,zn)),e.reaction&&h(e.reaction)}drawTile(e,r,i){var l,u;if(a(this,rs)===void 0)return;const n=a(this,rs).getContext("2d"),o=this.getSources();let c=0,d=0;for(;c<a(this,Oe).height-5;){let h=0;for(;h<a(this,Oe).width-5&&d<i;){if((l=o[d])!=null&&l.enabled){const f=o[d].element,[S,E,C,I,R,U,N,x]=qk(h,c,e,r,f.videoWidth,f.videoHeight);((u=f==null?void 0:f.classList)==null?void 0:u.contains("mirror"))?(n.save(),n.scale(-1,1),n.drawImage(f,S,E,C,I,-1*R,U,-1*N,x),n.restore()):n.drawImage(f,S,E,C,I,R,U,N,x),this.drawIcons(o[d],R,U,Math.max(N,x))}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,Oe).width,a(this,Oe).height];case 2:return[Math.floor(a(this,Oe).width/2),a(this,Oe).height];case 3:case 4:return[Math.floor(a(this,Oe).width/2),Math.floor(a(this,Oe).height/2)];case 5:case 6:return[Math.floor(a(this,Oe).width/3),Math.floor(a(this,Oe).height/2)];case 7:case 8:case 9:return[Math.floor(a(this,Oe).width/3),Math.floor(a(this,Oe).height/3)];default:return[Math.floor(a(this,Oe).width/3),Math.floor(a(this,Oe).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,xe).config)==null?void 0:e.viewType)!=="LIVESTREAM"}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(g(this,Yn,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),a(this,lt))try{document.body.removeChild(a(this,lt))}catch(e){}this.removeAllSources(),g(this,rs,void 0),g(this,is,void 0),g(this,pr,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,Yn))return;g(this,Yn,!0),this.createCanvas(),this.setupMediaSessionEvents();const i=document.createElement("video");g(this,Oe,{height:e!=null?e:rf,width:r!=null?r:nf}),i.height=a(this,Oe).height,i.width=a(this,Oe).width,i.autoplay=!0,i.muted=!0,i.srcObject=a(this,rs).captureStream(24),g(this,is,i),a(this,is).onloadedmetadata=()=>{try{this.emit("pipStarted"),a(this,is).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,vt)[e]!==void 0&&(a(this,vt)[e].enabled=!0)}disableSource(e){a(this,vt)[e]!==void 0&&(a(this,vt)[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,vt)[e]={id:e,element:r,enabled:i,pinned:n,displayText:o?Hk(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,vt)[e];i&&(a(this,vt)[e]={...i,...r})}removeSource(e){delete a(this,vt)[e]}removePinnedSource(){Object.values(a(this,vt)).forEach(r=>{r.pinned&&this.removeSource(r.id)})}removeAllSources(){g(this,vt,{})}enable(){g(this,mr,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",a(this,xe).videoEnabled),this.updateMediaSession("MIC",a(this,xe).audioEnabled),document.body.appendChild(a(this,lt)),g(this,pr,requestAnimationFrame(()=>this.animate())),a(this,is).onloadedmetadata=()=>{a(this,is).requestPictureInPicture().then(()=>{g(this,mr,"active")})},a(this,is).readyState===4&&a(this,is).requestPictureInPicture().then(()=>{g(this,mr,"active")})}};let gh=bp;rs=new WeakMap,Vi=new WeakMap,lt=new WeakMap,is=new WeakMap,Oe=new WeakMap,Ts=new WeakMap,pr=new WeakMap,vt=new WeakMap,xe=new WeakMap,Kn=new WeakMap,zn=new WeakMap,mr=new WeakMap,Yn=new WeakMap;function fh(s){let t=typeof s;if(t=="object"){if(Array.isArray(s))return"array";if(s===null)return"null"}return t}function jk(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}let Xs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Fd=[];for(let s=0;s<Xs.length;s++)Fd[Xs[s].charCodeAt(0)]=s;Fd["-".charCodeAt(0)]=Xs.indexOf("+"),Fd["_".charCodeAt(0)]=Xs.indexOf("/");function Gk(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=Fd[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 Wk(s){let t="",e=0,r,i=0;for(let n=0;n<s.length;n++)switch(r=s[n],e){case 0:t+=Xs[r>>2],i=(r&3)<<4,e=1;break;case 1:t+=Xs[i|r>>4],i=(r&15)<<2,e=2;break;case 2:t+=Xs[i|r>>6],t+=Xs[r&63],e=0;break}return e&&(t+=Xs[i],t+="=",e==1&&(t+="=")),t}var Hd;(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])})(Hd||(Hd={}));var Ve;(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"})(Ve||(Ve={}));function Jk(){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 Sh(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 qd=(1<<16)*(1<<16);function af(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>=qd&&(i=i+(r/qd|0),r=r%qd)}return n(-24,-18),n(-18,-12),n(-12,-6),n(-6),[t,r,i]}function vh(s,t){if(t>>>0<=2097151)return""+(qd*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 f=u?String(u):"";return h?"0000000".slice(f.length)+f:f}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 Kk(){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 ge;function zk(){const s=new DataView(new ArrayBuffer(8));ge=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}zk();function cf(s){if(!s)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const df=/^-?[0-9]+$/,jd=4294967296,Gd=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*jd+(this.lo>>>0);if(!Number.isSafeInteger(t))throw new Error("cannot convert to safe number");return t}}class dt extends lf{static from(t){if(ge)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=ge.C(t);case"number":if(t===0)return this.ZERO;t=ge.C(t);case"bigint":if(!t)return this.ZERO;if(t<ge.UMIN)throw new Error("signed value for ulong");if(t>ge.UMAX)throw new Error("ulong too large");return ge.V.setBigUint64(0,t,!0),new dt(ge.V.getInt32(0,!0),ge.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!df.test(t))throw new Error("string is no integer");let[e,r,i]=af(t);if(e)throw new Error("signed value for ulong");return new dt(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 dt(t,t/jd)}throw new Error("unknown value "+typeof t)}toString(){return ge?this.toBigInt().toString():vh(this.lo,this.hi)}toBigInt(){return cf(ge),ge.V.setInt32(0,this.lo,!0),ge.V.setInt32(4,this.hi,!0),ge.V.getBigUint64(0,!0)}}dt.ZERO=new dt(0,0);class ve extends lf{static from(t){if(ge)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=ge.C(t);case"number":if(t===0)return this.ZERO;t=ge.C(t);case"bigint":if(!t)return this.ZERO;if(t<ge.MIN)throw new Error("signed long too small");if(t>ge.MAX)throw new Error("signed long too large");return ge.V.setBigInt64(0,t,!0),new ve(ge.V.getInt32(0,!0),ge.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!df.test(t))throw new Error("string is no integer");let[e,r,i]=af(t);if(e){if(i>Gd||i==Gd&&r!=0)throw new Error("signed long too small")}else if(i>=Gd)throw new Error("signed long too large");let n=new ve(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 ve(t,t/jd):new ve(-t,-t/jd).negate()}throw new Error("unknown value "+typeof t)}isNegative(){return(this.hi&Gd)!==0}negate(){let t=~this.hi,e=this.lo;return e?e=~e+1:t+=1,new ve(e,t)}toString(){if(ge)return this.toBigInt().toString();if(this.isNegative()){let t=this.negate();return"-"+vh(t.lo,t.hi)}return vh(this.lo,this.hi)}toBigInt(){return cf(ge),ge.V.setInt32(0,this.lo,!0),ge.V.setInt32(4,this.hi,!0),ge.V.getBigInt64(0,!0)}}ve.ZERO=new ve(0,0);const uf={readUnknownField:!0,readerFactory:s=>new Qk(s)};function Yk(s){return s?Object.assign(Object.assign({},uf),s):uf}class Qk{constructor(t,e){this.varint64=Jk,this.uint32=Kk,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 Ve.Varint:for(;this.buf[this.pos++]&128;);break;case Ve.Bit64:this.pos+=4;case Ve.Bit32:this.pos+=4;break;case Ve.LengthDelimited:let r=this.uint32();this.pos+=r;break;case Ve.StartGroup:let i;for(;(i=this.tag()[1])!==Ve.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 ve(...this.varint64())}uint64(){return new dt(...this.varint64())}sint64(){let[t,e]=this.varint64(),r=-(t&1);return t=(t>>>1|(e&1)<<31)^r,e=e>>>1^r,new ve(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 dt(this.sfixed32(),this.sfixed32())}sfixed64(){return new ve(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 ie(s,t){if(!s)throw new Error(t)}const Xk=34028234663852886e22,Zk=-34028234663852886e22,eC=4294967295,tC=2147483647,sC=-2147483648;function lo(s){if(typeof s!="number")throw new Error("invalid int 32: "+typeof s);if(!Number.isInteger(s)||s>tC||s<sC)throw new Error("invalid int 32: "+s)}function Wd(s){if(typeof s!="number")throw new Error("invalid uint 32: "+typeof s);if(!Number.isInteger(s)||s>eC||s<0)throw new Error("invalid uint 32: "+s)}function Th(s){if(typeof s!="number")throw new Error("invalid float 32: "+typeof s);if(Number.isFinite(s)&&(s>Xk||s<Zk))throw new Error("invalid float 32: "+s)}const hf={writeUnknownFields:!0,writerFactory:()=>new iC};function rC(s){return s?Object.assign(Object.assign({},hf),s):hf}class iC{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(Wd(t);t>127;)this.buf.push(t&127|128),t=t>>>7;return this.buf.push(t),this}int32(t){return lo(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){Th(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){Wd(t);let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),this.raw(e)}sfixed32(t){lo(t);let e=new Uint8Array(4);return new DataView(e.buffer).setInt32(0,t,!0),this.raw(e)}sint32(t){return lo(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=ve.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=dt.from(t);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(e)}int64(t){let e=ve.from(t);return Sh(e.lo,e.hi,this.buf),this}sint64(t){let e=ve.from(t),r=e.hi>>31,i=e.lo<<1^r,n=(e.hi<<1|e.lo>>>31)^r;return Sh(i,n,this.buf),this}uint64(t){let e=dt.from(t);return Sh(e.lo,e.hi,this.buf),this}}const pf={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},mf={ignoreUnknownFields:!1};function nC(s){return s?Object.assign(Object.assign({},mf),s):mf}function aC(s){return s?Object.assign(Object.assign({},pf),s):pf}const gf=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 As;(function(s){s[s.BIGINT=0]="BIGINT",s[s.STRING=1]="STRING",s[s.NUMBER=2]="NUMBER"})(As||(As={}));var Jd;(function(s){s[s.NO=0]="NO",s[s.PACKED=1]="PACKED",s[s.UNPACKED=2]="UNPACKED"})(Jd||(Jd={}));function oC(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:Jd.NO,s.opt=(i=s.opt)!==null&&i!==void 0?i:s.repeat||s.oneof?!1:s.kind=="message",s}function cC(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 dC{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(!cC(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 As.BIGINT:return i=="bigint";case As.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,As.STRING)}}}function ms(s,t){switch(t){case As.BIGINT:return s.toBigInt();case As.NUMBER:return s.toNumber();default:return s.toString()}}class lC{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=fh(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(jk(o),c.name,o);const u=l[d];for(const[h,f]of Object.entries(o)){this.assert(f!==null,c.name+" map value",null);let S;switch(c.V.kind){case"message":S=c.V.T().internalJsonRead(f,r);break;case"enum":if(S=this.enum(c.V.T(),f,c.name,r.ignoreUnknownFields),S===!1)continue;break;case"scalar":S=this.scalar(f,c.V.T,c.V.L,c.name);break}this.assert(S!==void 0,c.name+" map value",f);let E=h;c.K==O.BOOL&&(E=E=="true"?!0:E=="false"?!1:E),E=this.scalar(E,c.K,As.STRING,c.name).toString(),u[E]=S}}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 f;switch(c.kind){case"message":f=c.T().internalJsonRead(h,r);break;case"enum":if(f=this.enum(c.T(),h,c.name,r.ignoreUnknownFields),f===!1)continue;break;case"scalar":f=this.scalar(h,c.T,c.L,c.name);break}this.assert(f!==void 0,c.name,o),u.push(f)}}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"&&ie(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 ie(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:(ie(typeof o=="number",`Unable to parse field ${this.info.typeName}#${r}, enum ${t[0]} has no value for "${e}".`),o)}ie(!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&&Th(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?Wd(c):lo(c),c;case O.INT64:case O.SFIXED64:case O.SINT64:if(t===null)return ms(ve.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return ms(ve.from(t),r);case O.FIXED64:case O.UINT64:if(t===null)return ms(dt.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return ms(dt.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 Gk(t)}}catch(o){n=o.message}this.assert(!1,i+(n?" - "+n:""),t)}}class uC{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);ie(d!==void 0),r[e.useProtoFieldName?n.name:n.jsonName]=d}return r}field(t,e,r){let i;if(t.kind=="map"){ie(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);ie(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);ie(u!==void 0),n[d.toString()]=u}break;case"enum":const c=t.V.T();for(const[d,l]of Object.entries(e)){ie(l===void 0||typeof l=="number");const u=this.enum(c,l,t.name,!1,!0,r.enumAsInteger);ie(u!==void 0),n[d.toString()]=u}break}(r.emitDefaultValues||Object.keys(n).length>0)&&(i=n)}else if(t.repeat){ie(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);ie(l!==void 0),n.push(l)}break;case"enum":const o=t.T();for(let d=0;d<e.length;d++){ie(e[d]===void 0||typeof e[d]=="number");const l=this.enum(o,e[d],t.name,t.opt,!0,r.enumAsInteger);ie(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);ie(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){ie(i);return}if(!(e===0&&!n&&!i))return ie(typeof e=="number"),ie(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){ie(i);return}const o=n||i;switch(t){case O.INT32:case O.SFIXED32:case O.SINT32:return e===0?o?0:void 0:(lo(e),e);case O.FIXED32:case O.UINT32:return e===0?o?0:void 0:(Wd(e),e);case O.FLOAT:Th(e);case O.DOUBLE:return e===0?o?0:void 0:(ie(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:(ie(typeof e=="string"),e);case O.BOOL:return e===!1?o?!1:void 0:(ie(typeof e=="boolean"),e);case O.UINT64:case O.FIXED64:ie(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let c=dt.from(e);return c.isZero()&&!o?void 0:c.toString();case O.INT64:case O.SFIXED64:case O.SINT64:ie(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let d=ve.from(e);return d.isZero()&&!o?void 0:d.toString();case O.BYTES:return ie(e instanceof Uint8Array),e.byteLength?Wk(e):o?"":void 0}}}function yh(s,t=As.STRING){switch(s){case O.BOOL:return!1;case O.UINT64:case O.FIXED64:return ms(dt.ZERO,t);case O.INT64:case O.SFIXED64:case O.SINT64:return ms(ve.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 hC{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 f=r.readUnknownField;if(f=="throw")throw new Error(`Unknown field ${o} (wire type ${c}) for ${this.info.typeName}`);let S=t.skip(c);f!==!1&&(f===!0?Hd.onRead:f)(this.info.typeName,e,o,c,S);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 f=d.kind=="enum"?O.INT32:d.T,S=d.kind=="scalar"?d.L:void 0;if(u){let I=l[h];if(c==Ve.LengthDelimited&&f!=O.STRING&&f!=O.BYTES){let R=t.uint32()+t.pos;for(;t.pos<R;)I.push(this.scalar(t,f,S))}else I.push(this.scalar(t,f,S))}else l[h]=this.scalar(t,f,S);break;case"message":if(u){let I=l[h],R=d.T().internalBinaryRead(t,t.uint32(),r);I.push(R)}else l[h]=d.T().internalBinaryRead(t,t.uint32(),r,l[h]);break;case"map":let[E,C]=this.mapEntry(d,t,r);l[h][E]=C;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,As.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=yh(t.K);o=t.K==O.BOOL?d.toString():d}if(c===void 0)switch(t.V.kind){case"scalar":c=yh(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 ms(t.int64(),r);case O.UINT64:return ms(t.uint64(),r);case O.FIXED64:return ms(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 ms(t.sfixed64(),r);case O.SINT32:return t.sint32();case O.SINT64:return ms(t.sint64(),r)}}}class pC{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(ie(Array.isArray(o)),d==Jd.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?ie(n.opt):this.scalar(e,u,n.no,o,c||n.opt);break;case"message":if(d){ie(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":ie(typeof o=="object"&&o!==null);for(const[h,f]of Object.entries(o))this.mapEntry(e,r,n,h,f);break}}let i=r.writeUnknownFields;i!==!1&&(i===!0?Hd.onWrite:i)(this.info.typeName,t,e)}mapEntry(t,e,r,i,n){t.tag(r.no,Ve.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:ie(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,Ve.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;ie(e!==O.BYTES&&e!==O.STRING),t.tag(r,Ve.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=Ve.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=Ve.LengthDelimited,i="string";break;case O.BOOL:o=e===!1,i="bool";break;case O.UINT32:i="uint32";break;case O.DOUBLE:r=Ve.Bit64,i="double";break;case O.FLOAT:r=Ve.Bit32,i="float";break;case O.INT64:o=n||ve.from(e).isZero(),i="int64";break;case O.UINT64:o=n||dt.from(e).isZero(),i="uint64";break;case O.FIXED64:o=n||dt.from(e).isZero(),r=Ve.Bit64,i="fixed64";break;case O.BYTES:o=n||!e.byteLength,r=Ve.LengthDelimited,i="bytes";break;case O.FIXED32:r=Ve.Bit32,i="fixed32";break;case O.SFIXED32:r=Ve.Bit32,i="sfixed32";break;case O.SFIXED64:o=n||ve.from(e).isZero(),r=Ve.Bit64,i="sfixed64";break;case O.SINT32:i="sint32";break;case O.SINT64:o=n||ve.from(e).isZero(),i="sint64";break}return[r,i,n||o]}}function mC(s){const t=s.messagePrototype?Object.create(s.messagePrototype):Object.defineProperty({},gf,{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]=yh(e.T,e.L);break;case"enum":t[r]=0;break;case"map":t[r]={};break}}return t}function Eh(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 gC(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?vf(c,n,o):Sf(c,n,o)))return!1;break;case"map":if(!(r.V.kind=="message"?Tf(r.V.T(),Kd(n),Kd(o)):vf(r.V.kind=="enum"?O.INT32:r.V.T,Kd(n),Kd(o))))return!1;break;case"message":let d=r.T();if(!(r.repeat?Tf(d,n,o):d.equals(n,o)))return!1;break}}return!0}const Kd=Object.values;function Sf(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 vf(s,t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(!Sf(s,t[r],e[r]))return!1;return!0}function Tf(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 yf=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})),fC=yf[gf]={};class v{constructor(t,e,r){this.defaultCheckDepth=16,this.typeName=t,this.fields=e.map(oC),this.options=r!=null?r:{},fC.value=this,this.messagePrototype=Object.create(null,yf),this.refTypeCheck=new dC(this),this.refJsonReader=new lC(this),this.refJsonWriter=new uC(this),this.refBinReader=new hC(this),this.refBinWriter=new pC(this)}create(t){let e=mC(this);return t!==void 0&&Eh(this,e,t),e}clone(t){let e=this.create();return Eh(this,e,t),e}equals(t,e){return gC(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){Eh(this,t,e)}fromBinary(t,e){let r=Yk(e);return this.internalBinaryRead(r.readerFactory(t),t.byteLength,r)}fromJson(t,e){return this.internalJsonRead(t,nC(e))}fromJsonString(t,e){let r=JSON.parse(t);return this.fromJson(r,e)}toJson(t,e){return this.internalJsonWrite(t,aC(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=rC(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 ${fh(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 Zs;(function(s){s[s.PUBLISHER=0]="PUBLISHER",s[s.SUBSCRIBER=1]="SUBSCRIBER"})(Zs||(Zs={}));var er;(function(s){s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO"})(er||(er={}));class SC extends v{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 Ef=new SC;class vC extends v{constructor(){super("media.HeaderExtension",[{no:1,name:"direction",kind:"scalar",opt:!0,T:9},{no:2,name:"uri",kind:"scalar",T:9}])}}const TC=new vC;class yC extends v{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new yC;class EC extends v{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",Zs]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const gs=new EC;class bC extends v{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 wC=new bC;class PC extends v{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:()=>gs},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8},{no:5,name:"producers",kind:"message",repeat:1,T:()=>wC}])}}const _C=new PC;class kC extends v{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 CC=new kC;class RC extends v{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>gs},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:4,name:"producer_ids",kind:"scalar",repeat:2,T:9}])}}const bf=new RC;class IC extends v{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>gs}])}}const AC=new IC;class MC extends v{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>gs}])}}new MC;class OC extends v{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 DC=new OC;class NC extends v{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 LC=new NC;class VC extends v{constructor(){super("media.ProducerEntry",[{no:1,name:"producing_transport_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9}])}}new VC;class xC extends v{constructor(){super("media.ConsumerEntry",[{no:1,name:"consuming_transport_id",kind:"scalar",T:9},{no:2,name:"consumer_id",kind:"scalar",T:9}])}}new xC;class UC extends v{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",er]},{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:()=>Ef}])}}const uo=new UC;class $C extends v{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>uo},{no:3,name:"producer_track",kind:"message",T:()=>LC},{no:4,name:"error_code",kind:"scalar",opt:!0,T:9}])}}const BC=new $C;class FC extends v{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>BC}}])}}const wf=new FC;class HC extends v{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>kf},{no:2,name:"receiver",kind:"message",T:()=>kf}])}}const Pf=new HC;class qC extends v{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>Ef},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>TC}])}}const _f=new qC;class jC extends v{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>_f},{no:2,name:"video",kind:"message",T:()=>_f}])}}const kf=new jC;class GC extends v{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 WC=new GC;class JC extends v{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 Cf=new JC;class KC extends v{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 zC=new KC;class YC extends v{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:()=>zC},{no:9,name:"capabilities",kind:"message",T:()=>Pf}])}}const QC=new YC;class XC extends v{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const ZC=new XC;class eR extends v{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const tR=new eR;class sR extends v{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 sR;class rR extends v{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:()=>WC},{no:5,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:6,name:"simulcast",kind:"message",T:()=>Cf}])}}const iR=new rR;class nR extends v{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>iR},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const aR=new nR;class oR extends v{constructor(){super("media.edge.UpdateConsumerSimulcastConfigRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"simulcast",kind:"message",T:()=>Cf},{no:3,name:"producing_transport_id",kind:"scalar",T:9},{no:4,name:"mid",kind:"scalar",T:9}])}}const cR=new oR;class dR extends v{constructor(){super("media.edge.UpdateConsumersSimulcastConfigRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>cR},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const lR=new dR;class uR extends v{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:()=>gs},{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 hR=new uR;class pR extends v{constructor(){super("media.edge.SelectedPeersRequest",[])}}new pR;class mR extends v{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const gR=new mR;class fR extends v{constructor(){super("media.edge.ProducerToggleRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const zd=new fR;class SR extends v{constructor(){super("media.edge.ConsumerToggleRequest",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}new SR;class vR extends v{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>gs},{no:3,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const TR=new vR;class yR extends v{constructor(){super("media.edge.ConsumerCloseRequest",[{no:1,name:"consumer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"description",kind:"message",T:()=>gs},{no:3,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const ER=new yR;class bR extends v{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new bR;class wR extends v{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const Rf=new wR;class PR extends v{constructor(){super("media.edge.PeerDisplayNameEditRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}const _R=new PR;class kR extends v{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 CR=new kR;class RR extends v{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 IR=new RR;class AR extends v{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 MR=new AR;class OR extends v{constructor(){super("media.edge.ErrorResponse",[{no:1,name:"error_message",kind:"scalar",T:9},{no:2,name:"event_id",kind:"scalar",T:5}])}}const DR=new OR;class NR extends v{constructor(){super("media.edge.EmptyResponse",[])}}new NR;class LR extends v{constructor(){super("media.edge.RoomParticipants",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"producer_states",kind:"message",repeat:1,T:()=>uo},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"user_id",kind:"scalar",opt:!0,T:9},{no:5,name:"capabilities",kind:"message",T:()=>Pf}])}}const If=new LR;class VR extends v{constructor(){super("media.edge.SelectedPeersResponse",[{no:1,name:"audio_peers",kind:"scalar",repeat:2,T:9},{no:2,name:"compulsory_peers",kind:"scalar",repeat:2,T:9}])}}const bh=new VR;class xR extends v{constructor(){super("media.edge.SelectedPeersDiffEntry",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"priority",kind:"scalar",T:5}])}}const UR=new xR;class $R extends v{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>UR}])}}const Af=new $R;class BR extends v{constructor(){super("media.edge.PeerJoinResponse",[])}}new BR;class FR extends v{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>MR},{no:2,name:"participants",kind:"message",repeat:1,T:()=>If},{no:3,name:"selected_peers",kind:"message",T:()=>bh},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const wh=new FR;class HR extends v{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}new HR;class qR extends v{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>wf}])}}new qR;class jR extends v{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:()=>gs}])}}const GR=new jR;class WR extends v{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:()=>gs}])}}const JR=new WR;class KR extends v{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>DC}])}}new KR;class zR extends v{constructor(){super("media.edge.ActiveSpeakerResponse",[{no:1,name:"responsepeer_id",kind:"scalar",T:9},{no:2,name:"volume",kind:"scalar",T:5}])}}new zR;class YR extends v{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new YR;class QR extends v{constructor(){super("media.edge.ProducerToggleResponse",[])}}new QR;class XR extends v{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new XR;class ZR extends v{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>gs}])}}const eI=new ZR;class tI extends v{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>gs}])}}const sI=new tI;class rI extends v{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new rI;class iI extends v{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new iI;class nI extends v{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new nI;class aI extends v{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const oI=new aI;class cI extends v{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const dI=new cI;class lI extends v{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const uI=new lI;class hI extends v{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>If}])}}const Mf=new hI;class pI extends v{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const Of=new pI;class mI extends v{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>Of},{no:3,name:"screenshare",kind:"message",T:()=>Of}])}}const gI=new mI;class fI extends v{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>bf},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>gI}])}}new fI;class SI extends v{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>uo}])}}const vI=new SI;class TI extends v{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>uo},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const Df=new TI;class yI extends v{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>uo}])}}const EI=new yI;class bI extends v{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Ph=new bI;class wI extends v{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Nf=new wI;class PI extends v{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new PI;class _I extends v{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new _I;class kI extends v{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new kI;class CI extends v{constructor(){super("media.edge.PeerDisplayNameEditBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}new CI;class RI extends v{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new RI;class II extends v{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new II;class AI extends v{constructor(){super("socket.ai.MeetingTranscript",[{no:1,name:"meeting_id",kind:"scalar",T:9},{no:2,name:"transcript",kind:"scalar",T:9},{no:3,name:"is_partial",kind:"scalar",T:8}])}}const _h=new AI;class MI extends v{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 MI;class OI extends v{constructor(){super("socket.api.ErrorMessage",[{no:1,name:"code",kind:"scalar",opt:!0,T:5},{no:2,name:"message",kind:"scalar",T:9}])}}const DI=new OI;var _i;(function(s){s[s.BROWSER=0]="BROWSER",s[s.TRACK=1]="TRACK",s[s.COMPOSITE=2]="COMPOSITE"})(_i||(_i={}));var tr;(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"})(tr||(tr={}));var kh;(function(s){s[s.NONE=0]="NONE",s[s.RECORDER=1]="RECORDER",s[s.LIVESTREAMER=2]="LIVESTREAMER"})(kh||(kh={}));var Ch;(function(s){s[s.PEERS=0]="PEERS",s[s.ROOMS=1]="ROOMS"})(Ch||(Ch={}));var Yd;(function(s){s[s.HIVE=0]="HIVE",s[s.CHAT=1]="CHAT",s[s.PING=2]="PING"})(Yd||(Yd={}));class NI extends v{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 LI=new NI;class VI extends v{constructor(){super("socket.room.Peer",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"stage_type",kind:"enum",opt:!0,T:()=>["socket.room.StageType",tr,"STAGE_TYPE_"]},{no:5,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:6,name:"preset_id",kind:"scalar",opt:!0,T:9},{no:7,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:8,name:"waitlisted",kind:"scalar",T:8},{no:9,name:"flags",kind:"message",T:()=>LI}])}}const Qd=new VI;class xI extends v{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>Qd}])}}const Vn=new xI;class UI extends v{constructor(){super("socket.room.PeerStatusUpdate",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"stage_type",kind:"enum",opt:!0,T:()=>["socket.room.StageType",tr,"STAGE_TYPE_"]}])}}const Lf=new UI;class $I extends v{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 BI=new $I;class FI extends v{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>Qd}])}}const Rh=new FI;class HI extends v{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const Vf=new HI;class qI extends v{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:()=>GI},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const xf=new qI;class jI extends v{constructor(){super("socket.room.ActiveRecording",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",_i]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const GI=new jI;class WI extends v{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>xf}])}}const Uf=new WI;class JI extends v{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const $f=new JI;class KI extends v{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 KI;class zI extends v{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Qd},{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",Yd,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const YI=new zI;class QI extends v{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Qd},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const XI=new QI;class ZI extends v{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>xf}])}}new ZI;class e0 extends v{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new e0;class t0 extends v{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 Ih=new t0;class s0 extends v{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 r0=new s0;class i0 extends v{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:()=>r0}])}}const Bf=new i0;class n0 extends v{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>Bf},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>Bf}])}}const a0=new n0;class o0 extends v{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const c0=new o0;class d0 extends v{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>c0}])}}const l0=new d0;class u0 extends v{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:()=>Ih}])}}const h0=new u0;class p0 extends v{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>h0}])}}const Ff=new p0;class m0 extends v{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 g0=new m0;class f0 extends v{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>g0}])}}new f0;class S0 extends v{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const v0=new S0;class T0 extends v{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>v0}])}}const y0=new T0;class E0 extends v{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>P0}])}}const b0=new E0;class w0 extends v{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:()=>Ih}])}}const P0=new w0;class _0 extends v{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 k0=new _0;class C0 extends v{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:()=>k0}])}}const R0=new C0;class I0 extends v{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:()=>Ih}])}}const Hf=new I0;class A0 extends v{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Hf}])}}new A0;class M0 extends v{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 O0=new M0;class D0 extends v{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>V0}])}}const N0=new D0;class L0 extends v{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 V0=new L0;class x0 extends v{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const qf=new x0;class U0 extends v{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",Ch,"BROADCAST_TYPE_"]}])}}const ho=new U0;class $0 extends v{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const B0=new $0;class F0 extends v{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const H0=new F0;class q0 extends v{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 j0=new q0;class G0 extends v{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>j0}])}}const jf=new G0;class W0 extends v{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 Gf=new W0;var Ah;(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"})(Ah||(Ah={}));var Nr;(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"})(Nr||(Nr={}));class J0 extends v{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 K0=new J0;class z0 extends v{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 Y0=new z0;class Q0 extends v{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 X0=new Q0;class Z0 extends v{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 eA=new Z0;class tA extends v{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>X0},{no:2,name:"private",kind:"message",T:()=>eA}])}}const sA=new tA;class rA extends v{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 iA=new rA;class nA extends v{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Nr,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Nr,"STREAM_PERMISSION_TYPE_"]}])}}const Mh=new nA;class aA extends v{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>Mh},{no:2,name:"audio",kind:"message",T:()=>Mh},{no:3,name:"screenshare",kind:"message",T:()=>Mh}])}}const oA=new aA;class cA extends v{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>K0},{no:2,name:"plugins",kind:"message",T:()=>Y0},{no:3,name:"chat",kind:"message",T:()=>sA},{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",Ah,"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",kh,"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:()=>iA},{no:23,name:"media",kind:"message",T:()=>oA}])}}const Oh=new cA;class dA extends v{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const lA=new dA;class uA extends v{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 hA=new uA;class pA extends v{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>hA}])}}const mA=new pA;class gA extends v{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>Oh}])}}const Wf=new gA;class fA extends v{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>Wf}])}}const SA=new fA;class vA extends v{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>Wf}])}}const Jf=new vA;class TA extends v{constructor(){super("socket.preset.PeerUserIDMap",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9}])}}const yA=new TA;class EA extends v{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>yA},{no:2,name:"patch",kind:"message",T:()=>Oh}])}}new EA;class bA extends v{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>Oh}])}}new bA;class wA extends v{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 Lr=new wA;class PA extends v{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 _A=new PA;class kA extends v{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:()=>_A}])}}const CA=new kA;class RA extends v{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Lr},{no:2,name:"next",kind:"scalar",T:8}])}}const IA=new RA;class AA extends v{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Lr}])}}const Kf=new AA;class MA extends v{constructor(){super("socket.chat.SendChatMessageToRoomRequest",[{no:1,name:"payload_type",kind:"scalar",T:5},{no:2,name:"payload",kind:"scalar",T:9}])}}const OA=new MA;class DA extends v{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>Lr}])}}const Dh=new DA;class NA extends v{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 LA=new NA;class VA extends v{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>Lr}])}}const Nh=new VA;class xA extends v{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 xA;class UA extends v{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>Lr}])}}new UA;class $A extends v{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 BA=new $A;class FA extends v{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 HA=new FA;class qA extends v{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:()=>Lr}])}}const Xd=new qA;class jA extends v{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>Lr}])}}const Zd=new jA;class GA extends v{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 WA=new GA;class JA extends v{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 el=new JA;class KA extends v{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 zA=new KA;class YA extends v{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 YA;class QA extends v{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}new QA;class XA extends v{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 XA;class ZA extends v{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 ZA;class eM extends v{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new eM;class tM extends v{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new tM;class sM extends v{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>Lr},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const rM=new sM;class iM extends v{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:()=>rM},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const nM=new iM;class aM extends v{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>nM}])}}new aM;class oM extends v{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 cM=new oM;class dM extends v{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>cM}])}}new dM;class lM extends v{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}new lM;class uM extends v{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}new uM;class hM extends v{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}new hM;class pM extends v{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}new pM;class mM extends v{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 mM;class gM extends v{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 gM;class fM extends v{constructor(){super("socket.plugin.PluginEventToRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}new fM;class SM extends v{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 SM;class vM extends v{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 Lh=new vM;class TM extends v{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:()=>Lh}])}}const yM=new TM;class EM extends v{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:()=>Lh}])}}const bM=new EM;class wM extends v{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:()=>Lh}])}}const PM=new wM;class _M extends v{constructor(){super("socket.plugin.PluginStoreDeleteRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9}])}}new _M;class kM extends v{constructor(){super("socket.plugin.EnablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"enabled_by",kind:"scalar",T:9}])}}const CM=new kM;class RM extends v{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>CM}])}}new RM;class IM extends v{constructor(){super("socket.plugin.DisablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"disabled_by",kind:"scalar",T:9}])}}new IM;class AM extends v{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 MM=new AM;class OM extends v{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:()=>MM}])}}const zf=new OM;class DM extends v{constructor(){super("socket.plugin.PluginEventResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}new DM;class NM extends v{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 Yf=new NM;class LM extends v{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const Qf=new LM;class VM extends v{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 xM=new VM;class UM extends v{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>xM}])}}const Vh=new UM;class $M extends v{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const BM=new $M;class FM extends v{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const HM=new FM;class qM extends v{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const Xf=new qM;class jM extends v{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:()=>WM},{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 Zf=new jM;class GM extends v{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:()=>KM}])}}const WM=new GM;class JM extends v{constructor(){super("socket.polls.PollVote",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])}}const KM=new JM;class zM extends v{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 YM=new zM;class QM extends v{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 XM=new QM;class ZM extends v{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>Zf}])}}const xh=new ZM;class eO extends v{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>Zf}])}}const tO=new eO;class sO extends v{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",_i]}])}}const eS=new sO;class rO extends v{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=ve.from(Math.floor(e/1e3)).toBigInt(),t.nanos=e%1e3*1e6,t}toDate(t){return new Date(ve.from(t.seconds).toNumber()*1e3+Math.ceil(t.nanos/1e6))}fromDate(t){const e=this.create(),r=t.getTime();return e.seconds=ve.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}internalJsonWrite(t,e){let r=ve.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 "+fh(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=ve.from(n/1e3).toBigInt(),r.nanos=0,i[7]&&(r.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),r}}new rO;class iO extends v{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 Uh=new iO;class nO extends v{constructor(){super("common.BulkedHubMessage",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Uh}])}}new nO;class aO extends v{constructor(){super("common.CFWorkersResponse",[{no:1,name:"responses",kind:"message",repeat:1,T:()=>Uh},{no:2,name:"broadcast_responses",kind:"message",repeat:1,T:()=>Uh}])}}new aO;const oO=0,cO=1,dO=2,lO=3,uO=5,hO={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},pO={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,searchChannelMessages:7,pinMessage:10},mO={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},gO={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},tS={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},fO={getUserPresets:0,updateUserPreset:1};function po(s,t){return Object.keys(t).reduce((e,r)=>(e[r]=(s<<16)+t[r],e),{})}function sS(s,t){return Object.keys(s).reduce((e,r)=>(e[r]=t|s[r],e),{})}const $=po(oO,hO),Ge=po(cO,pO),sr=po(dO,mO),rr=po(lO,gO),Vr=sS(tS,16777216),fs=sS(tS,50331648),tl=po(uO,fO);var SO=Object.defineProperty,vO=Object.getOwnPropertyDescriptor,xr=(s,t,e,r)=>{for(var i=r>1?void 0:r?vO(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&&SO(t,e,i),i},es=(s=>(s[s.TEXT=0]="TEXT",s[s.IMAGE=1]="IMAGE",s[s.FILE=2]="FILE",s[s.CUSTOM=3]="CUSTOM",s))(es||{});class ir{constructor(t,e){m(this,Ft,void 0);m(this,Qn,void 0);g(this,Ft,e),g(this,Qn,t)}get telemetry(){return a(this,Qn).getValue("telemetry")}get logger(){return a(this,Qn).getValue("logger")}getChatMessages(){return a(this,Ft).sendMessagePromise(Ge.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,Ft).sendMessagePromise(Ge.getPaginatedMessages,CA.toBinary(n));return o.payload?IA.fromBinary(o.payload):{messages:[],next:!1}}sendMessageToRoom(t,e){const r={payloadType:e,payload:t};a(this,Ft).sendMessage(Ge.sendMessageToRoom,OA.toBinary(r))}sendMessageToPeers(t,e,r){const i={payloadType:e,peerIds:r,payload:t};a(this,Ft).sendMessage(Ge.sendMessageToPeers,LA.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,Ft).sendMessagePromise(Ge.editMessage,BA.toBinary(n));return Zd.fromBinary(o.payload).message}async deleteMessage(t){const e={chatId:t},r=await a(this,Ft).sendMessagePromise(Ge.deleteMessage,WA.toBinary(e));return{id:el.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,Ft).sendMessagePromise(Ge.searchChannelMessages,zA.toBinary(r));return Kf.fromBinary(d.payload).messages}catch(d){return[]}}async setPinState(t,e){const r={chatId:t,pinned:e},i=await a(this,Ft).sendMessagePromise(Ge.pinMessage,HA.toBinary(r));return Xd.fromBinary(i.payload)}on(t,e){let r,i;switch(t){case Ge.sendMessageToRoom:{r=Dh.fromBinary.bind(Dh),i=Dh.create();break}case Ge.sendMessageToPeers:{r=Nh.fromBinary.bind(Nh),i=Nh.create();break}case Ge.editMessage:{r=Zd.fromBinary.bind(Zd),i=Zd.create();break}case Ge.pinMessage:{r=Xd.fromBinary.bind(Xd),i=Xd.create();break}case Ge.deleteMessage:{r=el.fromBinary.bind(el),i=el.create();break}}if(!r){this.logger.warn(`ChatSocketHandler::Event ${t} is not recognized`);return}a(this,Ft).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)})}}Ft=new WeakMap,Qn=new WeakMap,xr([y.trace("SocketService.getChatMessages")],ir.prototype,"getChatMessages",1),xr([y.trace("SocketService.getChatMessagesPaginated")],ir.prototype,"getChatMessagesPaginated",1),xr([y.trace("SocketService.sendMessageToRoom")],ir.prototype,"sendMessageToRoom",1),xr([y.trace("SocketService.sendMessageToPeers")],ir.prototype,"sendMessageToPeers",1),xr([y.trace("SocketService.sendMessage")],ir.prototype,"sendMessage",1),xr([y.trace("SocketService.editMessage")],ir.prototype,"editMessage",1),xr([y.trace("SocketService.deleteMessage")],ir.prototype,"deleteMessage",1),xr([y.trace("SocketService.searchMessages")],ir.prototype,"searchMessages",1);function TO(s){return s.replace(/([-_]\w)/g,t=>t[1].toUpperCase())}function Ms(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>Ms(e));const t={};return Object.keys(s).forEach(e=>{const r=Uu(e)?e:TO(e);t[r]=Ms(s[e])}),t}function yO(s){return s.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function rS(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>rS(e));const t={};return Object.keys(s).forEach(e=>{const r=Uu(e)?e:yO(e);t[r]=s[e]}),t}class sl 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 iS{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 f=new AbortController,S=setTimeout(()=>f.abort(),d);c.signal=f.signal;const E=await fetch(r,c);clearTimeout(S);let C=null;const I=E.headers.get("content-type");I&&I.includes("application/json")?C=await E.json():C=await E.text();const R={};E.headers.forEach((N,x)=>{R[x]=N});const U={data:C,status:E.status,statusText:E.statusText,headers:R,config:t};if(!E.ok)throw U;return U}catch(f){if(f instanceof Error&&l>0)return await new Promise(S=>setTimeout(S,u)),this.defaults.baseURL===Pi.apiBase.prod?this.defaults.baseURL=Pi.apiBase.prodAlternate:this.defaults.baseURL===Pi.apiBase.prodAlternate&&(this.defaults.baseURL=Pi.apiBase.prod),this.request({...t,retry:l-1});throw f}}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 EO=3,bO=30,wO=8e3;class PO{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=wO,retry:i=EO,retryDelay:n=bO,baseURL:o=Pi.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 iS({baseURL:o,timeout:r,retry:i,retryDelay:n,responseType:"json"}),this.fetchClient=new iS({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 f,S,E,C,I;const h=t.getValue("telemetry");try{h.injectContext(this.requests.defaults.headers.common);const R=await l(u);return u.url!==h.logsEndpoint&&this.logger.debug("xhr::fetch",{networkCall:{status:R.status,statusText:R.statusText,baseURL:u.baseURL||this.requests.defaults.baseURL,url:u.url,method:u.method}}),R}catch(R){if(!R)throw new P("Unknown network error occurred","0011");if(R instanceof P||R instanceof sl)throw R;((f=R.config)==null?void 0:f.url)!==h.logsEndpoint&&this.logger.error("xhr::fetch",{error:R,networkCall:{status:R.status,statusText:R.statusText,baseURL:((S=R.config)==null?void 0:S.baseURL)||this.requests.defaults.baseURL,url:(E=R.config)==null?void 0:E.url,retries:(C=R.config)==null?void 0:C.retry,method:(I=R.config)==null?void 0:I.method,isOnline:navigator.onLine?"online":"offline"}});const U=R instanceof Error&&R.message||"Network request failed";throw new P(U,"0011"),new sl(R)}}}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 _O=Object.defineProperty,kO=Object.getOwnPropertyDescriptor,nr=(s,t,e,r)=>{for(var i=r>1?void 0:r?kO(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&&_O(t,e,i),i};class Os extends PO{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=co(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=Ms(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=Ms((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 Ms(e)}async startRecording(e,r){return(await this.requests.post("/v2/recordings",{...rS(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 P("Cant fetch transcript s3 url","1801")}}}nr([y.trace("APIClient.getICEServers")],Os.prototype,"getICEServers",1),nr([y.trace("APIClient.startLivestreaming")],Os.prototype,"startLivestreaming",1),nr([y.trace("APIClient.stopLivestreaming")],Os.prototype,"stopLivestreaming",1),nr([y.trace("APIClient.getActiveLivestream")],Os.prototype,"getActiveLivestream",1),nr([y.trace("APIClient.getUserDetails")],Os.prototype,"getUserDetails",1),nr([y.trace("APIClient.startRecording")],Os.prototype,"startRecording",1),nr([y.trace("APIClient.stopRecording")],Os.prototype,"updateRecording",1),nr([y.trace("APIClient.getActiveRecording")],Os.prototype,"getActiveRecording",1),nr([y.trace("APIClient.getActiveTranscript")],Os.prototype,"getActiveTranscript",1);let $h;function CO(s,t){return $h=new Os(s,t),$h}function xt(){return $h}const xn={maxInvocations:5,period:1};function Ut(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 P(`Method rate limit ${u.maxInvocations} invocations/${u.period}sec exceeded`,"0013");return o+=1,n.apply(this,d)},i}}var RO=Object.defineProperty,IO=Object.getOwnPropertyDescriptor,Ds=(s,t,e,r)=>{for(var i=r>1?void 0:r?IO(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&&RO(t,e,i),i};const AO=["text","image","file","custom","poll"],rl={maxInvocations:180,period:60};let ts=(Tv=class extends Lt{constructor(t,e,r,i){const n=t.getValue("logger");super(n);m(this,Ol);m(this,No);p(this,"messages");m(this,re,void 0);m(this,xi,void 0);m(this,rt,void 0);m(this,Xn,void 0);p(this,"maxTextLimit",2e3);g(this,Xn,t),g(this,rt,e),g(this,re,r),g(this,xi,i),this.messages=[]}get telemetry(){return a(this,Xn).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 P("Max character limit breached","0503");if(e&&e.length>0){if(!((i=a(this,re).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,re).permissions)!=null&&n.chatPrivate.text))throw this.logger.error("sendTextMessage::private_chat_permission_denied"),new P("Could not send message to private chat.","0501")}else if(!((c=(o=a(this,re).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,re).permissions)==null?void 0:d.chatPublic)!=null&&l.text))throw this.logger.error("sendTextMessage::public_chat_permission_denied"),new P("Could not send message to public chat.","0501");if(!t)throw this.logger.error("sendTextMessage::message_can_not_be_empty"),new P("Message can not be empty.","0502");let r=[];e&&e.length>0&&(e.push(a(this,re).id),r=a(this,xi).joined.toArray().filter(u=>e.includes(u.id)).map(u=>u.userId),r.push(a(this,re).userId)),a(this,rt).sendMessage(t,es.TEXT,e)}async sendImageMessageInternal(t,e){var i,n,o,c,d,l;if(e&&e.length>0){if(!((i=a(this,re).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,re).permissions)!=null&&n.chatPrivate.files)){this.logger.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((c=(o=a(this,re).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,re).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=xt(),{getLocation:h,putLocation:f}=await u.getPresignedUrls(t.name);await u.uploadFile(t,f);let S=[];e&&e.length>0&&(e.push(a(this,re).id),S=a(this,xi).joined.toArray().filter(E=>e.includes(E.id)).map(E=>E.userId),S.push(a(this,re).userId)),a(this,rt).sendMessage(h,es.IMAGE,e)}catch(u){throw new P("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,re).permissions)!=null&&r.chatPrivate.canSend)||!((i=a(this,re).permissions)!=null&&i.chatPrivate.files)){this.logger.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((o=(n=a(this,re).permissions)==null?void 0:n.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,re).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=xt(),{getLocation:u,putLocation:h}=await l.getPresignedUrls(t.name);await l.uploadFile(t,h);let f=[];e&&e.length>0&&(e.push(a(this,re).id),f=a(this,xi).joined.toArray().filter(E=>e.includes(E.id)).map(E=>E.userId),f.push(a(this,re).userId));const S=JSON.stringify({link:u,name:t.name,size:"size"in t?t.size:0});a(this,rt).sendMessage(S,es.FILE,e)}catch(l){throw new P("Error sending file message.","0500",this.logger)}}get rateLimits(){return rl}updateRateLimits(t,e){rl.maxInvocations=t,rl.period=e}async sendTextMessage(t,e){return this.sendTextMessageInternal(t,e)}async sendCustomMessage(t,e){var n,o,c,d,l,u,h,f,S,E,C,I,R,U,N;if(e&&e.length>0){if(!((n=a(this,re).permissions)!=null&&n.chatPrivate.canSend)||!((o=a(this,re).permissions)!=null&&o.chatPrivate.files)||!((c=a(this,re).permissions)!=null&&c.chatPrivate.text)){this.logger.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((l=(d=a(this,re).permissions)==null?void 0:d.chatPublic)!=null&&l.canSend)||!((h=(u=a(this,re).permissions)==null?void 0:u.chatPublic)!=null&&h.files)||!((S=(f=a(this,re).permissions)==null?void 0:f.chatPublic)!=null&&S.text)){this.logger.error("sendCustomMessage::permission_denied");return}const r=async x=>{try{if(typeof x=="string")return{link:x};const B=xt(),{getLocation:q,putLocation:Z}=await B.getPresignedUrls(x.name);return await B.uploadFile(x,Z),{link:q,type:x.type,name:x.name,size:x.size}}catch(B){throw new P("Error sending image message.","0500",this.logger)}},i={...t,files:await Promise.all((C=(E=t.files)!=null?E:[])==null?void 0:C.map(async x=>r(x))),images:await Promise.all((R=(I=t.images)!=null?I:[])==null?void 0:R.map(async x=>r(x))),videos:await Promise.all((N=(U=t.videos)!=null?U:[])==null?void 0:N.map(async x=>r(x)))};a(this,rt).sendMessage(JSON.stringify(i),es.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,re).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(n=a(this,re).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,rt).editMessage(t,e,es.TEXT)}async editImageMessage(t,e){var i,n,o,c;if(!((n=(i=a(this,re).permissions)==null?void 0:i.chatPublic)!=null&&n.canSend)||!((c=(o=a(this,re).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=xt(),{getLocation:l,putLocation:u}=await d.getPresignedUrls(e.name);await d.uploadFile(e,u),a(this,rt).editMessage(t,l,es.IMAGE)}catch(d){throw new P("Error editing image message.","0500",this.logger)}}async editFileMessage(t,e){var r,i,n,o;if(!((i=(r=a(this,re).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(n=a(this,re).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=xt(),{getLocation:d,putLocation:l}=await c.getPresignedUrls(e.name);await c.uploadFile(e,l),a(this,rt).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),es.FILE)}catch(c){throw new P("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,rt).deleteMessage(t)}async pin(t){if(!a(this,No,Cp))throw new P("Can`t pin message without joining room","0505");try{await a(this,rt).setPinState(t,!0)}catch(e){throw new P(`No message found with id: ${t}`,"0504")}}async unpin(t){if(!a(this,No,Cp))throw new P("Can`t unpin message without joining room","0505");try{await a(this,rt).setPinState(t,!1)}catch(e){throw new P(`No message found with id: ${t}`,"0504")}}async fetchPublicMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await a(this,rt).getChatMessagesPaginated(t,e,r==="before")).messages.map(o=>mo.formatSocketPeerMessage(o))}async fetchPrivateMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after",userId:i}){return(await a(this,rt).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"userId",userId:i})).messages.map(c=>mo.formatSocketPeerMessage(c))}async fetchPinnedMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await a(this,rt).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"pinned",pinned:!0})).messages.map(o=>mo.formatSocketPeerMessage(o))}},re=new WeakMap,xi=new WeakMap,rt=new WeakMap,Xn=new WeakMap,Ol=new WeakSet,xv=function(){return a(this,Xn).getValue("connectionHandler")},No=new WeakSet,Cp=function(){return a(this,Ol,xv).socketJoined===!0},Tv);Ds([y.trace("Chat.sendTextMessage"),Ut(rl)],ts.prototype,"sendTextMessage",1),Ds([y.trace("Chat.sendImageMessage"),Ut({maxInvocations:20,period:60})],ts.prototype,"sendImageMessage",1),Ds([y.trace("Chat.sendFileMessage"),Ut({maxInvocations:20,period:60})],ts.prototype,"sendFileMessage",1),Ds([y.trace("Chat.sendMessage"),Ut({maxInvocations:180,period:60})],ts.prototype,"sendMessage",1),Ds([y.trace("Chat.editTextMessage")],ts.prototype,"editTextMessage",1),Ds([y.trace("Chat.editImageMessage")],ts.prototype,"editImageMessage",1),Ds([y.trace("Chat.editFileMessage")],ts.prototype,"editFileMessage",1),Ds([y.trace("Chat.editMessage")],ts.prototype,"editMessage",1),Ds([y.trace("Chat.deleteMessage")],ts.prototype,"deleteMessage",1),ts=Ds([ct("0500")],ts);var MO=Object.defineProperty,OO=Object.getOwnPropertyDescriptor,DO=(s,t,e,r)=>{for(var i=r>1?void 0:r?OO(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&&MO(t,e,i),i};const Ur=(yv=class{constructor(s,t,e,r){p(this,"chat");p(this,"chatSocketHandler");p(this,"self");m(this,Ui,void 0);g(this,Ui,s),this.chatSocketHandler=t,this.chat=new ts(s,t,e,r),this.self=e,this.setupEvents()}get telemetry(){return a(this,Ui).getValue("telemetry")}get logger(){return a(this,Ui).getValue("logger")}static async init(s,t,e,r){return new Ur(s,t,e,r)}static formatMessage(s){return{...s,time:new Date(s.time),type:AO[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 es.TEXT:{e.message=s.payload;break}case es.IMAGE:{e.link=s.payload;break}case es.FILE:{const{link:r,name:i,size:n}=JSON.parse(s.payload);e.link=r,e.name=i,e.size=n;break}case es.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 Ur.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=Kf.fromBinary(s.payload).messages;this.chat.messages=t.map(e=>Ur.formatSocketPeerMessage(e))}setupEvents(){a(this,Ui).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,async()=>{this.getChatMessages()}),this.chatSocketHandler.on(Ge.sendMessageToRoom,s=>{if(!s.message)return;const t=Ur.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(Ge.sendMessageToPeers,s=>{const t=Ur.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(Ge.editMessage,s=>{if(!s.message)return;const t=Ur.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(Ge.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(Ge.pinMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId),e=Ur.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})})}},Ui=new WeakMap,yv);let mo=Ur;DO([y.trace("ChatController.setupEvents")],mo.prototype,"setupEvents",1);var NO=Object.defineProperty,LO=Object.getOwnPropertyDescriptor,VO=(s,t,e,r)=>{for(var i=r>1?void 0:r?LO(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&&NO(t,e,i),i};let Bh=(Ev=class extends Lt{constructor(t,e,r){const i=t.getValue("logger");super(i);m(this,Dl);m(this,Nl);p(this,"items");m(this,Zn,void 0);m(this,ea,void 0);m(this,Lo,void 0);g(this,Lo,t),g(this,Zn,e),g(this,ea,r),this.items=[]}async create(t,e,r=!1,i=!1){if(!a(this,Nl,$v))throw new P("Can't create polls without joining room","0705");if(!a(this,Zn).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,ea).createPoll(t,e,r,i)}async vote(t,e){if(!a(this,Zn).permissions.polls.canVote){this.logger.error("Polls::vote::permission_denied");return}await a(this,ea).votePoll(t,e)}},Dl=new WeakSet,Uv=function(){return a(this,Lo).getValue("connectionHandler")},Nl=new WeakSet,$v=function(){var t;return((t=a(this,Dl,Uv))==null?void 0:t.socketJoined)===!0},Zn=new WeakMap,ea=new WeakMap,Lo=new WeakMap,Ev);Bh=VO([ct("0700")],Bh);var xO=Object.defineProperty,UO=Object.getOwnPropertyDescriptor,$O=(s,t,e,r)=>{for(var i=r>1?void 0:r?UO(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 Un=(bv=class{constructor(s,t,e){p(this,"polls");m(this,zr,void 0);m(this,ta,void 0);m(this,$i,void 0);this.polls=new Bh(s,t,e),g(this,ta,t),g(this,zr,s),g(this,$i,e),this.setupEvents()}get telemetry(){return a(this,zr).getValue("telemetry")}get logger(){return a(this,zr).getValue("logger")}static async init(s,t,e){return new Un(s,t,e)}canViewPolls(){return a(this,ta).permissions.polls.canView}setupEvents(){const s={[rr.createPoll]:r=>{r.poll&&this.updatePoll(Un.formatSocketServicePoll(r.poll))},[rr.updatePoll]:r=>{r.poll&&this.updatePoll(Un.formatSocketServicePoll(r.poll))},[rr.votePoll]:r=>{r.poll&&this.updatePoll(Un.formatSocketServicePoll(r.poll))}},t=()=>{a(this,zr).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,$i).on(r,s[r])})},e=()=>{a(this,zr).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,$i).removeListeners(r)})};a(this,ta).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,$i).getPolls();if(!(s!=null&&s.payload))return;const{polls:t}=tO.fromBinary(s.payload);this.polls.items=t.map(e=>Un.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}}},zr=new WeakMap,ta=new WeakMap,$i=new WeakMap,bv);let nS=Un;$O([y.trace("PollController.setupEvents")],nS.prototype,"setupEvents",1);var BO=Object.defineProperty,FO=Object.getOwnPropertyDescriptor,HO=(s,t,e,r)=>{for(var i=r>1?void 0:r?FO(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&&BO(t,e,i),i},aS=(s=>(s[s.User=0]="User",s[s.Meeting=1]="Meeting",s))(aS||{});let Fh=(wv=class extends Lt{constructor(t,e,r,i,n){const o=t.getValue("logger");super(o);m(this,Vo);p(this,"selfActiveTab");p(this,"broadcastTabChanges");m(this,sa,void 0);m(this,Bi,void 0);m(this,xo,void 0);p(this,"viewType");p(this,"meetingStartedTimestamp");p(this,"meetingTitle");p(this,"sessionId");g(this,sa,t),g(this,Bi,e),this.viewType=r,g(this,xo,i),this.meetingTitle=n,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return a(this,Vo,Rp).socketState}get mediaState(){return a(this,Vo,Rp).mediaState}get meetingId(){return a(this,sa).getValue("meetingId")}setBroadcastTabChanges(t){if(!a(this,Bi).permissions.canSpotlight)throw this.logger.error("Spotlight::setSpotlighted::permission_denied"),new P("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,Bi).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){a(this,xo).broadcastMessage("spotlight",{userId:a(this,Bi).userId,currentTab:this.selfActiveTab})}},sa=new WeakMap,Vo=new WeakSet,Rp=function(){return a(this,sa).getValue("connectionHandler")},Bi=new WeakMap,xo=new WeakMap,wv);Fh=HO([ct("0800")],Fh);function qO(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 jO=Object.defineProperty,GO=Object.getOwnPropertyDescriptor,oS=(s,t,e,r)=>{for(var i=r>1?void 0:r?GO(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&&jO(t,e,i),i};let $r=(Pv=class extends Lt{constructor(t){const e=t.getValue("logger");super(e);p(this,"transcripts");m(this,Uo,void 0);g(this,Uo,t),this.transcripts=[]}get telemetry(){return a(this,Uo).getValue("telemetry")}static async init(t,e){const r=new $r(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]]=qO(t);return{id:In(),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=>$r.parseTranscript(e,!1)).filter(Boolean):[]}async getActiveTranscript(){try{const t=xt(),{transcript:e}=await t.getActiveTranscript();this.transcripts=$r.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)}},Uo=new WeakMap,Pv);oS([y.trace("Ai.getActiveTranscript")],$r.prototype,"getActiveTranscript",1),$r=oS([ct("0000")],$r);var WO=Object.defineProperty,JO=Object.getOwnPropertyDescriptor,KO=(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&&WO(t,e,i),i};const cS=(_v=class{constructor(s,t,e,r,i,n){p(this,"meta");p(this,"ai");m(this,Yr,void 0);m(this,ra,void 0);p(this,"aiSocketHandler");m(this,Ht,void 0);g(this,Ht,s),this.meta=new Fh(s,t,t.config.viewType,e,n),this.ai=r,g(this,Yr,t),g(this,ra,e),this.aiSocketHandler=i,this.setupEvents()}get telemetry(){return a(this,Ht).getValue("telemetry")}get logger(){return a(this,Ht).getValue("logger")}static async init(s,t,e,r,i){const n=await $r.init(s,t.permissions.transcriptionEnabled);return new cS(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,aS.Meeting),this.meta.emit("activeTabUpdate",s.currentTab))}setupEvents(){a(this,Ht).getValue("peerSessionStore").on(_.TRANSPORT_STATE_UPDATE,s=>{this.meta.emit("mediaConnectionUpdate",s)}),a(this,Ht).getValue("peerSessionStore").on(_.SOCKET_STATE_UPDATE,s=>{this.meta.emit("socketConnectionUpdate",s)}),a(this,Ht).getValue("peerSessionStore").on(_.ROOM_STATE,({createdAt:s,roomUuid:t})=>{const e=this.meta.meetingStartedTimestamp;if(t&&(this.meta.sessionId=t),s&&!e){const r=new Date(s*1e3);this.meta.meetingStartedTimestamp=r,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),a(this,Ht).getValue("peerSessionStore").on(_.PRODUCER_SCORE_UPDATE,({score:s})=>{s<5&&this.meta.emit("poorConnection",{score:s})}),a(this,Yr).permissions.canSpotlight&&(this.logger.info("MetaController::Asserting Spotlight"),this.meta.selfActiveTab&&a(this,ra).broadcastMessage("spotlight",{userId:a(this,Yr).userId,currentTab:this.meta.selfActiveTab})),a(this,Ht).getValue("peerSessionStore").on(_.PEER_JOINED_INTERNAL,async s=>{a(this,Yr).permissions.canSpotlight&&this.meta.selfActiveTab&&a(this,ra).broadcastToPeers("spotlight",[s.id],{userId:a(this,Yr).userId,currentTab:this.meta.selfActiveTab})}),a(this,Ht).getValue("peerSessionStore").on(_.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,Ht).getValue("peerSessionStore").on(_.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)}),this.aiSocketHandler.on($.transcript,s=>{const{meetingId:t,transcript:e,isPartial:r}=s;let i;try{i=$r.parseTranscript(e,r)}catch(d){this.logger.error(`Failed to parse transcript: ${e}`,d)}if(!i){this.logger.warn("Received empty transcript data");return}this.ai.onTranscript(i);const{peerId:n,name:o,transcript:c}=i;this.logger.debug(`${t} Received transcript for peer ${n} - ${o}: ${c}`)})}},Yr=new WeakMap,ra=new WeakMap,Ht=new WeakMap,_v);let dS=cS;KO([y.trace("MetaController.setupEvents")],dS.prototype,"setupEvents",1);const go={},ar={executeWithLock({methodName:s,lockName:t,timeout:e}){return(r,i,n)=>{const o=n.value;return n.value=function(...d){var E,C;const l=(C=(this==null?void 0:this.peerId)||((E=d[0])==null?void 0:E.authToken))!=null?C:"",u=`${t}-${l}`,h=this==null?void 0:this.logger;if(go[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}go[u]=!0;const f=setTimeout(()=>delete go[u],e),S=o.apply(this,d);return Promise.resolve(S).then(()=>{delete go[u],clearTimeout(f)}).catch(()=>{delete go[u],clearTimeout(f)}),S},n}}};var zO=Object.defineProperty,YO=Object.getOwnPropertyDescriptor,ki=(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 Br extends Lt{constructor(e,r,i,n,o){const c=e.getValue("logger");super(c);m(this,Bo);m(this,ia);m(this,ns,void 0);m(this,Ll,void 0);m(this,le,void 0);m(this,$o,void 0);m(this,Ls,void 0);m(this,Ke,void 0);g(this,Ke,e),g(this,ns,n),g(this,Ll,o),g(this,le,r),g(this,$o,i),g(this,Ls,[]),this.setupEvents()}get telemetry(){return a(this,Ke).getValue("telemetry")}get status(){return a(this,Ke).getValue("stageStatus")}setupEvents(){const e={[_.GET_STAGE_REQUESTS]:async n=>{g(this,Ls,n)},[_.UPDATE_STAGE_REQUESTS]:async({add:n})=>{const o=a(this,Ls).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,Ke).getValue("peerSessionStore").onAsync(n,o)})},i=()=>{Object.entries(e).forEach(([n,o])=>{a(this,Ke).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,ns).getStageRequests()):(i(),g(this,Ls,[]),this.emit("stageAccessRequestUpdate",a(this,Ls))))}),a(this,le).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new P("Stage is disabled","2003");if(!a(this,le).permissions.acceptStageRequests)throw this.logger.error("Stage::get_access_request::permission_denied"),new P("You do not have permission to perform this action","2001");const e=a(this,$o).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return g(this,Ls,e),{stageRequests:a(this,Ls)}}async requestAccess(){if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new P("Stage is disabled","2003");if(this.status!=="OFF_STAGE")throw new P(`Unable to request access you are currently ${this.status}`,"2006");if(a(this,le).permissions.stageAccess===G.Allowed){D(this,ia,Du).call(this,"ACCEPTED_TO_JOIN_STAGE");return}a(this,ns).requestAccess(),D(this,ia,Du).call(this,"REQUESTED_TO_JOIN_STAGE")}async cancelRequestAccess(){if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new P("Stage is disabled","2003");a(this,ns).cancelRequestAccess(),D(this,ia,Du).call(this,"OFF_STAGE")}grantAccess(e){if(!a(this,le).roomJoined)throw new P("Can`t grant for participant without joining room");if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new P("Stage is disabled","2003");if(!a(this,le).permissions.acceptStageRequests)throw this.logger.error("Stage::grant_access::permission_denied"),new P("You do not have permission to perform this action","2001");return a(this,ns).grantAccess(e)}denyAccess(e){if(!a(this,le).roomJoined)throw new P("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new P("Stage is disabled","2003");if(!a(this,le).permissions.acceptStageRequests)throw this.logger.error("Stage::deny_access::permission_denied"),new P("You do not have permission to perform this action","2001");return a(this,ns).denyAccess(e)}get peerId(){return a(this,Ke).getValue("peerId")}async join(){const e=a(this,Ke).getValue("viewType");if(this.status==="ON_STAGE")throw new P("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||a(this,le).permissions.stageAccess===G.NotAllowed)throw new P(`Unable to join stage you are currently ${this.status}`,"2006");if(a(this,Ke).setValue("stageStatus","ON_STAGE",!1),await a(this,ns).joinStage(),e===Qs.Livestream){await a(this,Ke).getValue("selfController").joinRoom();return}a(this,Ke).notify("stageStatus"),a(this,le).audioEnabled&&a(this,Bo,Ip).shareMic(a(this,le).audioTrack),a(this,le).videoEnabled&&a(this,Bo,Ip).shareWebcam(a(this,le).videoTrack)}async leave(){if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new P("Stage is disabled","2003");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new P(`Unable to leave stage you are currently ${this.status}`,"2006");a(this,le).setIsPinned(!1),a(this,Ke).setValue("stageStatus","OFF_STAGE",!1),await a(this,ns).leaveStage(a(this,le).userId);try{await a(this,Ke).getValue("peerSessionStore").emitAsync(_.LEAVE_MEDIA_ROOM,"stageLeft")}catch(e){this.logger.error("Stage::leave::emitAsync::failed",{error:e})}a(this,Ke).notify("stageStatus")}async kick(e){if(!a(this,le).roomJoined)throw new P("Can`t kick participant without joining room","2005");if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new P("Stage is disabled","2003");if(!a(this,le).permissions.acceptStageRequests)throw this.logger.error("Stage::kick::permission_denied"),new P("You do not have permissions for kick","2001");return a(this,ns).kick(e)}}ns=new WeakMap,Ll=new WeakMap,le=new WeakMap,$o=new WeakMap,Ls=new WeakMap,Ke=new WeakMap,Bo=new WeakSet,Ip=function(){return a(this,Ke).getValue("roomNodeClient")},ia=new WeakSet,Du=async function(e){this.status!==e&&a(this,Ke).setValue("stageStatus",e)},ki([y.trace("Stage.getStageRequests")],Br.prototype,"getAccessRequests",1),ki([y.trace("Stage.requestAccess")],Br.prototype,"requestAccess",1),ki([y.trace("Stage.cancelRequestAccess")],Br.prototype,"cancelRequestAccess",1),ki([y.trace("Stage.grantAccess")],Br.prototype,"grantAccess",1),ki([y.trace("Stage.denyAccess")],Br.prototype,"denyAccess",1),ki([ar.executeWithLock({methodName:"joinStage",lockName:"Stage.join",timeout:5e3}),y.trace("Stage.joinStage")],Br.prototype,"join",1),ki([y.trace("Stage.leaveStage")],Br.prototype,"leave",1);function QO(s){return!(s.viewType==="LIVESTREAM"||s.viewType==="CHAT")}function Hh(s){switch(s){case tr.UNSPECIFIED:return"OFF_STAGE";case tr.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case tr.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case tr.OFF_STAGE:return"OFF_STAGE";case tr.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var XO=Object.defineProperty,ZO=Object.getOwnPropertyDescriptor,eD=(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};class lS{constructor(t,e,r,i,n){p(this,"stage");m(this,Qr,void 0);m(this,ys,void 0);m(this,Xr,void 0);m(this,Fo,0);m(this,Tt,void 0);g(this,Tt,t),this.stage=new Br(t,i,n,e,r),g(this,Xr,e),g(this,Qr,i),g(this,ys,n),this.setupEvents()}get telemetry(){return a(this,Tt).getValue("telemetry")}get logger(){return a(this,Tt).getValue("logger")}setupEvents(){a(this,Tt).subscribe("stageStatus",t=>{this.stage.emit("stageStatusUpdate",t)}),a(this,Xr).on($.grantStageAccess,()=>{a(this,Qr).permissions.stageAccess!==G.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),a(this,Xr).on($.peerStageStatusUpdate,t=>{t!==void 0&&(t.peerId===a(this,Qr).id?this.selfStageStatusHandler(t):this.peerStageStatusHandler(t))}),a(this,Xr).on($.denyStageAccess,()=>{a(this,Qr).permissions.stageAccess!==G.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),a(this,Xr).on($.getStageRequests,async t=>{var r;if(a(this,Qr).permissions.stageAccess!==G.Allowed)return;const e=(r=t==null?void 0:t.stageRequests)!=null?r:[];await a(this,Tt).getValue("peerSessionStore").emitAsync(_.GET_STAGE_REQUESTS,e),a(this,Fo)<e.length&&e.length>0&&this.stage.emit("newStageRequest",{count:e.length}),g(this,Fo,e.length),this.stage.emit("stageAccessRequestUpdate",e)})}getCurrentStageRequests(){return a(this,ys).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,Tt).setValue("stageStatus",t)}selfStageStatusHandler(t){const e=Hh(t.stageType),r=a(this,Tt).getValue("stageStatus");if(r!==e)switch(t.stageType){case 1:a(this,Tt).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,Tt).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}async peerStageStatusHandler(t){const e=a(this,ys).joined.get(t.peerId),r=a(this,ys).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,Tt).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:a(this,ys).viewMode,page:a(this,ys).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,Tt).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:a(this,ys).viewMode,page:a(this,ys).currentPage});break}a(this,Tt).getValue("peerSessionStore").emit(_.UPDATE_PEER_STAGE_STATUS,{id:e.id,status:e.stageStatus})}}Qr=new WeakMap,ys=new WeakMap,Xr=new WeakMap,Fo=new WeakMap,Tt=new WeakMap,eD([y.trace("Stage.setupEvents")],lS.prototype,"setupEvents",1);var tD=Object.defineProperty,sD=Object.getOwnPropertyDescriptor,qh=(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};let fo=(kv=class extends Mn{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,Fi,void 0);m(this,gr,void 0);m(this,Ho,void 0);m(this,qo,void 0);m(this,Hi,void 0);p(this,"active");p(this,"enabledBy");g(this,Ho,t);const o=t.getValue("meetingId");this.id=`${o}:${e.id}`,this.name=e.name,this.icon=e.icon,g(this,qo,e.component),this.permissions=e.permissions,g(this,Fi,i),g(this,gr,r),this.active=!1,this.enabledBy=""}get component(){return a(this,qo)}get telemetry(){return a(this,Ho).getValue("telemetry")}set activePluginsStore(t){g(this,gr,t)}activateForSelf(){g(this,Hi,new Date),this.active=!0,this.emit("stateUpdate",{active:this.active,pluginId:this.id}),this.emit("enabled")}deactivateForSelf(){g(this,Hi,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,gr))throw new P("Cannot activate plugin: active plugins store is not available yet.","0604");await a(this,gr).set(this.id,{name:this.name,icon:this.icon,id:this.id,enabledBy:a(this,Fi).id}),this.enabledBy=a(this,Fi).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,Fi).id)return;if(!a(this,gr))throw new P("Cannot deactivate plugin: active plugins store is not available yet.","0604");const t=a(this,Hi)?new Date().getTime()-a(this,Hi).getTime():0;await a(this,gr).set(this.id,null),this.deactivateForSelf(),this.logger.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:t}})}},Fi=new WeakMap,gr=new WeakMap,Ho=new WeakMap,qo=new WeakMap,Hi=new WeakMap,kv);qh([y.trace("Plugin.activatePlugin")],fo.prototype,"activate",1),qh([y.trace("Plugin.deactivatePlugin")],fo.prototype,"deactivate",1),fo=qh([ct("0600")],fo);class uS extends Map{constructor(e,r=void 0){const{onAddEvent:i,onDeleteEvent:n,onClearEvent:o}=e;super();m(this,Ue,void 0);m(this,qi,void 0);p(this,"onAddEvent");p(this,"onDeleteEvent");p(this,"onClearEvent");g(this,Ue,new Mn(r)),this.onAddEvent=i,this.onDeleteEvent=n,this.onClearEvent=o,g(this,qi,new Map)}emit(e,...r){return a(this,Ue).emit(e,...r)}on(e,r){return a(this,Ue).on(e,r)}addListener(e,r){return a(this,Ue).addListener(e,r)}off(e,r){return a(this,Ue).off(e,r)}once(e,r){return a(this,Ue).once(e,r)}prependListener(e,r){return a(this,Ue).prependListener(e,r)}prependOnceListener(e,r){return a(this,Ue).prependOnceListener(e,r)}removeListener(e,r){return a(this,Ue).removeListener(e,r)}removeAllListeners(e){return a(this,Ue).removeAllListeners(e)}listeners(e){return a(this,Ue).listeners(e)}listenerCount(e){return a(this,Ue).listenerCount(e)}getMaxListeners(){return a(this,Ue).getMaxListeners()}setMaxListeners(e){return a(this,Ue).setMaxListeners(e)}eventNames(){return a(this,Ue).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,qi).set(e,o),r.on("*",o),i&&a(this,Ue).emit(this.onAddEvent,r),n}delete(e,r=!0,i=!1){const n=this.get(e);if(!n)return!1;n.removeListener("*",a(this,qi).get(e));const o=super.delete(e);return i&&n.removeAllListeners(),r&&a(this,Ue).emit(this.onDeleteEvent,n),o}clear(e=!0,r=!1){this.forEach(n=>{n.removeListener("*",a(this,qi).get(n.id)),r&&n.removeAllListeners()});const i=super.clear();return e&&a(this,Ue).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}Ue=new WeakMap,qi=new WeakMap;class hS extends uS{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 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};let jh=class{constructor(s){p(this,"all");p(this,"active");this.all=new hS(s),this.active=new hS(s)}};jh=nD([ct("0600")],jh);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};const pS=(Cv=class{constructor(s,t,e,r){m(this,Vl);m(this,jo);m(this,Go);m(this,Wo);p(this,"plugins");m(this,Es,void 0);m(this,na,void 0);m(this,Zr,void 0);m(this,ji,null);g(this,Zr,s),this.plugins=t,g(this,na,e),g(this,Es,r),this.setupEvents()}get telemetry(){return a(this,Zr).getValue("telemetry")}get logger(){return a(this,Zr).getValue("logger")}static async init(s,t,e,r){var l,u;const i=s.getValue("logger"),n=s.getValue("connectionHandler"),o=new jh(i);let c;n.socketState.state==="connected"?(i.info("Creating active plugins store immediately. Socket is already connected."),c=await r.create(ph,!0)):i.info("Deferring active plugins store creation until socket connects."),t.forEach(h=>{const f=new fo(s,h,c,e);o.all.add(f)});const d=new pS(s,o,r,c);return c?D(l=d,Wo,Op).call(l):D(u=d,Vl,Bv).call(u),d}cleanup(){D(this,jo,Ap).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,Zr).getValue("peerSessionStore").onAsync(_.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,Es)){this.logger.warn("Active plugins store not available yet on ROOM_JOINED. Sync will be performed when store is created.");return}await D(this,Go,Mp).call(this),this.logger.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to sync active plugins.")})}},Es=new WeakMap,na=new WeakMap,Zr=new WeakMap,ji=new WeakMap,Vl=new WeakSet,Bv=function(){const s=a(this,Zr).getValue("peerSessionStore"),t=async e=>{if(e.state==="connected"&&!a(this,Es))try{g(this,Es,await a(this,na).create(ph,!0)),D(this,jo,Ap).call(this),this.plugins.all.toArray().forEach(r=>{r.activePluginsStore=a(this,Es)}),D(this,Wo,Op).call(this),this.logger.info("Active plugins store created after socket connected"),await D(this,Go,Mp).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(_.SOCKET_STATE_UPDATE,t),g(this,ji,()=>{s.off(_.SOCKET_STATE_UPDATE,t)})},jo=new WeakSet,Ap=function(){a(this,ji)&&(a(this,ji).call(this),g(this,ji,null))},Go=new WeakSet,Mp=async function(){try{await a(this,na).refresh(a(this,Es).name)}catch(t){this.logger.error("Failed to refresh active plugins store, syncing from stale data.",{error:t})}const s=a(this,Es).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())})},Wo=new WeakSet,Op=function(){a(this,Es).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())})})},Cv);let mS=pS;cD([y.trace("PluginController.setupEvents")],mS.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,Jo,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},g(this,Jo,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,Jo).getValue("peerSessionStore").emit(_.SOCKET_STATE_UPDATE,r))}}Jo=new WeakMap;var lD=Object.defineProperty,uD=Object.getOwnPropertyDescriptor,So=(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 gS="Cannot start recording: another recording is already in progress.";let Ci=(Rv=class extends Lt{constructor(t,e){const r=t.getValue("logger");super(r);m(this,ca);m(this,aa,void 0);m(this,oa,void 0);p(this,"recordingPeerIds",[]);p(this,"recordings",[]);g(this,oa,t),g(this,aa,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,oa).getValue("telemetry")}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}async start(t){if(!a(this,aa).permissions.canRecord)throw this.logger.error("Recording::start::permission_denied"),new P("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 P(gS,"1005");try{const e=xt(),{recording:r={}}=a(this,oa).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 sl&&e.status===409?new P(gS,"1005"):new P("Error while starting recording","1000",this.logger)}}async stop(t){await D(this,ca,Nu).call(this,"stop",["RECORDING","PAUSED"],t)}async pause(t){await D(this,ca,Nu).call(this,"pause",["RECORDING"],t)}async resume(t){await D(this,ca,Nu).call(this,"resume",["PAUSED"],t)}},aa=new WeakMap,oa=new WeakMap,ca=new WeakSet,Nu=async function(t,e,r){if(!a(this,aa).permissions.canRecord)throw this.logger.error("Recording::stop::permission_denied"),new P("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 P("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 xt().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 P("Error while stopping recording","1000",this.logger)}})},Rv);So([y.trace("Recording.start")],Ci.prototype,"start",1),So([y.trace("Recording.stop")],Ci.prototype,"stop",1),So([y.trace("Recording.stop")],Ci.prototype,"pause",1),So([y.trace("Recording.stop")],Ci.prototype,"resume",1),Ci=So([ct("1000")],Ci);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};class fS{constructor(t,e,r){p(this,"recording");p(this,"room");m(this,Gi,void 0);g(this,Gi,t),this.recording=new Ci(t,e),this.room=r,this.setupEvents()}get telemetry(){return a(this,Gi).getValue("telemetry")}get logger(){return a(this,Gi).getValue("logger")}getRecordingTypeFromProtoType(t){let e;switch(t){case _i.BROWSER:e="BROWSER";break;case _i.COMPOSITE:e="COMPOSITE";break;case _i.TRACK:e="TRACK";break;default:e="BROWSER"}return e}setupEvents(){a(this,Gi).getValue("peerSessionStore").on(_.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($.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($.recordingPaused,t=>{const e=[...this.recording.recordings];e.forEach(r=>{r.id===t.recordingId&&(r.state="PAUSED")}),this.recording.updateRecordings(e)}),this.room.on($.recordingStopped,t=>{const e=[...this.recording.recordings.filter(r=>r.id!==t.recordingId)];this.recording.updateRecordings(e)})}}Gi=new WeakMap,mD([y.trace("RecordingController.setupEvents")],fS.prototype,"setupEvents",1);class gD{constructor(t){m(this,Wi,void 0);g(this,Wi,t)}hasFeature(t){return a(this,Wi).getValue("logger").warn("Unimplemented method: meeting.__internals__.hasFeature called"),!1}getFeatureValue(t){return a(this,Wi).getValue("logger").warn("Unimplemented method: meeting.__internals__.getFeatureValue called"),null}getAllFeatures(){return a(this,Wi).getValue("logger").warn("Unimplemented method: meeting.__internals__.getAllFeatures called"),{}}}Wi=new WeakMap;class Gh{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=Ee,this.callStats=i}static init(t){return new Gh(t.getValue("authToken"),t.getValue("logger"),new gD(t),t.getValue("callstats"))}}class Wh{constructor(t){p(this,"internals");this.internals=t}static async init(t){const e=Gh.init(t);return new Wh(e)}}var fD=Object.defineProperty,SD=Object.getOwnPropertyDescriptor,$t=(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&&fD(t,e,i),i};class Rt extends Mn{constructor(e,r,i=nl,n=!0){const o=e.getValue("logger");super(o);m(this,He,void 0);m(this,we,void 0);m(this,Te,void 0);m(this,fr,void 0);m(this,as,void 0);m(this,Ko,void 0);m(this,De,void 0);p(this,"audioUpdateInProgress");p(this,"videoUpdateInProgress");g(this,De,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,g(this,He,new wS(e,r)),g(this,we,new WD(e,a(this,He),void 0,i)),g(this,Te,new ZD(e,a(this,He),void 0,i)),g(this,as,new YD(a(this,De),a(this,He))),g(this,fr,new KD(e,a(this,He))),g(this,Ko,n),a(this,we).on("trackMuted",this.onAudioTrackMuted.bind(this)),a(this,we).on("trackChanged",this.onAudioTrackChanged.bind(this)),a(this,Te).on("trackChanged",this.onVideoTrackChanged.bind(this)),a(this,Te).on("trackEnded",this.onVideoTrackEnded.bind(this)),a(this,as).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}get telemetry(){return a(this,De).getValue("telemetry")}set context(e){g(this,De,e)}async onVisibilityChange(){a(this,De).getValue("callstats").tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?a(this,De).getValue("callstats").browserBackgrounded():(a(this,De).getValue("callstats").browserForegrounded(),await this.setupSpeaker())}async repopulateAvailableDevices(){return!0}async setupStreams({audio:e,video:r}){var o;e?a(this,De).getValue("callstats").audioOn():a(this,De).getValue("callstats").audioOff(),r?a(this,De).getValue("callstats").videoOn():a(this,De).getValue("callstats").videoOff();let i,n;if(e&&r)try{const c=await a(this,He).getAudioAndVideoTrack(a(this,we).userSelectedDevice,a(this,Te).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,He).getAudioTrack(!1,a(this,we).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!n&&r)try{n=await a(this,He).getVideoTrack(a(this,Te).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get video track",{error:c})}e&&!i&&a(this,De).getValue("callstats").audioOff(),r&&!n&&a(this,De).getValue("callstats").videoOff(),await a(this,we).setMediaTrack(i),await a(this,Te).setMediaTrack(n);try{await this.setupSpeaker()}catch(c){}if(n){const c=await this.getDeviceById(n.getSettings().deviceId);a(this,De).getValue("callstats").selectedDevice("VIDEO",c)}if(i){const c=await this.getDeviceById(i.getSettings().deviceId);a(this,De).getValue("callstats").selectedDevice("AUDIO",c)}(o=a(this,fr).currentDevice)!=null&&o.deviceId&&a(this,De).getValue("callstats").selectedDevice("SPEAKER",a(this,fr).currentDevice),a(this,He).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})}getCurrentDevices(){return{audio:a(this,we).currentDevice,video:a(this,Te).currentDevice,speaker:a(this,fr).currentDevice}}get permissions(){return a(this,He).permissions}getAllDevices(){return a(this,He).getAvailableDevices()}getDeviceById(e,r){return a(this,He).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return a(this,we).mediaTrack}get audioTrack(){return a(this,we).transformedMediaTrack}get audioEnabled(){return a(this,we).trackEnabled}async enableAudio(e){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{e?await a(this,we).enableTrack(!1,e):await a(this,we).unmuteTrack()}catch(r){}finally{this.audioUpdateInProgress=!1}}}disableAudio(){a(this,we).mediaTrack&&!a(this,we).isCustomTrack?a(this,we).muteTrack():a(this,we).disableTrack()}getAudioDevices(e){return a(this,He).getAudioInputDevices(e)}async setAudioDevice(e,{saveDevicePreference:r}){await a(this,we).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,De).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,fr).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,fr).setupSpeaker(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,De).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,Te).mediaTrack}get videoTrack(){return a(this,Te).transformedMediaTrack}get videoEnabled(){return a(this,Te).trackEnabled}async enableVideo(e){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{e?await a(this,Te).enableTrack(!1,e):await a(this,Te).unmuteTrack()}catch(r){}finally{this.videoUpdateInProgress=!1}}}disableVideo(){a(this,Te).disableTrack()}getVideoDevices(e){return a(this,He).getVideoInputDevices(e)}async setVideoDevice(e,{saveDevicePreference:r}){await a(this,Te).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,De).getValue("callstats").selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async updateVideoConstraints(e){await a(this,Te).updateConstraints(e)}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:a(this,as).audioMediaTrack,video:a(this,as).videoMediaTrack}}get screenShareEnabled(){return a(this,as).trackEnabled}async enableScreenShare(){await a(this,as).enableScreenShare()}async disableScreenShare(){a(this,as).disableScreenShare()}async updateScreenshareConstraints(e){await a(this,as).updateConstraints(e)}getSpeakerDevices(e){return a(this,He).getAudioOutputDevices(e)}addAudioMiddleware(e){return a(this,we).addMiddleware(e)}removeAudioMiddleware(e){return a(this,we).removeMiddleware(e)}removeAllAudioMiddlewares(){return a(this,we).removeAllMiddlewares()}addVideoMiddleware(e){return a(this,Te).addMiddleware(e)}removeVideoMiddleware(e){return a(this,Te).removeMiddleware(e)}removeAllVideoMiddlewares(){return a(this,Te).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return a(this,Te).setVideoMiddlewareGlobalConfig(e)}destruct(){a(this,we).disableTrack(),a(this,Te).disableTrack(),a(this,Te).terminateMiddlewareWebWorker(),a(this,as).disableScreenShare(),a(this,He).destruct()}async onDeviceChange(e,r){var n,o;if(this.emit("DEVICE_LIST_UPDATED",e),r||!a(this,Ko))return;let i=!1;(n=e==null?void 0:e.added)==null||n.reverse().forEach(async c=>{var d;c&&!nl(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,we).disableTrack()}removeVideoTrack(){a(this,Te).disableTrack(),a(this,Te).terminateMiddlewareWebWorker()}async removeDocumentEventListeners(){document.removeEventListener("visibilitychange",this.onVisibilityChange)}}He=new WeakMap,we=new WeakMap,Te=new WeakMap,fr=new WeakMap,as=new WeakMap,Ko=new WeakMap,De=new WeakMap,$t([y.trace("MediaHandler.setupStreams")],Rt.prototype,"setupStreams",1),$t([y.trace("MediaHandler.enableAudio")],Rt.prototype,"enableAudio",1),$t([y.trace("MediaHandler.disableAudio")],Rt.prototype,"disableAudio",1),$t([y.trace("MediaHandler.setAudioDevice")],Rt.prototype,"setAudioDevice",1),$t([y.trace("MediaHandler.enableVideo")],Rt.prototype,"enableVideo",1),$t([y.trace("MediaHandler.disableVideo")],Rt.prototype,"disableVideo",1),$t([y.trace("MediaHandler.setVideoDevice")],Rt.prototype,"setVideoDevice",1),$t([y.trace("MediaHandler.updateVideoConstraints")],Rt.prototype,"updateVideoConstraints",1),$t([y.trace("MediaHandler.enableScreenShare")],Rt.prototype,"enableScreenShare",1),$t([y.trace("MediaHandler.disableScreenShare")],Rt.prototype,"disableScreenShare",1),$t([y.trace("MediaHandler.updateScreenshareConstraints")],Rt.prototype,"updateScreenshareConstraints",1),$t([y.trace("MediaHandler.destruct")],Rt.prototype,"destruct",1),$t([y.trace("MediaHandler.onDeviceChange")],Rt.prototype,"onDeviceChange",1);function il(s,t,e){switch(!0){case Ee.isChromiumBased():switch(t){case"NotAllowedError":return e.includes("by system")?"SYSTEM_DENIED":s==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case Ee.isSafari():switch(t){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case Ee.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 vD=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function nl(s){var e,r;const t=(e=s.label)==null?void 0:e.toLowerCase();return((r=Ee._bowser)==null?void 0:r.getOSName())==="macOS"&&t.includes("iphone")?!0:vD.some(i=>t==null?void 0:t.includes(i))}async function TD(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 yD=s=>(t,e)=>(s.set(t,e),e),SS=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,vS=536870912,TS=vS*2,ED=(s,t)=>e=>{const r=t.get(e);let i=r===void 0?e.size:r<TS?r+1:0;if(!e.has(i))return s(e,i);if(e.size<vS){for(;e.has(i);)i=Math.floor(Math.random()*TS);return s(e,i)}if(e.size>SS)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()*SS);return s(e,i)},yS=new WeakMap,bD=yD(yS),al=ED(bD,yS),wD=s=>s.method!==void 0&&s.method==="call",PD=s=>s.error===null&&typeof s.id=="number",ol=((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(wD(l)){const{params:{timerId:u,timerType:h}}=l;if(h==="interval"){const f=t.get(u);if(typeof f=="number"){const S=r.get(f);if(S===void 0||S.timerId!==u||S.timerType!==h)throw new Error("The timer is in an undefined state.")}else if(typeof f!="undefined")f();else throw new Error("The timer is in an undefined state.")}else if(h==="timeout"){const f=e.get(u);if(typeof f=="number"){const S=r.get(f);if(S===void 0||S.timerId!==u||S.timerType!==h)throw new Error("The timer is in an undefined state.")}else if(typeof f!="undefined")f(),e.delete(u);else throw new Error("The timer is in an undefined state.")}}else if(PD(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:f,timerType:S}=h;r.delete(u),S==="interval"?t.delete(f):e.delete(f)}else{const{error:{message:u}}=l;throw new Error(u)}}),{clearInterval:l=>{const u=al(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=al(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=al(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=al(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})}}))})();`),ES=s=>ol().clearInterval(s),_D=s=>ol().clearTimeout(s),bS=(s,t)=>ol().setInterval(s,t),Jh=Object.freeze(Object.defineProperty({__proto__:null,clearInterval:ES,clearTimeout:_D,setInterval:bS,setTimeout:(s,t)=>ol().setTimeout(s,t)},Symbol.toStringTag,{value:"Module"}));class kD{constructor(t){m(this,Ji,void 0);m(this,zo,void 0);g(this,zo,t)}get logger(){return a(this,zo).getValue("logger")}terminateMiddlewareWebWorker(){if(a(this,Ji))try{ES(a(this,Ji)),g(this,Ji,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(f=>f({canvas:i,WorkerTimers:Jh})));if(r.disablePerFrameCanvasRendering){const S=i.captureStream().getVideoTracks()[0];return Object.defineProperty(S,"originalSettings",{value:e.getSettings()}),S}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 f=0;f<n.length;f+=1)typeof n[f]=="function"&&await n[f](i,d)}catch(f){this.logger.error("getTransformedVideoTrack::middleware_execution_failed",{error:f})}};try{o.play()}catch(f){}o.addEventListener("play",()=>{i.width=o.width||e.getSettings().width,i.height=o.width||e.getSettings().height,g(this,Ji,bS(l,50))},!1);const h=i.captureStream().getVideoTracks()[0];return Object.defineProperty(h,"originalSettings",{value:e.getSettings()}),h}}Ji=new WeakMap,zo=new WeakMap;const CD={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}}},RD=[[320,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2}]],[640,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2}]],[1280,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]],[1920,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]],[3840,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]]],ID=(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=RD,n=i.map(([h])=>h).sort((h,f)=>h-f);let o=Number.MAX_VALUE,c=0;return n.forEach((h,f)=>{Math.abs(h-r)<o&&(o=Math.abs(h-r),c=f)}),i[c][1]};var ce=(s=>(s.WEBCAM="webcam",s.WEBCAM_BACKUP="webcam_backup",s.MIC="mic",s.SCREENSHARE_VIDEO="screenshare_video",s.SCREENSHARE_AUDIO="screenshare_audio",s))(ce||{});const AD=$k(),$n=Ms(AD.config.media);function MD(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 OD{constructor(t,e){m(this,Ki,void 0);m(this,xl,void 0);p(this,"getScreenShareConstraints",()=>{var l,u,h,f,S,E,C,I,R;const t=(l=a(this,Ki))==null?void 0:l.screenshare,e=(h=(u=t==null?void 0:t.width)==null?void 0:u.max)!=null?h:1920,r=(S=(f=t==null?void 0:t.height)==null?void 0:f.max)!=null?S:1080,i=(C=(E=t==null?void 0:t.frameRate)==null?void 0:E.max)!=null?C:5,n=(R=(I=t==null?void 0:t.frameRate)==null?void 0:I.ideal)!=null?R: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,Ki))==null?void 0:n.audio,i=r!=null&&r.enableStereo?2:1;return Ee.isFirefox()||Ee.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,Ki))==null?void 0:o.video,i=t_(CD);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});g(this,xl,t),g(this,Ki,e)}getUpdatedVideoConstraints(t){return t}}Ki=new WeakMap,xl=new WeakMap;class Kh extends Error{constructor(e,r,i){super(r);p(this,"constraints");p(this,"name");this.name=e,this.constraints=i}}class DD{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 ND=Object.defineProperty,LD=Object.getOwnPropertyDescriptor,Ss=(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};let Bt=(Iv=class extends DD{constructor(t,e){super();m(this,da,void 0);m(this,os,void 0);m(this,ze,void 0);g(this,ze,t),g(this,os,new OD(t,e)),g(this,da,new AbortController)}get telemetry(){return a(this,ze).getValue("telemetry")}get logger(){return a(this,ze).getValue("logger")}get constraintsBuilder(){return a(this,os)}async destruct(){var t;(t=a(this,da))==null||t.abort()}handlePermissionErrors(t,e){const r=il(t,e.name,e.message);return this.permissions[t]=r,a(this,ze).getValue("peerSessionStore").emit(_.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(R=>R.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(R=>R.deviceId===e));let f;e&&h?f=e:d&&((n=d[0])!=null&&n.deviceId)&&(f=(o=d[0])==null?void 0:o.deviceId);const S={audio:a(this,os).getAudioConstraints(u).audio,video:a(this,os).getVideoConstraints(f).video};this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(S)});const E=await navigator.mediaDevices.getUserMedia(S);this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(S)});const C=E.getAudioTracks()[0];let I=E.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",I.label.includes("OBS Virtual")){const U=(await this.getVideoInputDevices()).find(N=>N.label.includes("OBS Virtual"));I=await this.getVideoTrack(U.deviceId)}return a(this,ze).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),a(this,ze).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:C,videoTrack:I}}catch(c){throw this.logger.error("WebMediaInterface.getAudioAndVideoTrack",{error:c}),new P("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,ze).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new P("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(f=>f.deviceId!==l),u=a(this,os).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 f=il("audio",h.name,h.message),S=new Kh(h.name,h.message,u);if(f==="COULD_NOT_START"){const E=r.shift();if(!E)throw S;this.logger.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(u),error:h});const C=a(this,os).getAudioConstraints(E.deviceId);return this.logger.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(C)}),o(E.deviceId)}throw S}};try{const l=await o(n);return l.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",a(this,ze).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),l}catch(l){throw l.constraints&&this.handlePermissionErrors("audio",l),new P(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,ze).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new P("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:f}=h;e&&typeof f!="boolean"&&(h={video:{deviceId:f.deviceId}}),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(h)});const[S]=(await navigator.mediaDevices.getUserMedia(h)).getVideoTracks();if(e&&typeof f!="boolean"&&typeof f.width=="object"){const{width:E,height:C}=S.getSettings(),{ideal:I}=f.width;S.applyConstraints({width:{ideal:I},height:{ideal:Math.floor(C*I/E)},frameRate:f.frameRate})}return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(h)}),S}catch(h){const f=il("video",h.name,h.message),S=new Kh(h.name,h.message,u);if(f==="COULD_NOT_START"){const E=r.shift();if(!E)throw S;this.logger.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(u),error:h});const C=a(this,os).getVideoConstraints(E.deviceId);return this.logger.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(C)}),o({video:C.video})}throw S}};try{const u=a(this,os).getVideoConstraints(n),h=await o(u);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",a(this,ze).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),h}catch(u){throw u.constraints&&this.handlePermissionErrors("video",u),new P(u.message,"1602")}}async getScreenShareTracks(){const t=async e=>{try{this.logger.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),a(this,ze).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=il("video",r.name,r.message),n=new Kh(r.name,r.message,e),o={video:!0};if(dk(e,o))throw n;if(i==="COULD_NOT_START")return t(o);throw n}};try{const e=a(this,os).getScreenShareConstraints(),r=await t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",a(this,ze).getValue("peerSessionStore").emit(_.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 P(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 nl(i)?4:n.includes("airpods")||n.includes("airdopes")||n.includes("bluetooth")||n.includes("wireless")||n.includes("headphones")||n.includes("headset")||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 f=r(i),S=r(n);if(f&&!S)return-1;if(!f&&S)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 P("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 P("Failed to get device","1609")}}async onDeviceChange(t){if(Ee.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(f=>f.kind==="audioinput")&&a(this,ze).getValue("callstats").devices("AUDIO",o==null?void 0:o.filter(f=>f.kind==="audioinput")),h.some(f=>f.kind==="videoinput")&&a(this,ze).getValue("callstats").devices("VIDEO",o==null?void 0:o.filter(f=>f.kind==="videoinput")),h.some(f=>f.kind==="audiooutput")&&a(this,ze).getValue("callstats").devices("SPEAKER",o==null?void 0:o.filter(f=>f.kind==="audiooutput")),t(r,d,!1)}},{signal:a(this,da).signal})}}},da=new WeakMap,os=new WeakMap,ze=new WeakMap,Iv);Ss([y.trace("WebMediaInterface.destruct")],Bt.prototype,"destruct",1),Ss([y.trace("WebMediaInterface.handlePermissionErrors")],Bt.prototype,"handlePermissionErrors",1),Ss([y.trace("WebMediaInterface.getAudioAndVideoTrack")],Bt.prototype,"getAudioAndVideoTrack",1),Ss([y.trace("WebMediaInterface.getAudioTrack")],Bt.prototype,"getAudioTrack",1),Ss([y.trace("WebMediaInterface.getVideoTrack")],Bt.prototype,"getVideoTrack",1),Ss([y.trace("WebMediaInterface.getScreenShareTracks")],Bt.prototype,"getScreenShareTracks",1),Ss([y.trace("WebMediaInterface.getAvailableDevices")],Bt.prototype,"getAvailableDevices",1),Ss([y.trace("WebMediaInterface.getAvailableDevicesByKind")],Bt.prototype,"getAvailableDevicesByKind",1),Ss([y.trace("WebMediaInterface.getDevice")],Bt.prototype,"getDevice",1),Ss([y.trace("WebMediaInterface.onDeviceChange")],Bt.prototype,"onDeviceChange",1),Bt=Ss([ct("1600")],Bt);const wS=Bt,Ri={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}},VD=(s=0)=>new Promise(t=>setTimeout(t,s)),xD=(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):VD().then(d))}return d().then(l=>(i.disconnect(),l),l=>{throw i.disconnect(),l})},UD=typeof AudioContext!="undefined"?AudioContext:null;class zh{constructor(t){p(this,"_AudioContext");p(this,"audioContext");p(this,"_audioContextRefContainers");const e={AudioContext:UD,...t};Object.defineProperties(this,{_AudioContext:{value:e.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:zh}})}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 PS=new zh,$D=3,BD=250;function FD(s){const t={},e=PS.getOrCreate(t);let r=$D;function i(){return r-=1,xD(e,s.srcObject,BD).then(n=>n?r>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{PS.release(t)})}async function _S(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 FD(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 HD=Object.defineProperty,qD=Object.getOwnPropertyDescriptor,kS=(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};let cl=class extends Mn{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=>Ri.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>Ri.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 P("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 P("No device received!","1603");this.userSelectedDevice=t.deviceId,e&&this.setUserPreferredDevice(t.deviceId),await this.onSetDevice(t)}async addMiddleware(t){if(Ee.isWebKitBased()&&!(Ee.isSafari()&&wk.test(Ee.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))}};kS([y.trace("BaseMediaHandler.unmuteTrack")],cl.prototype,"unmuteTrack",1),cl=kS([ct("1600")],cl);const CS=cl;var jD=Object.defineProperty,GD=Object.getOwnPropertyDescriptor,Yh=(s,t,e,r)=>{for(var i=r>1?void 0:r?GD(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&&jD(t,e,i),i};const Qh="[Realtimekit]nonSilentDeviceLabels";class dl extends CS{async onSetDevice(t){if(!t)throw this.logger.warn("AudioMediaHandler.setDevice No device received"),new P("No device received!","1603");if(t.kind!=="audioinput")throw this.logger.warn("AudioMediaHandler.setDevice Received non audio device"),new P("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 P(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 TD(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(Ri.getItem(Qh,this.logger));if(o!=null&&o.devices.some(l=>l.label===r.label))return r;if(!await _S(this.logger,r)){const l=(d=o==null?void 0:o.devices.concat({label:r.label}))!=null?d:[{label:r.label}];return Ri.setItem(Qh,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 _S(this.logger,r)){const h=(u=o==null?void 0:o.devices.concat({label:r.label}))!=null?u:[{label:r.label}];return Ri.setItem(Qh,JSON.stringify({devices:h}),this.logger),this.logger.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return this.logger.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1}),r}}Yh([y.trace("AudioMediaHandler.setTransformedTrack")],dl.prototype,"setTransformedTrack",1),Yh([y.trace("AudioMediaHandler.onTrackEnded")],dl.prototype,"onTrackEnded",1),Yh([y.trace("AudioMediaHandler.conditionallyChangeTrack")],dl.prototype,"conditionallyChangeTrack",1);const WD=dl;class JD{constructor(t,e){m(this,zi,void 0);p(this,"currentDevice");p(this,"userPreferredDeviceKey","Realtimekit::speaker::UserDeviceID");p(this,"logger");p(this,"setUserPreferredDevice",t=>Ri.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>Ri.getItem(this.userPreferredDeviceKey,this.logger));g(this,zi,e),this.logger=t.getValue("logger")}async setPreferredSpeaker(){const t=this.getUserPreferredDevice(),e=await a(this,zi).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,zi)instanceof wS))return;let r=t;if(t||([r]=(await a(this,zi).getAvailableDevicesByKind("audiooutput")).filter(d=>!nl(d))),!r)throw new P("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){}})}}zi=new WeakMap;const KD=JD;class zD extends Mn{constructor(e,r){const i=e.getValue("logger");super(i);p(this,"mediaInterface");p(this,"audioMediaTrack");p(this,"videoMediaTrack");m(this,Yo,void 0);g(this,Yo,e),this.mediaInterface=r}get trackEnabled(){return!!this.videoMediaTrack}async enableScreenShare(){var e,r;try{const{audioTrack:i,videoTrack:n}=await this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=i,this.videoMediaTrack=n,this.addMediaTrackListeners(),((r=(e=this.mediaInterface)==null?void 0:e.permissions)==null?void 0:r.screenshare)==="ACCEPTED")return;this.mediaInterface.permissions&&(this.mediaInterface.permissions.screenshare="ACCEPTED",a(this,Yo).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch(i){}}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}async updateConstraints(e){if(!this.videoMediaTrack)throw new P("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new P("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.bind(this)),Ee.isWebKitBased()&&((r=this.videoMediaTrack)==null||r.addEventListener("mute",this.onTrackEnded.bind(this)))}removeMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded),(r=this.videoMediaTrack)==null||r.removeEventListener("mute",this.onTrackEnded)}onTrackEnded(){this.emit("trackEnded")}}Yo=new WeakMap;const YD=zD;var QD=Object.defineProperty,XD=Object.getOwnPropertyDescriptor,ll=(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&&QD(t,e,i),i};class vo extends CS{constructor(e,r,i,n){super(e,r,i,n);m(this,la,void 0);m(this,Qo,{disablePerFrameCanvasRendering:!1});g(this,la,new kD(e))}async onSetDevice(e){if(!e)throw this.logger.warn("VideoMediaHandler.setDevice No device received"),new P("No device received!","1603");if(e.kind!=="videoinput")throw this.logger.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new P("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 P("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,la).getTransformedVideoTrack(this.middlewares,this.mediaTrack,a(this,Qo)),this.emit("trackChanged")}catch(i){this.logger.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}}async setVideoMiddlewareGlobalConfig(e){g(this,Qo,e)}async updateConstraints(e){if(!this._mediaTrack)throw new P("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new P("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,la).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}}la=new WeakMap,Qo=new WeakMap,ll([y.trace("VideoMediaHandler.setTransformedTrack")],vo.prototype,"setTransformedTrack",1),ll([y.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],vo.prototype,"setVideoMiddlewareGlobalConfig",1),ll([y.trace("VideoMediaHandler.onTrackEnded")],vo.prototype,"onTrackEnded",1),ll([y.trace("VideoMediaHandler.conditionallyChangeTrack")],vo.prototype,"conditionallyChangeTrack",1);const ZD=vo,RS=Ms(mh()),ha=class{constructor(t){m(this,yt,void 0);m(this,Yi,void 0);m(this,Xo,void 0);m(this,ua,void 0);if(!t)throw new P("Could not load preset.","0904");g(this,yt,t.config),g(this,Xo,t.name),g(this,Yi,t.ui||Ms(mh().ui)),g(this,ua,t.permissions.plugins.config)}static fromResponse(t){return new ha(t)}static default(){return new ha(RS)}static init(t,e=!0){return!t||e?new ha(RS):new ha(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,Yi).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return a(this,yt).viewType}get livestreamViewerQualities(){return a(this,yt).livestreamViewerQualities||[]}get maxVideoStreams(){return a(this,yt).maxVideoStreams}get maxScreenShareCount(){return a(this,yt).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(a(this,ua)).filter(t=>a(this,ua)[t].disabled)}get designTokens(){return a(this,Yi).designTokens}get configDiff(){return a(this,Yi).configDiff}get isSimulcastEnabled(){var t,e,r,i;return(i=(r=(e=(t=a(this,yt))==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,f,S,E,C,I,R,U,N,x,B,q,Z,se;return{audio:{enableStereo:(i=(r=(e=(t=a(this,yt))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?i:$n.audio.enableStereo,enableHighBitrate:(d=(c=(o=(n=a(this,yt))==null?void 0:n.media)==null?void 0:o.audio)==null?void 0:c.enableHighBitrate)!=null?d:$n.audio.enableHighBitrate},video:{quality:(f=(h=(u=(l=a(this,yt))==null?void 0:l.media)==null?void 0:u.video)==null?void 0:h.quality)!=null?f:$n.video.quality,frameRate:(I=(C=(E=(S=a(this,yt))==null?void 0:S.media)==null?void 0:E.video)==null?void 0:C.frameRate)!=null?I:$n.video.frameRate},screenshare:{quality:(x=(N=(U=(R=a(this,yt))==null?void 0:R.media)==null?void 0:U.screenshare)==null?void 0:N.quality)!=null?x:$n.screenshare.quality,frameRate:(se=(Z=(q=(B=a(this,yt))==null?void 0:B.media)==null?void 0:q.screenshare)==null?void 0:Z.frameRate)!=null?se:$n.screenshare.frameRate}}}get name(){return a(this,Xo)}};let Xh=ha;yt=new WeakMap,Yi=new WeakMap,Xo=new WeakMap,ua=new WeakMap;var e1=Object.defineProperty,t1=Object.getOwnPropertyDescriptor,IS=(s,t,e,r)=>{for(var i=r>1?void 0:r?t1(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 Zh extends Lt{constructor(e,r){const i=e.getValue("logger");super(i);m(this,pa,void 0);p(this,"state","IDLE");p(this,"playbackUrl");p(this,"ingestionCredentials");p(this,"viewerCount");m(this,Zo,void 0);g(this,pa,r),g(this,Zo,e),this.viewerCount=0}get telemetry(){return a(this,Zo).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,pa).permissions.canLivestream)throw this.logger.error("Livestream::start::permission_denied"),new P("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const r=xt(),{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 P("Error while starting livestream","1900",this.logger)}}async stop(){if(!a(this,pa).permissions.canLivestream)throw this.logger.error("Livestream::stop::permission_denied"),new P("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 P("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),await xt().stopLivestreaming()}catch(e){throw this.logger.error("Livestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new P("Error while stopping livestream","1900",this.logger)}}}pa=new WeakMap,Zo=new WeakMap,IS([y.trace("livestream.start")],Zh.prototype,"start",1),IS([y.trace("livestream.stop")],Zh.prototype,"stop",1);var s1=Object.defineProperty,r1=Object.getOwnPropertyDescriptor,i1=(s,t,e,r)=>{for(var i=r>1?void 0:r?r1(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&&s1(t,e,i),i};class AS{constructor(t,e,r){p(this,"livestream");m(this,ma,void 0);m(this,ga,void 0);m(this,Sr,void 0);m(this,Vs,void 0);g(this,Vs,t),g(this,ga,e),this.livestream=new Zh(t,e),g(this,Sr,r),this.setupEvents()}get logger(){return a(this,Vs).getValue("logger")}get telemetry(){return a(this,Vs).getValue("telemetry")}async fetchInitialLivestreamingState(){const t=xt(),{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,Sr).on($.startedLivestream,async t=>{this.livestream.playbackUrl=t.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{a(this,ga).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}}),a(this,Sr).on($.livestreamingInvoked,async t=>{if(t.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{a(this,ga).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}}),a(this,Sr).on($.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),a(this,Sr).on($.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),a(this,Sr).on($.roomPeerCount,t=>{this.livestream.viewerCount=t.count,this.livestream.emit("viewerCountUpdate",t.count)}),a(this,Vs).getValue("peerSessionStore").on(_.PEER_JOINED_INTERNAL,async t=>{var e;((e=t.flags)==null?void 0:e.hiddenParticipant)===!0&&t.recorderType==="LIVESTREAMER"&&(g(this,ma,t.id),this.livestream.setLivestreamState("LIVESTREAMING"))}),a(this,Vs).getValue("peerSessionStore").on(_.PEER_CLOSED,t=>{t.id===a(this,ma)&&(g(this,ma,void 0),this.livestream.setLivestreamState("IDLE"))}),a(this,Vs).getValue("peerSessionStore").onAsync(_.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,Vs).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,async()=>{try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Error: LivestreamController.fetchLivestream")}})}}ma=new WeakMap,ga=new WeakMap,Sr=new WeakMap,Vs=new WeakMap,i1([y.trace("LivestreamController.setupEvents")],AS.prototype,"setupEvents",1);var n1=Object.defineProperty,a1=Object.getOwnPropertyDescriptor,To=(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&&n1(t,e,i),i};class Bn{constructor({name:t,socketHandler:e,meetingId:r}){m(this,Ul);p(this,"name","");m(this,it,{});m(this,ei,"");m(this,ti,void 0);p(this,"rateLimitConfig",{maxInvocations:5,period:1});p(this,"bulkRateLimitConfig",{maxInvocations:5,period:1});p(this,"listeners",{});this.name=t,g(this,ti,e),g(this,ei,r)}async set(t,e,r=!0,i=!1){a(this,it)[t]=e,r&&this.remoteSet(t,e),i&&(this.listeners[t]&&this.listeners[t].forEach(n=>n({[t]:a(this,it)[t]})),this.listeners["*"]&&this.listeners["*"].forEach(n=>n({[t]:a(this,it)[t]})))}remoteSet(t,e){a(this,ti).storeInsertKeys(a(this,ei),this.name,[{key:t,payload:e}])}async bulkSet(t){t.forEach(({key:e,payload:r})=>{a(this,it)[e]=r}),a(this,ti).storeInsertKeys(a(this,ei),this.name,t)}async update(t,e,r=!0){D(this,Ul,Fv).call(this,t,e,r)}async delete(t,e=!0,r=!1){if(a(this,it)[t]&&delete a(this,it)[t],e)return a(this,ti).storeDeleteKeys(a(this,ei),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,it)[e]&&delete a(this,it)[e]}),a(this,ti).storeDeleteKeys(a(this,ei),this.name,t)}get(t){if(a(this,it)[t])return a(this,it)[t]}getAll(){return a(this,it)}clear(){g(this,it,{})}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){g(this,it,t)}}it=new WeakMap,ei=new WeakMap,ti=new WeakMap,Ul=new WeakSet,Fv=function(t,e,r=!0){let i;const n=a(this,it)[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)},To([Ut(xn,"rateLimitConfig")],Bn.prototype,"remoteSet",1),To([Ut(xn,"bulkRateLimitConfig")],Bn.prototype,"bulkSet",1),To([Ut(xn,"rateLimitConfig")],Bn.prototype,"update",1),To([Ut(xn,"rateLimitConfig")],Bn.prototype,"delete",1),To([Ut(xn,"bulkRateLimitConfig")],Bn.prototype,"bulkDelete",1);class o1{constructor(t,e){m(this,ec);m(this,$l);p(this,"stores",new Map);m(this,si,void 0);m(this,ri,"");m(this,tc,void 0);m(this,bs,new Map);g(this,si,e),g(this,ri,t.getValue("meetingId")),g(this,tc,t),D(this,$l,Hv).call(this)}create(t,e=!1){if(Pk.includes(t)&&!e)throw new P(`'${t}' is a reserved store name.`,"0601");const r=new Bn({name:t,socketHandler:a(this,si),meetingId:a(this,ri)});return a(this,si).storeGetKeys(a(this,ri),t,[]),new Promise((n,o)=>{const c=setTimeout(()=>{a(this,bs).delete(t),o(Error("Failed"))},3e3);a(this,bs).set(t,{rejectTimeout:c,resolve:n,store:r})})}refresh(t){const e=this.stores.get(t);return e?(e.clear(),a(this,si).storeGetKeys(a(this,ri),t,[]),new Promise((i,n)=>{const o=setTimeout(()=>{a(this,bs).delete(t),n(Error("Store refresh timed out"))},3e3);a(this,bs).set(t,{rejectTimeout:o,resolve:i,store:e})})):Promise.reject(Error(`Store '${t}' does not exist`))}}si=new WeakMap,ri=new WeakMap,ec=new WeakSet,Dp=function(){return a(this,tc).getValue("peerId")},tc=new WeakMap,bs=new WeakMap,$l=new WeakSet,Hv=function(){[sr.storeInsertKeys,sr.storeGetKeys,sr.storeDeleteKeys].forEach(t=>{a(this,si).on(t,async e=>{var n,o;if(e.pluginId!==a(this,ri))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===sr.storeGetKeys){const c=a(this,bs).get(e.storeName),d=this.stores.get(e.storeName)||(c==null?void 0:c.store);if(a(this,bs).get(e.storeName)&&(this.stores.set(e.storeName,c.store),c.resolve(d),clearTimeout(c.rejectTimeout),a(this,bs).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,bs).get(e.storeName))==null?void 0:o.store);i!==void 0&&(t===sr.storeInsertKeys&&r.forEach(({key:c,peerId:d,payload:l})=>{d!==a(this,ec,Dp)&&i.set(c,l,!1,!0)}),t===sr.storeDeleteKeys&&r.forEach(({key:c,peerId:d})=>{d!==a(this,ec,Dp)&&i.delete(c,!1,!0)}))})})};function Ii(s){var t,e,r,i,n,o,c,d,l,u,h,f,S;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:(S=(f=s.screenShareTracks)==null?void 0:f.video)==null?void 0:S.id}}}}:{}}var c1=Object.defineProperty,d1=Object.getOwnPropertyDescriptor,Fn=(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&&c1(t,e,i),i};const l1=.8,u1=1.2;let or=(Av=class extends Lt{constructor(t,e,r,i){const n=t.getValue("logger");super(n);m(this,Qi);m(this,ii);m(this,Xi);m(this,Bl);m(this,Zi);m(this,rc);m(this,Hl);m(this,ql);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,fa,void 0);p(this,"supportsRemoteControl",!1);m(this,Sa,void 0);p(this,"presetName");m(this,qt,void 0);m(this,vr,void 0);m(this,sc,void 0);m(this,ni,new Map);m(this,Tr,1);m(this,Fl,dh(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>u1&&a(this,Tr)===1?(g(this,Tr,0),a(this,qt).getValue("peerSessionStore").emit(_.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,Tr)})):d<l1&&a(this,Tr)===0&&(g(this,Tr,1),a(this,qt).getValue("peerSessionStore").emit(_.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,Tr)}))},2e3));g(this,qt,t);const{id:o,userId:c,displayName:d,device:l,picture:u,isHost:h,flags:f,stageStatus:S,customParticipantId:E,audioMuted:C,audioTrack:I,videoEnabled:R=!1,videoTrack:U,producers:N,metadata:x}=e;this.id=o,this.userId=c,this.name=d,this.device=l,this.picture=u,this.isHost=h,this.flags=f,this.manualProducerConfig=Sk,g(this,Sa,S!=null?S:"ON_STAGE"),this.customParticipantId=E,this.audioEnabled=!C,this.audioTrack=I,this.videoEnabled=R,this.videoTrack=U,this.screenShareTracks={audio:void 0,video:void 0},this.producers=N!=null?N:[],this.presetName=x==null?void 0:x.preset_name,g(this,fa,!1),g(this,vr,r),g(this,sc,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),D(this,rc,Np).call(this)}get stageStatus(){return a(this,Sa)}get telemetry(){return a(this,qt).getValue("telemetry")}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(this.logger.info("Participant::setVideoEnabled::videoUpdate",{...Ii(this)}),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(this.logger.info("Participant::setAudioEnabled::audioUpdate",{...Ii(this)}),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}))}setScreenShareEnabled(t,e=!0){this.screenShareEnabled=t,e&&this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}setupEvents(){this.on("videoUpdate",D(this,rc,Np)),a(this,ii,Ja)&&(this.on("audioUpdate",D(this,Hl,jv)),this.on("screenShareUpdate",D(this,ql,Gv)))}async pin(){if(!a(this,Xi,dd))throw new P("Can`t pin participant without joining room","1205");if(!a(this,vr).permissions.pinParticipant)throw new P("You do not have permission to pin participants.","1201");return a(this,Qi,cd).pinPeer(this.id)}async unpin(){if(!a(this,Xi,dd))throw new P("Can`t unpin participant without joining room","1205");if(!a(this,vr).permissions.pinParticipant)throw new P("You do not have permission to unpin participants.","1201");return a(this,Qi,cd).pinPeer(null)}setIsPinned(t,e=!0){var i;g(this,fa,t);const r=t?"pinned":"unpinned";(i=a(this,Zi,ld))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}async disableAudio(){const t=this.id;if(this.logger.info("Participant::disable_audio",{participant:{id:t}}),!a(this,Xi,dd))throw new P("Can`t disable participant audio without joining room","1205");if(a(this,vr).permissions.canDisableParticipantAudio)return a(this,Qi,cd).disableAudio(t);throw this.logger.error("Participant::unauthorized_disable_audio",{participant:{id:t}}),new P("Unauthorized: User does not have permission to disable participant audio.","1201")}async kick(){const t=this.id;if(this.logger.info("Participant::kick",{participant:{id:t}}),!a(this,Bl,qv))throw new P("Can`t kick participant without joining room","1205");if(a(this,vr).permissions.kickParticipant){await a(this,qt).getValue("peerSessionStore").emitAsync(_.KICK_PEER,{peerId:t});return}throw this.logger.error("Participant::unauthorized_kick",{participant:{id:t}}),new P("Unauthorized: User does not have permission to kick participants.","1201")}async disableVideo(){const t=this.id;if(this.logger.info("Participant::disable_video",{participant:{id:t}}),!a(this,Xi,dd))throw new P("Can`t disable participant video without joining room","1205");if(a(this,vr).permissions.canDisableParticipantVideo)return a(this,Qi,cd).disableVideo(t);throw this.logger.error("Participant::unauthorized_disable_video",{participant:{id:t}}),new P("Unauthorized: User does not have permission to disable participant video.","1201")}async getPermissions(){return a(this,sc).getUserPermissions(this.userId)}setStageStatus(t){g(this,Sa,t),this.emit("stageStatusUpdate",this)}get isPinned(){return a(this,fa)}registerVideoElement(t){var r,i,n,o;if(!t)return;let e;(i=(r=a(this,ni).get(t))==null?void 0:r.observer)==null||i.disconnect(),"ResizeObserver"in window&&(e=new ResizeObserver(()=>a(this,Fl).call(this,t)),e.observe(t)),a(this,ni).set(t,{observer:e}),this.updateVideo(t),(o=a(this,Zi,ld))==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,Zi,ld))==null||e.removeSource(this.id);return}t.srcObject=void 0,(i=(r=a(this,ni).get(t))==null?void 0:r.observer)==null||i.disconnect(),a(this,ni).delete(t),(n=a(this,Zi,ld))==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"}},fa=new WeakMap,Sa=new WeakMap,qt=new WeakMap,Qi=new WeakSet,cd=function(){return a(this,qt).getValue("roomNodeClient")},ii=new WeakSet,Ja=function(){return a(this,qt).getValue("audioPlayback")},Xi=new WeakSet,dd=function(){return a(this,qt).getValue("connectionHandler").mediaJoined},Bl=new WeakSet,qv=function(){return a(this,qt).getValue("connectionHandler").socketJoined},vr=new WeakMap,sc=new WeakMap,ni=new WeakMap,Zi=new WeakSet,ld=function(){return a(this,qt).getValue("pip")},Tr=new WeakMap,Fl=new WeakMap,rc=new WeakSet,Np=function(){Array.from(a(this,ni).keys()).forEach(this.updateVideo)},Hl=new WeakSet,jv=function(){var t,e;this.audioEnabled&&this.audioTrack?(t=a(this,ii,Ja))==null||t.addParticipantTrack(this.id,this.audioTrack):(e=a(this,ii,Ja))==null||e.removeParticipantTrack(this.id)},ql=new WeakSet,Gv=function(){var t,e;this.screenShareEnabled&&this.screenShareTracks.audio?(t=a(this,ii,Ja))==null||t.addParticipantTrack(`screenshare-${this.id}`,this.screenShareTracks.audio):(e=a(this,ii,Ja))==null||e.removeParticipantTrack(`screenshare-${this.id}`)},Av);Fn([y.trace("Participant.disableAudio")],or.prototype,"disableAudio",1),Fn([y.trace("Participant.kick")],or.prototype,"kick",1),Fn([y.trace("Participant.disableVideo")],or.prototype,"disableVideo",1),Fn([y.trace("Participant.getPermissions")],or.prototype,"getPermissions",1),Fn([y.trace("Participant.setStageStatus")],or.prototype,"setStageStatus",1),or=Fn([ct("1200")],or);class yo extends uS{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 h1 extends Mn{constructor(e){super(e);m(this,ai,void 0);g(this,ai,new Map)}__set(e,r){return a(this,ai).set(e,r)}__clear(){return a(this,ai).clear()}get(e){return a(this,ai).get(e)}toArray(){return Array.from(a(this,ai).values())}}ai=new WeakMap;class p1{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 m1{constructor(){p(this,"_activeSpeakerPeers");p(this,"_compulsoryPeers");this._activeSpeakerPeers=new p1,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)}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 MS=new m1;var g1=Object.defineProperty,f1=Object.getOwnPropertyDescriptor,Ns=(s,t,e,r)=>{for(var i=r>1?void 0:r?f1(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};const S1=["ACTIVE_GRID","PAGINATED","MANUAL"];let ss=(Mv=class extends Lt{constructor(t,e,r){const i=t.getValue("logger");super(i);m(this,ic);m(this,en);m(this,va);p(this,"waitlisted");p(this,"joined");p(this,"active");p(this,"videoSubscribed");p(this,"audioSubscribed");p(this,"pinned");p(this,"all");m(this,Ne,void 0);m(this,tn,void 0);m(this,At,void 0);p(this,"rateLimitConfig",{maxInvocations:5,period:1});p(this,"viewMode");p(this,"currentPage");p(this,"lastActiveSpeaker");p(this,"selectedPeers",MS);g(this,Ne,t),g(this,tn,e),g(this,At,r),this.waitlisted=new yo(i),this.joined=new yo(i),this.videoSubscribed=new yo(i),this.audioSubscribed=new yo(i),this.active=this.videoSubscribed,this.pinned=new yo(i),this.all=new h1(i),this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return a(this,Ne).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get telemetry(){return a(this,Ne).getValue("telemetry")}setupEvents(){a(this,Ne).getValue("peerSessionStore").on(_.E2EE_ACTIVE_CONSUMER,({peerId:e})=>{var r;((r=a(this,Ne).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,Ne).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,Ne))==null?void 0:t.getValue("maxPreferredStreams")}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new P("0 <= Max active participants count limit <= 24","1203");a(this,Ne).setValue("maxPreferredStreams",t),a(this,va,Lu)&&a(this,Ne).getValue("peerSessionStore").emit(_.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,en,ud))throw new P("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,At).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,At).acceptWaitingRoomRequest(e)}async rejectWaitingRoomRequest(t){var r,i;if(!a(this,en,ud))throw new P("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,At).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=>S1.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 P(`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,Ne).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="ACTIVE_GRID"?(this.currentPage=0,a(this,Ne).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="MANUAL"&&(this.currentPage=0,a(this,Ne).getValue("peerSessionStore").emit(_.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 P("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,Ne).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}async unsubscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new P("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,Ne).getValue("peerSessionStore").emit(_.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 P(`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,Ne).getValue("peerSessionStore").emit(_.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,va,Lu))throw new P("Can`t disable all audio without joining room","1205");if(a(this,tn).permissions.canAllowParticipantAudio)return a(this,ic,Lp).muteAll(t);throw this.logger.error("Participants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new P("Unauthorized: User does not have permission to disable peer audio.","1201")}async disableAllVideo(){if(this.logger.info("Participants::disable_all_video"),!a(this,va,Lu))throw new P("Can`t disable all video without joining room","1205");if(a(this,tn).permissions.canAllowParticipantVideo)return a(this,ic,Lp).muteAllVideo();throw this.logger.error("Participants::unauthorized_disable_all_video"),new P("Unauthorized: User does not have permission to disable peer video.","1201")}async kickAll(){if(this.logger.info("Participants::kick_all"),a(this,Ne).getValue("viewType")!=="LIVESTREAM"&&!a(this,en,ud))throw new P("Can`t kick all without joining room","1205");if(!a(this,tn).permissions.kickParticipant)throw this.logger.error("Participants::unauthorized_kick_all"),new P("Unauthorized: User does not have permission to kick peers.","1201");const e=!0;a(this,At).kickAll(e)}async broadcastMessage(t,e,r){if(this.logger.info("Participants::broadcastMessage"),!a(this,en,ud))throw new P("Can`t broadcast message without joining room","1205");if(!(t!=null&&t.trim()))throw new P("`type` must be a non-empty string.","1209");if(r)if("meetingIds"in r)await a(this,At).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,At).broadcastToPeers(t,i,e)}else await a(this,At).broadcastMessage(t,e)}async getAllJoinedPeers(t,e,r){return(await a(this,At).getRoomPeers(t,e,r)).peers.map(cr.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 P("Cannot update permissions, no valid userIDs found","1204");a(this,At).updatePermissions(i,e)}async getParticipantsInMeetingPreJoin(){return a(this,At).getRoomPeersNonPaginated()}},Ne=new WeakMap,ic=new WeakSet,Lp=function(){return a(this,Ne).getValue("roomNodeClient")},en=new WeakSet,ud=function(){var t;return((t=a(this,Ne).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},va=new WeakSet,Lu=function(){var t;return((t=a(this,Ne).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},tn=new WeakMap,At=new WeakMap,Mv);Ns([y.trace("Participants.setViewMode")],ss.prototype,"setViewMode",1),Ns([y.trace("Participants.setPage")],ss.prototype,"setPage",1),Ns([y.trace("Participants.disableAllAudio")],ss.prototype,"disableAllAudio",1),Ns([y.trace("Participants.disableAllVideo")],ss.prototype,"disableAllVideo",1),Ns([y.trace("Participants.kickAll")],ss.prototype,"kickAll",1),Ns([y.trace("Participants.broadcastMessage"),Ut(xn,"rateLimitConfig")],ss.prototype,"broadcastMessage",1),Ns([y.trace("Participants.getAllJoinedPeers"),Ut({maxInvocations:10,period:60})],ss.prototype,"getAllJoinedPeers",1),Ns([y.trace("Participant.updatePermissions"),Ut({maxInvocations:1e3,period:60})],ss.prototype,"updatePermissions",1),Ns([y.trace("Participants.getParticipantsInMeetingPreJoin")],ss.prototype,"getParticipantsInMeetingPreJoin",1),ss=Ns([ct("1200")],ss);var v1=Object.defineProperty,T1=Object.getOwnPropertyDescriptor,Ai=(s,t,e,r)=>{for(var i=r>1?void 0:r?T1(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&&v1(t,e,i),i};const OS=(Ov=class{constructor(s,t,e){p(this,"participants");p(this,"self");p(this,"selectedPeers",MS);p(this,"maxSpatialLayerUpdates",new Map);p(this,"consumerPeerMap");p(this,"events");p(this,"roomSocketHandler");p(this,"context");p(this,"videoPeerConsumerMap",new Map);m(this,cs,{mode:"ACTIVE_GRID",page:0});m(this,ws,!1);m(this,oi,!1);p(this,"updateConsumerSpatialLayers",dh(()=>{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,e=[])=>{this.logger.info(`updateConsumers: Starting consumer updates - AddProducers: ${s.length}, RemoveProducers: ${t.length}, RemoveStaleConsumers: ${e.length}, ConsumersSyncing: ${a(this,ws)}`);try{s.length!==0&&(this.logger.info(`updateConsumers: Creating consumers for ${s.length} producers: [${s.map(r=>r.producerId).join(", ")}]`),await this.roomNodeClient.createConsumers(s),this.logger.info("updateConsumers: Successfully created consumers."))}catch(r){this.logger.error("updateConsumers: Error creating consumers",{error:r})}try{t.length!==0&&(this.logger.info(`updateConsumers: Closing consumers for ${t.length} producers: [${t.map(r=>r.producerId).join(", ")}]`),await this.roomNodeClient.closeConsumers(t),this.logger.info("updateConsumers: Successfully closed consumers."))}catch(r){this.logger.error("updateConsumers: Error closing consumers",{error:r})}try{e.length!==0&&(this.logger.info(`updateConsumers: Closing ${e.length} stale consumers: [${e.join(", ")}]`),await this.roomNodeClient.closeConsumersById(e),this.logger.info("updateConsumers: Successfully closed stale consumers."))}catch(r){this.logger.error("updateConsumers: Error closing stale consumers",{error:r})}this.logger.info("updateConsumers: Completed consumer updates.")});this.context=s,this.roomSocketHandler=e,this.participants=new ss(s,t,this.roomSocketHandler),this.self=t,this.consumerPeerMap=new Map,this.events=fs,t.config.viewType!=="CHAT"&&this.setupEventsGlobal(),this.setupEvents()}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")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}setupEvents(){this.roomSocketHandler.on($.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),this.context.getValue("peerSessionStore").on(_.SOCKET_PEERS,s=>{const t=this.participants.joined.size>0;this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear(),this.participants.pinned.clear(),this.participants.joined.clear(),this.participants.currentPage=0,this.participants.viewMode="ACTIVE_GRID",t&&this.participants.emit("viewModeChanged",{viewMode:"ACTIVE_GRID",currentPage:this.participants.currentPage,pageCount:this.participants.pageCount}),s==null||s.forEach(e=>{e.waitlisted||this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(e))})}),this.roomSocketHandler.on(this.events.peerJoinedBroadcast,({participant:s})=>{this.logger.info("PEER_INFO:::MEDIA_JOIN",{participant:{id:s.peerId,maskedName:[...(s==null?void 0:s.displayName)||""].map((t,e)=>e%2?"*":t).join("")}}),this.onParticipantMediaJoined(s.peerId,s.producerStates)}),this.roomSocketHandler.on(this.events.selfJoinComplete,({participants:s,selectedPeers:t,roomState:e})=>{s.forEach(({peerId:n,producerStates:o})=>this.onParticipantMediaJoined(n,o));const{audioPeers:r,compulsoryPeers:i}=t!=null?t:{};e.pinnedPeerIds.length!==0&&this.onParticipantPinned(e.pinnedPeerIds[0]),this.computeActivateParticipants(r!=null?r:[],i),this.logger.info("selfJoinComplete: Emitting UPDATE_ACTIVE with createAllConsumers=true"),this.context.getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{createAllConsumers:!0})}),this.context.getValue("peerSessionStore").on(_.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(_.NEW_PRODUCER,({peerId:s,producer:t})=>{const e=this.participants.joined.get(s);if(!e){this.logger.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:t==null?void 0:t.producerId,kind:t==null?void 0:t.kind,status:"not_initialized",appData:{screenShare:t==null?void 0:t.screenShare}},participant:{id:s}});return}e.producers.push(t),this.logger.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:t==null?void 0:t.producerId,peerId:s,kind:t==null?void 0:t.kind,status:"not_initialized",appData:{screenShare:t==null?void 0:t.screenShare}}}),(t==null?void 0:t.kind)==="audio"&&this.participants.audioSubscribed.get(s)||(t==null?void 0:t.kind)==="video"&&this.participants.videoSubscribed.get(s)||t!=null&&t.screenShare?(this.logger.info(`NEW_PRODUCER: scheduling syncConsumer (AUTO mode) - Producer: ${t.producerId}, Peer: ${s}, Kind: ${t.kind}, ScreenShare: ${t.screenShare}, ConsumersSyncing: ${a(this,ws)}, VideoSub: ${t.kind==="video"?this.participants.videoSubscribed.has(s):"N/A"}, AudioSub: ${t.kind==="audio"?this.participants.audioSubscribed.has(s):"N/A"}`),this.scheduleSyncConsumers({source:"NEW_PRODUCER_AUTO"})):this.logger.info("ParticipantController::NEW_PRODUCER::not_consuming_producer_auto",{producer:{id:t==null?void 0:t.producerId,peerId:s,kind:t==null?void 0:t.kind,status:"UNKNOWN",appData:{screenShare:t==null?void 0:t.screenShare}}})}),this.context.getValue("peerSessionStore").on(_.PRODUCER_CLOSED,({peerId:s,producerId:t})=>{const e=this.participants.joined.get(s);if(!e){this.logger.warn("ParticipantController::NEW_PRODUCER::participant not found",{participant:{id:s}});return}e.producers=e.producers.filter(r=>r.producerId!==t)}),this.context.getValue("peerSessionStore").on(_.PRODUCER_TOGGLE,({peerId:s,producerId:t,paused:e,kind:r})=>{const i=this.participants.joined.get(s);if(i){r==="audio"&&i.setAudioEnabled(!e);const n=i.producers.find(o=>o.producerId===t);n&&(n.pause=e),r==="video"&&this.context.getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}}),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,ws)}, 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){const t=s.requests.filter(r=>!this.participants.waitlisted.toArray().find(i=>i.userId===r.userId)),e=this.participants.waitlisted.toArray().filter(r=>!s.requests.find(i=>i.userId===r.userId));t.forEach(r=>this.participants.waitlisted.add(new or(this.context,{id:r.peerId,displayName:r.displayName,audioMuted:!0,videoEnabled:!1,audioTrack:void 0,videoTrack:void 0,stageStatus:"OFF_STAGE",userId:r.userId,flags:{},isHost:!1,customParticipantId:r.customParticipantId,picture:r.picture,metadata:{preset_name:r.presetName}},this.self,this.roomSocketHandler))),e.forEach(r=>this.participants.waitlisted.delete(r.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,cs).mode!==s&&(a(this,cs).mode=s),e&&a(this,cs).page!==e&&(a(this,cs).page=e);const{mode:r,page:i}=a(this,cs);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":break;default:throw new Error(`View mode ${s} not supported`)}}async scheduleSyncConsumers({source:s}){var e,r,i;const t=((e=a(this,cs))==null?void 0:e.mode)==="PAGINATED"&&!a(this,ws)?200:0;this.logger.info(`scheduleSyncConsumers():: Source: ${s}, ViewMode: ${(r=a(this,cs))==null?void 0:r.mode}, ConsumersSyncing: ${a(this,ws)}, Delay: ${t}, Page: ${(i=a(this,cs))==null?void 0:i.page}`),setTimeout(()=>this.syncConsumers(),t)}async syncConsumers(){var S,E,C,I,R,U;const s=this.context.getValue("connectionHandler");if((S=s==null?void 0:s.socketState)!=null&&S.state&&s.socketState.state!=="connected"){this.logger.info("syncConsumers: Socket not connected, deferring sync.");return}if(((C=(E=s==null?void 0:s.mediaState)==null?void 0:E.recv)==null?void 0:C.state)!=="connected"){this.logger.info("syncConsumers: Connection not ready, exiting.");return}if(a(this,ws)){g(this,oi,!0),this.logger.info("syncConsumers: Sync in progress, marking resyncRequired=true and exiting.");return}this.logger.info("syncConsumers: Starting sync operation."),g(this,ws,!0),g(this,oi,!1);let t=[];this.participants.videoSubscribed.forEach(N=>{var q,Z;const x=this.participants.joined.get(N.id),B=(Z=(q=N.producers)==null?void 0:q.filter(se=>se.kind==="video"))!=null?Z:[];x&&(B!=null&&B.length)&&B.forEach(se=>{var zt,A,T,w;const at=((A=(zt=x.manualProducerConfig)==null?void 0:zt.video)!=null?A:!0)&&se.kind==="video"&&!se.screenShare,Ct=((w=(T=x.manualProducerConfig)==null?void 0:T.screenshareVideo)!=null?w:!0)&&se.kind==="video"&&se.screenShare;(at||Ct)&&(se.pause||t.push(se))})}),this.participants.audioSubscribed.forEach(N=>{var q,Z;const x=this.participants.joined.get(N.id),B=(Z=(q=N.producers)==null?void 0:q.filter(se=>se.kind==="audio"))!=null?Z:[];x&&(B!=null&&B.length)&&B.forEach(se=>{var zt,A,T,w;const at=((A=(zt=x.manualProducerConfig)==null?void 0:zt.audio)!=null?A:!0)&&se.kind==="audio"&&!se.screenShare,Ct=((w=(T=x.manualProducerConfig)==null?void 0:T.screenshareAudio)!=null?w:!0)&&se.kind==="audio"&&se.screenShare;(at||Ct)&&t.push(se)})}),t=fk(t,N=>N.producerId);const e=new Map;t.forEach(N=>{e.set(N.producerId,N)});const r=(R=(I=this.roomNodeClient)==null?void 0:I.getConsumers())!=null?R:new Map,i=new Map(Array.from(r.values()).map(N=>[N.producerId,N]));let n=t.filter(N=>!i.has(N.producerId));t.filter(N=>!N.consumer&&i.has(N.producerId)).forEach(N=>{const x=i.get(N.producerId);x&&(this.logger.info(`syncConsumers: remapping existing consumer ${x.id} to producer ${N.producerId}`),this.processNewConsumer(x.id))});let c=[],d=Array.from(r.values()).filter(N=>!this.participants.joined.has(N.peerId)).map(N=>N.id),l=Array.from(r.values()).filter(N=>this.participants.joined.has(N.peerId)).map(N=>N.peerId);l=gk(l),l==null||l.forEach(N=>{var B;const x=this.participants.joined.get(N);if(!x){this.logger.warn(`Peer with ${N} doesn't exist in joined list but producers of it are being consumed.`);return}(B=x.producers)!=null&&B.length&&x.producers.forEach(q=>{const Z=q.consumer&&r.has(q.consumer.id);!e.has(q.producerId)&&(i.has(q.producerId)||Z)&&c.push(q)})}),this.logger.info(`syncConsumers: Computed changes - AddProducers: ${n.length} [${n.map(N=>N.producerId).join(", ")}], RemoveProducers: ${c.length} [${c.map(N=>N.producerId).join(", ")}], RemoveStaleConsumers: ${d.length} [${d.join(", ")}]`.substring(0,5e3));const u=35,h=35;n.length>u&&(this.logger.warn(`syncConsumers: Too many remote producers to create consumers: ${n.length}. Only adding ${u} in this run.`),n=n.slice(0,u),this.scheduleSyncConsumers({source:"SOFT_CAPPED_CREATE_CONSUMERS"}));const f=d.length+c.length;f>h&&(this.logger.warn(`syncConsumers: Too many remote consumers to close: ${f}. Only removing ${h} in this run.`),d=d.slice(0,h),c=c.slice(0,h-d.length),this.scheduleSyncConsumers({source:"SOFT_CAPPED_REMOVE_CONSUMERS"}));try{n.length>0||c.length>0||d.length>0?(this.logger.info(`syncConsumers: Calling updateConsumers with changes. Adding ${n.length}, removing ${c.length}, and removing ${d.length} stale consumers.`),await this.updateConsumers(n,c,d),this.logger.info("syncConsumers: updateConsumers completed successfully.")):this.logger.info("syncConsumers: No changes needed, skipping updateConsumers.")}catch(N){this.logger.error("syncConsumers: updateConsumers failed with error.",{error:N})}finally{this.logger.info("syncConsumers: Setting consumersSyncing=false and completing sync."),g(this,ws,!1),(U=s==null?void 0:s.socketState)!=null&&U.state&&s.socketState.state!=="connected"&&g(this,oi,!0)}a(this,oi)&&(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=OS.formatSocketPeerMessage(s);return new or(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("PEER_INFO:::SOCKET_ON_MEDIA_JOIN",{participant:{id:e.id,maskedName:[...(e==null?void 0:e.name)||""].map((r,i)=>i%2?"*":r).join("")}}),this.logger.info(`onParticipantMediaJoined: peer ${s} has joined media room. Processing.`),t.forEach(r=>{r.kind===er.AUDIO&&!r.screenShare?e.setAudioEnabled(!r.pause):r.kind===er.VIDEO&&!r.screenShare&&(e.setVideoEnabled(!r.pause),this.updatePipSource(e.id,!r.pause)),e.producers.push({...r,producingTransportId:r.producingTransportId,kind:r.kind===er.AUDIO?"audio":"video",producingPeerId:s,mimeType:r.mimeType})}),this.logger.info(`onParticipantMediaJoined: Emitting UPDATE_ACTIVE for peer ${s}`),this.context.getValue("peerSessionStore").emit(_.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=>{if(!this.participants.joined.get(o)){this.logger.warn("updateActiveParticipants::participant_not_in_joined_list",{participant:{id:o}});return}s.add(this.participants.joined.get(o),!r.get(o))}),s.emit("participantsUpdate")}updateParticipantsMap(s,t){Array.from(s.keys()).forEach(r=>{t.includes(r)||s.delete(r,!0)}),t.forEach(r=>{s.get(r)||s.add(this.participants.joined.get(r),!0)}),s.emit("participantsUpdate")}updatePinnedParticipants(){this.participants.pinned.forEach(s=>{s.setIsPinned(!1),this.participants.pinned.delete(s.id)})}setupEventsGlobal(){this.roomSocketHandler.on($.joinRoom,({peer:s})=>{s.waitlisted||(this.logger.info("Processing socket join",{peers:s.peerId}),this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(s)),this.logger.info("Processed socket join",{peers:s.peerId}))}),this.roomSocketHandler.on($.leaveRoom,s=>{const{peerId:t}=s.peer;this.selectedPeers.delete(t,this.context),this.onParticipantLeave(t)}),this.context.getValue("peerSessionStore").on(_.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(_.SOCKET_SERVICE_DISCONNECTED,()=>{g(this,oi,!0),this.logger.info("Socket disconnected — keeping participants visible for seamless reconnection")}),this.context.getValue("peerSessionStore").on(_.CONSUMER_PAUSED,({id:s})=>{this.processConsumerPaused(s)}),this.context.getValue("peerSessionStore").on(_.CONSUMER_RESUMED,({id:s})=>{this.processConsumerResumed(s)}),this.context.getValue("peerSessionStore").on(_.NEW_CONSUMER_CREATED,({id:s})=>{this.processNewConsumer(s)}),this.context.getValue("peerSessionStore").on(_.CONSUMER_CLOSED,({id:s})=>{this.processConsumerClosed(s)}),this.context.getValue("peerSessionStore").on(_.ROOM_MESSAGE,async({payload:s,type:t,timestamp:e})=>{this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(_.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(_.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(_.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(_.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(_.UPDATE_ACTIVE,({viewMode:s,page:t,createAllConsumers:e}={})=>{this.logger.info(`UPDATE_ACTIVE event received - viewMode: ${a(this,cs).mode}, page: ${t}, CreateAllConsumers: ${e}`),e&&(this.logger.info(`UPDATE_ACTIVE viewMode: ${s}, Page: ${t}, Removing existing subscriptions.`),this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear()),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.logger.info(`onParticipantSocketJoined: peer ${s.id} has joined socket edge. Processing.`),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.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(_.UPDATE_STAGE_REQUESTS,{request:{displayName:s.name,userId:s.userId,peerId:s.id},add:!0})),this.context.getValue("peerSessionStore").emit(_.PEER_JOINED_INTERNAL,s)}async onParticipantLeave(s){this.logger.info(`peer ${s} has left. Deleting peer from maps and closing consumers.`);const t=this.participants.joined.get(s);this.participants.joined.delete(s,!0,!0),this.participants.pinned.delete(s,!0,!0),this.participants.waitlisted.delete(s,!0,!0),this.roomNodeClient&&this.roomNodeClient.closeConsumers(t==null?void 0:t.producers),t&&t.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&this.context.getValue("peerSessionStore").emit(_.UPDATE_STAGE_REQUESTS,{request:{displayName:t.name,userId:t.userId,peerId:t.id},add:!1});const{currentPage:e}=this.participants,r=this.maxPreferredStreams*(e-1),i=this.participants.videoSubscribed.get(s);this.participants.viewMode==="MANUAL"?this.context.getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:e}):r===0?this.participants.setViewMode("ACTIVE_GRID"):this.participants.joined.size<=r?e===2?this.participants.setViewMode("ACTIVE_GRID"):this.participants.setPage(e-1):i&&this.context.getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:e})}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}),{peerId:e,kind:r,appData:u,remotelyPaused:d,track:n,producerId:o,rtpReceiver:c,localId:l}}processConsumerClosed(s){const{peerId:t,type:e,appData:r,remotelyPaused:i,producerId:n}=this.consumerPeerMap.get(s)||{},o=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.screenShare!==!0&&this.videoPeerConsumerMap.delete(t),!o)return;const c=o.producers.find(l=>l.producerId===n);c&&(c.consumer={id:s,peerId:t,kind:void 0,appData:r,paused:i,producerId:n,rtpReceiver:void 0,localId:void 0});const d=[];r&&r.screenShare?(o.setScreenShareEnabled(!1),this.context.getValue("callstats").consumerSharedMediaState(s,{screen:!1}),o.screenShareTracks.video&&d.push(o.screenShareTracks.video.id),o.screenShareTracks.audio&&d.push(o.screenShareTracks.audio.id),o.screenShareTracks={audio:void 0,video:void 0}):e==="audio"?(o.setAudioEnabled(!1),o.audioTrack&&d.push(o.audioTrack.id),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:!1}),o.audioTrack=void 0):e==="video"&&(o.setVideoEnabled(!1),this.updatePipSource(o.id,!1),o.videoTrack&&d.push(o.videoTrack.id),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!1}),o.videoTrack=void 0),r.e2ee&&d.forEach(l=>{this.context.getValue("peerSessionStore").emit(_.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:l})})}processConsumerResumed(s){var f;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(S=>S.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(_.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),(f=this.context)==null||f.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(_.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(_.E2EE_ACTIVE_CONSUMER,{peerId:t,rtpReceiver:c,track:i}),this.context.getValue("peerSessionStore").emit(_.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=Hh(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(_.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}},cs=new WeakMap,ws=new WeakMap,oi=new WeakMap,Ov);let cr=OS;Ai([y.trace("ParticipantController.setupEvents")],cr.prototype,"setupEvents",1),Ai([y.trace("ParticipantController.setupEvents")],cr.prototype,"setupEventsGlobal",1),Ai([y.trace("ParticipantController.processMedia")],cr.prototype,"processMedia",1),Ai([y.trace("ParticipantController.processConsumerClosed")],cr.prototype,"processConsumerClosed",1),Ai([y.trace("ParticipantController.processConsumerResumed")],cr.prototype,"processConsumerResumed",1),Ai([y.trace("ParticipantController.processConsumerPaused")],cr.prototype,"processConsumerPaused",1),Ai([y.trace("ParticipantController.processNewConsumer")],cr.prototype,"processNewConsumer",1);const Ae=Ms(mh().permissions),Gl=class extends Lt{constructor(e,r,i,n=!1){const o=e.getValue("logger");super(o);m(this,Et);m(this,Y,void 0);m(this,Ta,void 0);m(this,ya,void 0);m(this,jl,e=>{var l,u,h;const{chat:r,connectedMeetings:i,plugins:n,polls:o,media:c,...d}=e;if(r&&(r.private&&Or(a(this,Y).chat.private,r.private),r.public&&Or(a(this,Y).chat.public,r.public),this.emit("chatUpdate")),i&&Or(a(this,Y).connectedMeetings,i),c){const f=E=>{switch(E){case Nr.NONE:return G.Allowed;case Nr.ALLOWED:return G.Allowed;case Nr.NOT_ALLOWED:return G.NotAllowed;case Nr.CAN_REQUEST:return G.CanRequest;default:return}},S={audio:void 0,video:void 0,screenshare:void 0};(l=c.audio)!=null&&l.canProduce&&(S.audio={canProduce:f(c.audio.canProduce)}),(u=c.video)!=null&&u.canProduce&&(S.video={canProduce:f(c.video.canProduce)}),(h=c.screenshare)!=null&&h.canProduce&&(S.screenshare={canProduce:f(c.screenshare.canProduce)}),Or(a(this,Y).media,S)}n&&(Or(a(this,Y).plugins,n),this.emit("pluginsUpdate")),o&&(Or(a(this,Y).polls,o),this.emit("pollsUpdate")),Object.keys(d).length!==0&&Or(a(this,Y),d),this.emit("permissionsUpdate",e)});if(!r)throw this.logger.error("PermissionPreset::load_preset_permissions_failed"),new P("Could not load preset permissions.","0904");g(this,ya,e),g(this,Ta,i),g(this,Y,r),n&&this.setupEvents()}setupEvents(){a(this,ya).getValue("peerSessionStore").on(_.UPDATE_PERMISSIONS,a(this,jl))}static init(e,r,i){let n;return i?n=new Gl(e,i,r,!0):n=new Gl(e,Ae,r),n}get mediaRoomType(){return"CF"}get stageEnabled(){var e;return((e=a(this,Y))==null?void 0:e.stageEnabled)||a(this,Ta)===Qs.Webinar||a(this,Ta)===Qs.Livestream}get acceptStageRequests(){var e,r;return this.stageEnabled?((e=a(this,Y))==null?void 0:e.acceptStageRequests)||((r=a(this,Y))==null?void 0:r.canAcceptProductionRequests):!1}get stageAccess(){var e,r,i;return((e=a(this,Y))==null?void 0:e.stageAccess)===G.NotAllowed?G.NotAllowed:((r=a(this,Y))==null?void 0:r.stageAccess)===G.CanRequest?G.CanRequest:((i=a(this,Y))==null?void 0:i.stageAccess)===G.Allowed||a(this,Y).media.audio.canProduce===G.Allowed||a(this,Y).media.video.canProduce===G.Allowed||a(this,Y).media.screenshare.canProduce===G.Allowed?G.Allowed:a(this,Y).media.audio.canProduce===G.CanRequest||a(this,Y).media.video.canProduce===G.CanRequest||a(this,Y).media.screenshare.canProduce===G.CanRequest?G.CanRequest:G.NotAllowed}get acceptWaitingRequests(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.acceptWaitingRequests)!=null?r:Ae.acceptWaitingRequests}get requestProduceVideo(){var e,r,i;return((i=(r=(e=a(this,Y))==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,Y))==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,Y))==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,Y))==null?void 0:e.disableParticipantAudio)!=null?r:Ae.disableParticipantAudio}get canAllowParticipantScreensharing(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.canAcceptProductionRequests)!=null?r:Ae.canAcceptProductionRequests}get canAllowParticipantVideo(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.disableParticipantVideo)!=null?r:Ae.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.kickParticipant)!=null?r:Ae.kickParticipant}get pinParticipant(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.pinParticipant)!=null?r:Ae.pinParticipant}get canRecord(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.canRecord)!=null?r:Ae.canRecord}get waitingRoomBehaviour(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.waitingRoomType)!=null?r:Ae.waitingRoomType}get plugins(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.plugins)!=null?r:Ae.plugins}get polls(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.polls)!=null?r:Ae.polls}get canProduceVideo(){var r;const e=(r=a(this,Y).media.video.canProduce)!=null?r:Ae.media.video.canProduce;return this.stageEnabled&&(a(this,Et,Yt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Et,Yt)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,Et,Yt)==="OFF_STAGE"||a(this,Et,Yt)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get canProduceScreenshare(){var r;const e=(r=a(this,Y).media.screenshare.canProduce)!=null?r:Ae.media.screenshare.canProduce;return this.stageEnabled&&(a(this,Et,Yt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Et,Yt)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,Et,Yt)==="OFF_STAGE"||a(this,Et,Yt)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get canProduceAudio(){var r;const e=(r=a(this,Y).media.audio.canProduce)!=null?r:Ae.media.audio.canProduce;return this.stageEnabled&&(a(this,Et,Yt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Et,Yt)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,Et,Yt)==="OFF_STAGE"||a(this,Et,Yt)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get chatPublic(){var e,r,i;return(i=(r=(e=a(this,Y))==null?void 0:e.chat)==null?void 0:r.public)!=null?i:Ae.chat.public}get chatPrivate(){var e,r,i;return(i=(r=(e=a(this,Y))==null?void 0:e.chat)==null?void 0:r.private)!=null?i:Ae.chat.private}get connectedMeetings(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.connectedMeetings)!=null?r:Ae==null?void 0:Ae.connectedMeetings}get hiddenParticipant(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.hiddenParticipant)!=null?r:Ae.hiddenParticipant}get showParticipantList(){var e;return(e=a(this,Y).showParticipantList)!=null?e:Ae.showParticipantList}get canChangeParticipantPermissions(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.canChangeParticipantPermissions)!=null?r:Ae.canChangeParticipantPermissions}get canEditDisplayName(){var e;return(e=a(this,Y).canEditDisplayName)!=null?e:!1}get isRecorder(){return a(this,Y).isRecorder}get canSpotlight(){return a(this,Y).canSpotlight}get canLivestream(){return a(this,Y).canLivestream}get transcriptionEnabled(){return a(this,Y).transcriptionEnabled}};let ep=Gl;Y=new WeakMap,Ta=new WeakMap,ya=new WeakMap,jl=new WeakMap,Et=new WeakSet,Yt=function(){return a(this,ya).getValue("stageStatus")};class DS extends Lt{constructor(e,r){super(r);p(this,"localMediaHandler");m(this,jt,void 0);g(this,jt,e)}async updatePermission(){var d,l;const e=(u,h)=>{this.mediaPermissions[u]=h;const f={message:this.mediaPermissions[u],kind:u};h==="DENIED"?a(this,jt).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_ERROR,f):a(this,jt).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,f)};if(Ee.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,jt))==null||i.getValue("callstats").mediaPermission("AUDIO",e),(n=a(this,jt))==null||n.getValue("callstats").mediaPermission("SPEAKER",e);break}case"video":{(o=a(this,jt))==null||o.getValue("callstats").mediaPermission("VIDEO",e);break}case"screenshare":{(c=a(this,jt))==null||c.getValue("callstats").mediaPermission("SCREENSHARE",e);break}}}get peerId(){var e;return(e=a(this,jt))==null?void 0:e.getValue("peerId")}async init(e={},r=!1,i=null){var n,o,c,d,l,u,h;if(Ee.init(),i&&g(this,jt,i),!this.localMediaHandler)try{let f=!0;if((n=i==null?void 0:i.getValue("defaults"))!=null&&n.mediaHandler)f=!1,this.localMediaHandler=i.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:S}=navigator;this.localMediaHandler=await S.init(e)}else this.localMediaHandler=new Rt(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(_.MEDIA_PERMISSION_UPDATE,async S=>{if(this.populateMediaPermissionsInCallstats({message:S.message,kind:S.kind}),S.message==="NOT_REQUESTED")switch(S==null?void 0:S.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",S)}),i==null||i.getValue("peerSessionStore").on(_.MEDIA_PERMISSION_ERROR,async S=>{const{kind:E,message:C,constraints:I}=S;this.populateMediaPermissionsInCallstats({message:C,kind:E}),E==="audio"?(this.logger.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):E==="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:C},constraints:I,mediaPermissionsErrors:{kind:E,message:C}}),this.emit("mediaPermissionError",S),this.emit("mediaPermissionUpdate",{message:C,kind:E})}),f){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 S=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 S}}catch(f){this.logger.error("Self::init::Failed To Setup Streams",{error:{name:f.name,message:f.message}})}}set context(e){g(this,jt,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.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableVideo(){await this.localMediaHandler.enableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}async disableAudio(){this.localMediaHandler.disableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableScreenShare(){await this.localMediaHandler.enableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableScreenShare(){await this.localMediaHandler.disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableVideo(){await this.localMediaHandler.disableVideo(),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.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.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})}}jt=new WeakMap;var y1=Object.defineProperty,E1=Object.getOwnPropertyDescriptor,St=(s,t,e,r)=>{for(var i=r>1?void 0:r?E1(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&&y1(t,e,i),i};let We=(Dv=class extends DS{constructor(t,e,r,i,n){const o=t.getValue("logger");super(t,o);m(this,yr);m(this,Qe);m(this,wa);m(this,$e);m(this,nc);p(this,"name");p(this,"picture");p(this,"customParticipantId");p(this,"waitlistStatus");m(this,Ea,void 0);m(this,bt,void 0);m(this,ba,void 0);p(this,"role");p(this,"userId");p(this,"organizationId");p(this,"supportsRemoteControl",!1);p(this,"device");m(this,Ye,void 0);p(this,"hidden",!1);p(this,"presetName");p(this,"roomState","init");m(this,Pa,new Set);m(this,_a,new Set);g(this,Ye,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=e.customParticipantId,this.waitlistStatus="none",g(this,bt,r),g(this,Ea,i),this.hidden=!1,g(this,ba,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=Ee.isElectron(),this.device=Ee.getDeviceInfo(),this.presetName=n,this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),D(this,nc,Vp).call(this)}get telemetry(){return a(this,Ye).getValue("telemetry")}get stageStatus(){return a(this,Ye).getValue("stageStatus")}get producers(){var t,e;return Array.from((e=(t=a(this,Qe,mt).getProducers())==null?void 0:t.values())!=null?e:[])}get id(){return this.peerId}get peerId(){return a(this,Ye).getValue("peerId")}static async __init__(t,e,r,i,n,o=!1){var f,S,E,C,I,R;let c=(S=(f=t.getValue("defaults"))==null?void 0:f.audio)!=null?S:!0,d=(C=(E=t.getValue("defaults"))==null?void 0:E.video)!=null?C:!0;r.canProduceAudio!=="ALLOWED"&&(c=!1),r.canProduceVideo!=="ALLOWED"&&(d=!1);const l=new We(t,e,r,i,n),u=MD(i.mediaConstraints);Or(u,(I=t.getValue("defaults"))==null?void 0:I.mediaConfiguration);const h=(R=t.getValue("defaults"))==null?void 0:R.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,bt).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",D(this,nc,Vp));const t=a(this,wa,Vu);t&&t.onError(e=>{this.emit("autoplayError",e)}),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::AUDIO_TRACK_CHANGE",{...Ii(this)}),a(this,$e,je)&&this.audioEnabled)try{await a(this,Qe,mt).shareMic(this.audioTrack)}catch(e){this.logger.error("Self::setupEvents::Error while sharing mic",{error:e}),this.localMediaHandler.disableAudio()}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",{...Ii(this)}),a(this,$e,je)&&this.rawVideoTrack===void 0)this.logger.info("Self::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&a(this,$e,je))try{await a(this,Qe,mt).shareWebcam(this.videoTrack)}catch(e){this.logger.error("Self::setupEvents::failed shareWebcam",{error:e}),this.videoEnabled&&await this.localMediaHandler.disableVideo()}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,wa,Vu))==null||r.setSpeakerDevice(e.deviceId))}),this.localMediaHandler.on("DEVICE_LIST_UPDATED",e=>{this.emit("deviceListUpdate",e)}),this.localMediaHandler.on("SCREENSHARE_TRACK_CHANGE",async()=>{if(!a(this,$e,je)){this.logger.error("Self.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{await a(this,Qe,mt).shareScreen(this.screenShareTracks)}catch(e){this.logger.error("Self::setupEvents::Error while sharing screen",{error:e}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.logger.info("Self::setupEvents::SCREENSHARE_TRACK_CHANGE",{...Ii(this)}),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",{...Ii(this)})}),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{var e;(e=a(this,Ye))==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,$e,je)&&await a(this,Qe,mt).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(e=a(this,Ye))==null||e.getValue("callstats").videoOff()}),a(this,bt).on("permissionsUpdate",e=>{var r,i,n;(r=e==null?void 0:e.media)!=null&&r.audio&&a(this,bt).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,bt).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,bt).canProduceScreenshare!==G.Allowed&&(this.disableScreenShare(),this.logger.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return a(this,bt)}get config(){return a(this,Ea)}get roomJoined(){var t;return a(this,Ea).viewType===Qs.Livestream&&this.stageStatus!=="ON_STAGE"?((t=a(this,Ye).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:a(this,$e,je)}setName(t){if(!t)throw new P("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,bt).canProduceAudio===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if((e=a(this,Ye))==null||e.getValue("callstats").audioOn(),await this.localMediaHandler.enableAudio(t),a(this,$e,je)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{await a(this,Qe,mt).shareMic(this.audioTrack)}catch(r){this.logger.error("Self::enableAudio::Error while sharing mic",{error:r}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}}async enableVideo(t){var e;if(a(this,bt).canProduceVideo!==G.NotAllowed&&!(a(this,bt).canProduceVideo===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if((e=a(this,Ye))==null||e.getValue("callstats").videoOn(),await this.localMediaHandler.enableVideo(t),a(this,$e,je)&&this.stageStatus==="ON_STAGE")try{await a(this,Qe,mt).shareWebcam(this.videoTrack)}catch(r){this.logger.error("Self::enableVideo::Error while sharing video",{error:r}),this.videoEnabled&&this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),this.logger.info("Self.enableVideo",{...Ii(this)})}}async updateVideoConstraints(t){if(!this.localMediaHandler.updateVideoConstraints)throw new P("Unsupported","1102");await this.localMediaHandler.updateVideoConstraints(t)}async enableScreenShare(){if(!a(this,$e,je))throw new P("Can`t enable screenshare without joining room","1105");if(a(this,bt).canProduceScreenshare!==G.NotAllowed&&!(a(this,bt).canProduceScreenshare===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.screenShareEnabled&&(await this.localMediaHandler.enableScreenShare(),this.screenShareTracks.audio||this.screenShareTracks.video)){try{await a(this,Qe,mt).shareScreen(this.screenShareTracks)}catch(t){this.logger.error("Self::enableScreenShare::Error while sharing screen",{error:t}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}}async updateScreenshareConstraints(t){if(!this.localMediaHandler.updateScreenshareConstraints)throw new P("Unsupported","1102");await this.localMediaHandler.updateScreenshareConstraints(t)}async disableAudio(){var t;this.audioEnabled&&(this.localMediaHandler.disableAudio(),a(this,$e,je)&&a(this,Qe,mt).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),(t=a(this,Ye))==null||t.getValue("callstats").audioOff())}async disableVideo(){var t;this.videoEnabled&&(await this.localMediaHandler.disableVideo(),a(this,$e,je)&&await a(this,Qe,mt).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(t=a(this,Ye))==null||t.getValue("callstats").videoOff())}async disableScreenShare(){this.screenShareEnabled&&(await this.localMediaHandler.disableScreenShare(),a(this,$e,je)&&await a(this,Qe,mt).disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var i;g(this,ba,t);const r=t?"pinned":"unpinned";(i=a(this,yr,Cn))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}get isPinned(){return a(this,ba)}async pin(){if(!a(this,$e,je))throw new P("Can`t pin participants without joining room","1105");return this.show(),a(this,Qe,mt).pinPeer(this.id)}async unpin(){if(!a(this,$e,je))throw new P("Can`t unpin participants without joining room","1105");return a(this,Qe,mt).pinPeer(null)}async hide(){if(!a(this,$e,je))throw new P("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})}show(){if(!a(this,$e,je))throw new P("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 P("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,$e,je)&&await a(this,Qe,mt).muteSelf(),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,$e,je)&&await a(this,Qe,mt).pauseWebcam(),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,wa,Vu))==null?void 0:t.play()}registerVideoElement(t,e=!1){var r,i;t&&(e?a(this,Pa).add(t):a(this,_a).add(t),this.updateVideo(t),e||(i=a(this,yr,Cn))==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,yr,Cn).removeSource(this.id);return}t.srcObject=void 0,e?a(this,Pa).delete(t):(a(this,_a).delete(t),a(this,yr,Cn).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,yr,Cn))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(n=a(this,yr,Cn))==null||n.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},Ea=new WeakMap,bt=new WeakMap,ba=new WeakMap,Ye=new WeakMap,yr=new WeakSet,Cn=function(){return a(this,Ye).getValue("pip")},Qe=new WeakSet,mt=function(){return a(this,Ye).getValue("roomNodeClient")},wa=new WeakSet,Vu=function(){return a(this,Ye).getValue("audioPlayback")},$e=new WeakSet,je=function(){var t;return((t=a(this,Ye).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Pa=new WeakMap,_a=new WeakMap,nc=new WeakSet,Vp=function(){Array.from(a(this,_a)).forEach(t=>this.updateVideo(t,!1)),Array.from(a(this,Pa)).forEach(t=>this.updateVideo(t,!0))},Dv);St([y.trace("Self.cleanupEvents")],We.prototype,"cleanupEvents",1),St([y.trace("Self.setupEvents")],We.prototype,"setupEvents",1),St([y.trace("Self.setupTracks")],We.prototype,"setupTracks",1),St([y.trace("Self.destructMediaHandler")],We.prototype,"destructMediaHandler",1),St([y.trace("Self.removeDocumentEventListeners")],We.prototype,"removeDocumentEventListeners",1),St([ar.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"Self.toggleAudio",timeout:3e3}),y.trace("Self.enableAudio")],We.prototype,"enableAudio",1),St([ar.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"Self.toggleVideo",timeout:3e3}),y.trace("Self.enableVideo")],We.prototype,"enableVideo",1),St([y.trace("Self.updateVideoConstraints")],We.prototype,"updateVideoConstraints",1),St([y.trace("Self.enableScreenShare"),ar.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3})],We.prototype,"enableScreenShare",1),St([y.trace("Self.updateScreenshareConstraints")],We.prototype,"updateScreenshareConstraints",1),St([ar.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"Self.toggleAudio",timeout:3e3}),y.trace("Self.disableAudio")],We.prototype,"disableAudio",1),St([ar.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"Self.toggleVideo",timeout:3e3}),y.trace("Self.disableVideo")],We.prototype,"disableVideo",1),St([ar.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3}),y.trace("Self.disableScreenShare")],We.prototype,"disableScreenShare",1),St([y.trace("Self.setDevice")],We.prototype,"setDevice",1),We=St([ct("1100")],We);class tp extends Error{constructor(t){super(t!=null?t:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,tp)}}class sp extends Error{constructor(t){super(t!=null?t:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,sp)}}class rp{constructor(t,e=!1){p(this,"pendingTasks",new Map);p(this,"nextTaskId",0);p(this,"stopping",!1);m(this,ac,void 0);this.log=e,g(this,ac,{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 tp);this.stopping=!1}remove(t){const e=Array.from(this.pendingTasks.values())[t];e&&e.reject(new sp)}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,ac).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)}}}ac=new WeakMap;class Eo extends Error{constructor(t){super(t),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Eo):this.stack=new Error(t).stack}}class It extends Error{constructor(t){super(t),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,It):this.stack=new Error(t).stack}}class Fr extends Error{constructor(t){super(t),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,It):this.stack=new Error(t).stack}}const NS=s=>new Promise(t=>setTimeout(t,s));async function LS(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 NS(o*(c+1)):i==="exponential"&&await NS(o*(c+Math.max(0,c-1)));else break}c+=1}return r(d)})}function b1(s){return s.map(t=>({channels:t.channels,clockRate:t.clockRate,mimeType:t.mimeType,sdpFmtpLine:t.sdpFmtpLine}))}function w1(s){return s.map(t=>({uri:t.uri}))}function ul(s){return{codecs:b1(s.codecs),headerExtensions:w1(s.headerExtensions?s.headerExtensions:[])}}function P1(s){const t=RTCRtpReceiver.getCapabilities("audio"),e=RTCRtpReceiver.getCapabilities("video"),r=RTCRtpSender.getCapabilities("audio"),i=RTCRtpSender.getCapabilities("video");s&&(e.codecs=e.codecs.filter(({mimeType:d})=>s===d),i.codecs=i.codecs.filter(({mimeType:d})=>s===d));const n={audio:ul(t),video:ul(e)};return{sender:{audio:ul(r),video:ul(i)},receiver:n}}class hl extends ft.EventEmitter{constructor(e){super();m(this,oc,void 0);g(this,oc,e),this.setMaxListeners(1/0)}get logger(){return a(this,oc).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)}})}}oc=new WeakMap;var VS={},pl={},_1={get exports(){return pl},set exports(s){pl=s}},xS=_1.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(xS).forEach(function(s){var t=xS[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=pl,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 f=h[0],S=h.slice(2);f==="m"&&(l.push({rtp:[],fmtp:[]}),u=l[l.length-1]);for(var E=0;E<(i[f]||[]).length;E+=1){var C=i[f][E];if(C.reg.test(S))return r(C,u,S)}}),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}})})}}(VS);var ip=pl,k1=/%[sdv%]/g,C1=function(s){var t=1,e=arguments,r=e.length;return s.replace(k1,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""}})},bo=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 C1.apply(null,i)},R1=["v","o","s","i","u","e","p","c","b","t","r","z","a"],I1=["i","c","b","a"],A1=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||R1,r=t.innerOrder||I1,i=[];return e.forEach(function(n){ip[n].forEach(function(o){o.name in s&&s[o.name]!=null?i.push(bo(n,o,s)):o.push in s&&s[o.push]!=null&&s[o.push].forEach(function(c){i.push(bo(n,o,c))})})}),s.media.forEach(function(n){i.push(bo("m",ip.m[0],n)),r.forEach(function(o){ip[o].forEach(function(c){c.name in n&&n[c.name]!=null?i.push(bo(o,c,n)):c.push in n&&n[c.push]!=null&&n[c.push].forEach(function(d){i.push(bo(o,c,d))})})})}),i.join(`\r
|
|
16
15
|
`)+`\r
|
|
17
|
-
`},Mi=AS,w1=b1,hl=w1,Oi=Mi.parse;Mi.parseParams,Mi.parseFmtpConfig,Mi.parsePayloads,Mi.parseRemoteCandidates,Mi.parseImageAttributes,Mi.parseSimulcastStreamList;class pl extends tp{constructor(e,r){super(e);p(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new pl(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,f)=>{var D;const S=Oi(h),E=S.media[S.media.length-1],k=E.rtp.filter(x=>f.some(B=>B.name===x.codec)),I=E.fmtp.filter(x=>k.some(B=>B.payload===x.payload)),R=(D=E.rtcpFb)==null?void 0:D.filter(x=>k.some(B=>B.payload===x.payload)),U=k.map(x=>x.payload);return S.media[S.media.length-1].rtp=k,S.media[S.media.length-1].fmtp=I,S.media[S.media.length-1].rtcpFb=R,S.media[S.media.length-1].payloads=U.join(" "),hl(S)},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),e==="audio"||e.kind==="audio"){const{enableDtx:h,enableStereo:f}=this,S=this.enableHighBitrate?f?128e3:64e3:f?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${f?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${S}`)}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 tp{static createFactory(t){return()=>new ip(t)}get name(){return"Safari12"}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection(),this.logger.debug("Safari12::creating new transceiver");const n=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e}),o=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`Safari12::senders available params: ${JSON.stringify(o)}`);const c=[];r&&r.length>0&&r.forEach(u=>{var f;const h=o.codecs.find(S=>S.mimeType.includes(u.name));if(u.parameters){this.logger.info(`Safari12::codecOption.parameters:, ${JSON.stringify(u.parameters)}`);const S=((f=h.sdpFmtpLine)==null?void 0:f.split(";"))||[];S.push(...u.parameters);const E=[...new Set(S).values()];h.sdpFmtpLine=E.join(";")}c.push(h)}),this.logger.info(`Safari12::selected codecs: ${JSON.stringify(c)}`),n.setCodecPreferences(c);const d=await this.pc.createOffer();if(await this.pc.setLocalDescription(d),t==="audio"||t.kind==="audio"){const{enableStereo:u,enableDtx:h}=this,f=this.enableHighBitrate?u?128e3:64e3:u?64e3:32e3;d.sdp=d.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${u?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${f}`)}return this.midTransceiverMap.set(n.mid,n),{offerSdp:d,callback:async u=>(this.logger.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(u)}]`),await this.pc.setRemoteDescription(u),n.mid),sender:n.sender,mid:n.mid}}}function P1(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}class _1 extends ll{constructor(e,r){var i;super(e);m(this,Us);m(this,cc);m(this,jl);m(this,Gl);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,oc,void 0);m(this,sn,void 0);m(this,xs,void 0);m(this,ql,void 0);this.id=r.id,this.localId=r.localId,g(this,oc,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,g(this,xs,!1),this.producerId=r.producerId,this.track=r.track,g(this,sn,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,N(this,jl,Uv).call(this),g(this,ql,e)}get closed(){return a(this,xs)}get kind(){return this.track.kind}get paused(){return a(this,sn)}close(e,r){a(this,xs)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,a(this,Us,vi)),g(this,xs,!0),r&&(N(this,Gl,$v).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(a(this,xs))throw new Rt("closed");return a(this,oc).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",a(this,Us,vi)),a(this,xs)){this.logger.error("consumer::pause() | Consumer closed",a(this,Us,vi));return}g(this,sn,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",a(this,Us,vi)),a(this,xs)){this.logger.error("Consumer::resume() | Consumer closed",a(this,Us,vi));return}g(this,sn,!1),this.track.enabled=!0,this.safeEmit("resume")}}oc=new WeakMap,sn=new WeakMap,xs=new WeakMap,ql=new WeakMap,Us=new WeakSet,vi=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},cc=new WeakSet,Op=function(){this.logger.debug('Consumer::track "ended" event',a(this,Us,vi)),this.safeEmit("trackended")},jl=new WeakSet,Uv=function(){this.track.addEventListener("ended",N(this,cc,Op).bind(this))},Gl=new WeakSet,$v=function(){try{this.track.removeEventListener("ended",N(this,cc,Op)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...a(this,Us,vi),error:e})}};class k1 extends ll{constructor(e,r){var i,n;super(e);m(this,jt);p(this,"id");p(this,"localId");m(this,Ps,void 0);p(this,"kind");p(this,"appData");p(this,"rtpSender");m(this,Pa,void 0);m(this,_a,void 0);m(this,rn,void 0);m(this,cs,!1);m(this,nt,void 0);m(this,oi,void 0);m(this,ka,void 0);m(this,Wl,void 0);this.id=r.id,this.localId=r.localId,g(this,nt,r.track),this.kind=(i=r.track)==null?void 0:i.kind,g(this,oi,r.disableTrackOnPause?!((n=r.track)!=null&&n.enabled):!1),g(this,ka,void 0),g(this,Pa,r.stopTracks),g(this,_a,r.disableTrackOnPause),g(this,rn,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),g(this,Ps,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),g(this,Wl,e)}get closed(){return a(this,cs)}get track(){return a(this,nt)}get paused(){return a(this,oi)}get maxSpatialLayer(){return a(this,ka)}async close(e){if(a(this,cs))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,a(this,jt,Cs)),g(this,cs,!0),this._destroyTrack(),e===Eo){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await a(this,Ps).stopSending(this.localId),{answer:n}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(n)}async getStats(){if(a(this,cs))throw new Rt("closed");return a(this,Ps).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",a(this,jt,Cs)),a(this,cs)&&this.logger.error("Producer::pause() | Producer closed",a(this,jt,Cs)),g(this,oi,!0),a(this,nt)&&a(this,_a)&&(a(this,nt).enabled=!1),a(this,rn)&&a(this,Ps).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",a(this,jt,Cs)),a(this,cs)){this.logger.error("Producer::resume() | Producer closed",a(this,jt,Cs));return}g(this,oi,!1),a(this,nt)&&a(this,_a)&&(a(this,nt).enabled=!0),a(this,rn)&&a(this,Ps).replaceTrack(this.localId,a(this,nt)),this.emit("resume")}async replaceTrack({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,a(this,jt,Cs)),a(this,cs)){if(e&&a(this,Pa))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...a(this,jt,Cs),error:r})}throw new Rt("closed")}else if(e&&e.readyState==="ended")throw new Rt("track ended");if(e===a(this,nt)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,a(this,jt,Cs));return}(!a(this,rn)||!a(this,oi))&&await a(this,Ps).replaceTrack(this.localId,e),this._destroyTrack(),g(this,nt,e),this._handleTrack()}async setMaxSpatialLayer(e){if(a(this,cs))throw new Rt("closed");if(this.kind!=="video")throw new To("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await a(this,Ps).setMaxSpatialLayer(this.localId,e),g(this,ka,e)}async setRtpEncodingParameters(e){if(a(this,cs))throw new Rt("closed");if(typeof e!="object")throw new TypeError("invalid params");await a(this,Ps).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,a(this,jt,Cs)),this.safeEmit("trackended",this.track.id)}_handleTrack(){a(this,nt)&&a(this,nt).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(a(this,nt))try{a(this,nt).removeEventListener("ended",this._onTrackEnded),a(this,Pa)&&a(this,nt).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...a(this,jt,Cs),error:r})}}}Ps=new WeakMap,Pa=new WeakMap,_a=new WeakMap,rn=new WeakMap,cs=new WeakMap,nt=new WeakMap,oi=new WeakMap,ka=new WeakMap,Wl=new WeakMap,jt=new WeakSet,Cs=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};const Eo="transport closed",Ra=class extends ll{constructor(e,{id:r,direction:i,handlerFactory:n,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:u,config:h}){var k,I,R;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,Ca,void 0);g(this,Ca,e);const f=e.getValue("logger");f.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const S=P1(l,{});delete S.iceServers,delete S.iceTransportPolicy,delete S.bundlePolicy,delete S.rtcpMuxPolicy,delete S.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new ep(f,!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=(R=h==null?void 0:h.enableDtx)!=null?R:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:o,iceTransportPolicy:c,additionalSettings:l,proprietaryConstraints:d}),this.appData=u||{};const E=3e4;this.transportConnectionPromise=new Promise(U=>{const D=setTimeout(()=>{f.error("ICE connection timeout - possible firewall blocking WebRTC or TURN unreachable",{transport:{id:this.id,type:this.direction}}),U(!1)},E);this.once("connected",()=>{clearTimeout(D),U(!0)}),this.once("disconnect",()=>{clearTimeout(D),U(!1)}),this.once("close",()=>{clearTimeout(D),U(!1)})}),this.handler.on("@connectionstatechange",U=>{U!==this.connectionState&&(this.logger.debug(`connection state changed to ${U}`),this.connectionState=U,U==="connected"&&(this.connected=!0,this.emit("connected")),U==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(U==="failed"||U==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",U))}),this.handler.on("@icecandidate",({candidate:U})=>{this.closed||this.safeEmit("icecandidate",U)})}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(Eo).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(Eo)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new Rt("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 Rt("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new To("not a sending Transport");if(r.readyState==="ended")throw new Rt("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 Br("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:f,localId:S,rtpSender:E}=await this.awaitQueue.push(async()=>{const{offerSdp:k,callback:I,sender:R,mid:U}=await this.handler.send({track:n,encodings:o,codecOptions:c,screenShare:h==null?void 0:h.screenShare}),{answer:D,producerId:x}=await r({offer:k,kind:n.kind,paused:l?!n.enabled||Object.hasOwn(n,"fakeTracks"):!1,appData:{...h||{},mid:U},codecOptions:c,producingTransportId:this.serverId}),B=await I(D);return{producerId:x,localId:B,rtpSender:R}},"Transport.produce");return this.createProducerObject({id:f,localId:S,track:n,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:u,appData:h,handler:this.handler,rtpSender:E})}async createProducerObject(e){const r=new k1(a(this,Ca),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 Rt("closed");if(this.direction!=="recv")throw new To("not a receiving transport");if(!await this.transportConnectionPromise)throw new Br("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(f=>l.push(f)).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=Oi(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=Oi(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:hl(n)}}static parseHeaderExtensionMappings(e){const r=Oi(e.sdp),i={};return r.media.forEach(n=>{i[n.mid]=n.ext}),i}static setHeaderExtensionMappings(e,r){const i=Oi(e.sdp);return i.media=i.media.map(o=>{const c={...o};return c.ext=r[o.mid],c}),{...e,sdp:hl(i)}}async closeConsumers(e,r){try{const i=e.map(l=>l.transceiver.mid),n=Ra.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=Ra.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=Ra.setCodecAndFmtpMappings(c,i,n),c=Ra.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=Oi(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=hl(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:f}=e,S=`${c}:${h}`,E={...e,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(k,I)=>{const R=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${S} producingPeerId: ${n}`),this.consumerTrackEvents.delete(S),E.isTimedout=!0,I(E)},5e3),U=(x,B)=>{try{if(x.readyState==="ended")clearTimeout(R),I(E);else{const q=x;q.enabled=!0,this.handler.midTransceiverMap.set(B.mid,B);const Z=new _1(a(this,Ca),{id:r,localId:B.mid,transceiver:B,track:q,paused:d,producerId:i,producingPeerId:n,producingTransportId:o,handler:this.handler,appData:{...u,screenShare:l,peerId:n},rtpReceiver:B.receiver,mimeType:f});this.consumers.set(r,Z),Z.once("close",()=>{this.consumers.delete(Z.id),this.handler.midTransceiverMap.delete(B.mid)}),this.logger.info(`consumer created for peerId: ${n} of kind: ${h} with screenShare: ${l}`,{consumer:{id:r,kind:h,appData:{screenShare:l},peerId:n,producerId:i}}),this.emit("newconsumer",Z),clearTimeout(R),k(Z)}}catch(q){this.logger.warn("error while creating consumer:",q),clearTimeout(R),I(E)}},D=this.unknownTracksMap.get(S);D?(this.logger.info(`track event already received [trackId: ${D.track.id}] [mid: ${D.transceiver.mid}]`),this.unknownTracksMap.delete(S),U(D.track,D.transceiver)):(this.logger.info(`Registering onTrack handler for key ${S} [producingPeerId: ${n}]`),this.consumerTrackEvents.set(S,U))})}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 np=Ra;Ca=new WeakMap;function C1(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=zp.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 R1{constructor(t,{handlerName:e,handlerFactory:r}={}){p(this,"handlerFactory");m(this,yr,void 0);m(this,nn,void 0);const i=t.getValue("logger");if(i.debug("constructor()"),g(this,yr,t),g(this,nn,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,nn).debug(`Device::constructor() | handler given: ${e}`);else if(e=C1(a(this,nn)),e)a(this,nn).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=sp.createFactory(a(this,yr));break;case"Safari12":this.handlerFactory=ip.createFactory(a(this,yr));break;case"Firefox60":this.handlerFactory=pl.createFactory(a(this,yr),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=pl.createFactory(a(this,yr),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=Cn();return new np(a(this,yr),{id:e,...t,handlerFactory:this.handlerFactory})}}yr=new WeakMap,nn=new WeakMap;const I1=2e3;class A1 extends gt.EventEmitter{constructor(e,r){super();m(this,Oa);m(this,hc);m(this,Jl);m(this,pc);m(this,Kl);m(this,zl);m(this,Yl);m(this,Ql);m(this,Xl);m(this,mc);m(this,ci);p(this,"context");m(this,Ia,void 0);m(this,Ze,void 0);m(this,et,void 0);m(this,dc,void 0);m(this,lc,void 0);m(this,an,void 0);m(this,Aa,void 0);m(this,uc,void 0);m(this,Ma,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});m(this,on,void 0);m(this,$s,"all");this.context=e,g(this,an,r),g(this,Ia,new R1(e)),g(this,Aa,new f1(r)),g(this,uc,fs),a(this,Oa,Du).mediaState={send:{state:Fr.NEW},recv:{state:Fr.NEW}},ao(this.context,"forceRelay")&&g(this,$s,"relay"),this.logger.info(`ICE Transport Policy initially set to ${a(this,$s)}`),N(this,hc,Dp).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return a(this,an)}get socketHandler(){return a(this,Aa)}get sendTransport(){return a(this,Ze)}get recvTransport(){return a(this,et)}get events(){return a(this,uc)}set sendTransportConnectedCallback(e){g(this,dc,e)}set recvTransportConnectedCallback(e){g(this,lc,e)}async setupTransports(e){await N(this,Jl,Bv).call(this,e);let r,i;e.send&&(r=N(this,pc,Np).call(this,a(this,Ze)).then(n=>{try{a(this,dc).call(this,n)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=N(this,pc,Np).call(this,a(this,et)).then(n=>{try{a(this,lc).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,Ze);this.logger.info("Closing send transport",{transport:{id:n,serverId:o,type:c}}),a(this,Ze).close(),a(this,Ze).removeAllListeners(),g(this,Ze,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,et);this.logger.info("Closing recv transport",{transport:{id:n,serverId:o,type:c}}),(r=a(this,et))==null||r.close(),(i=a(this,et))==null||i.removeAllListeners(),g(this,et,void 0)}N(this,hc,Dp).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}Ia=new WeakMap,Ze=new WeakMap,et=new WeakMap,dc=new WeakMap,lc=new WeakMap,an=new WeakMap,Aa=new WeakMap,uc=new WeakMap,Ma=new WeakMap,on=new WeakMap,$s=new WeakMap,Oa=new WeakSet,Du=function(){return this.context.getValue("connectionHandler")},hc=new WeakSet,Dp=function(){g(this,on,{send:void 0,recv:void 0})},Jl=new WeakSet,Bv=async function(e){var o,c,d,l,u,h,f,S;ao(this.context,"forceRelay")&&g(this,$s,"relay"),this.logger.info(`ICE Transport Policy set to ${a(this,$s)}`);const n=await Vt().getICEServers().catch(E=>(this.logger.warn(`failed to get iceservers from server: ${E.message}`),[]));e.send&&N(this,zl,Hv).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:(f=(h=(u=this.context.getValue("defaults").mediaConfiguration)==null?void 0:u.audio)==null?void 0:h.enableStereo)!=null?f:!1,enableDtx:!1},iceTransportPolicy:a(this,$s)}),e.recv&&N(this,Yl,qv).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(S=this.context.getValue("modules").e2ee)==null?void 0:S.enabled},iceTransportPolicy:a(this,$s)})},pc=new WeakSet,Np=async function(e){const{id:r,serverId:i,direction:n}=e;N(this,Ql,jv).call(this,e);try{return await IS(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 Br("Cannot reconnect closed transport");await N(this,Kl,Fv).call(this,e)}catch(l){if(l instanceof Br){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}},Kl=new WeakSet,Fv=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!a(this,an).isConnected)throw new Br("Socket is not connected");if(e.connectionState==="closed")throw new Br("Transport is closed");try{await e.connect(n=>N(this,Xl,Gv).call(this,i,n)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(n){throw a(this,Ma).transportFailureCount[i]+=1,n.message==="ice connection failed"?new Br(n.message):n}},zl=new WeakSet,Hv=function(e){var r,i;if(a(this,Ze)&&a(this,Ze).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=a(this,Ze))==null?void 0:r.id,serverId:(i=a(this,Ze))==null?void 0:i.serverId,type:"send"}});return}g(this,Ze,a(this,Ia).createTransport({...e,direction:"send"})),N(this,ci,Wa).call(this,{state:Fr.NEW,direction:"send",sfuSessionId:a(this,Ze).serverId}),this.context.getValue("callstats").configureSendTransport(a(this,Ze))},Yl=new WeakSet,qv=function(e){var r,i;if(a(this,et)&&a(this,et).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=a(this,et))==null?void 0:r.id,serverId:(i=a(this,et))==null?void 0:i.serverId,type:"recv"}});return}g(this,et,a(this,Ia).createTransport({...e,direction:"recv"})),N(this,ci,Wa).call(this,{state:Fr.NEW,direction:"recv",sfuSessionId:a(this,et).serverId}),this.context.getValue("callstats").configureRecvTransport(a(this,et))},Ql=new WeakSet,jv=function(e){const{direction:r,id:i}=e;e.on("serveridchange",n=>{N(this,ci,Wa).call(this,{state:e.connectionState,direction:r,sfuSessionId:n})}),e.on("connectionstatechange",async n=>{N(this,ci,Wa).call(this,{state:n,direction:r,sfuSessionId:e.serverId}),this.logger.info(`Transport connection state changed for ${r} transport`,{transport:{id:i,serverId:e.serverId,type:r,status:n}});const o=()=>{const c=a(this,on)[r];c!==void 0&&(clearTimeout(c),a(this,on)[r]=void 0)};switch(n){case"connected":o(),a(this,Ma).lastConnectionTime=performance.now();break;case"disconnected":a(this,on)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await N(this,mc,Lp).call(this,e.direction)},I1);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 N(this,mc,Lp).call(this,e.direction);break}}),e.on("icecandidate",async n=>{this.logger.debug("Sending iceCandidate:",{iceCandidate:n})})},Xl=new WeakSet,Gv=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?Xs.SUBSCRIBER:Xs.PUBLISHER},producers:[]};return a(this,Aa).connectTransport(c)}catch(n){throw this.logger.error(`Error in ${e} transport connection:`,{error:n}),n}},mc=new WeakSet,Lp=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),a(this,an).isConnected&&a(this,Ma).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),g(this,$s,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:a(this,Ze)}),this.context.getValue("peerSessionStore").emit(_.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:a(this,et)}),this.context.getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}const r=e==="send"?a(this,Ze):a(this,et);N(this,ci,Wa).call(this,{state:Fr.CONNECTED,direction:e,sfuSessionId:r.serverId})},ci=new WeakSet,Wa=function(e){const{state:r,direction:i,sfuSessionId:n}=e;a(this,Oa,Du).mediaState[i]={state:r,sfuSessionId:n},this.context.getValue("peerSessionStore").emit(_.TRANSPORT_STATE_UPDATE,{transport:i,...a(this,Oa,Du).mediaState[i]})};class M1{constructor(t,e,r,i,n){m(this,Zl,void 0);m(this,ds,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=n,g(this,Zl,t),g(this,ds,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,f={simulcast:{preferredRid:"f",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}};e.set(u,l),r.push({producingPeerId:l,producerId:u,producingTransportId:h,...f})});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,ds).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(f){}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,ds).info("Negotiating socket consumer",{transport:this.recvTransport}),a(this,ds).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:Xs.SUBSCRIBER}};return a(this,ds).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,EC.toBinary(r)),a(this,ds).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){a(this,ds).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,ds).info(`Closing consumers: ${JSON.stringify(n)}`);const o={description:{sdp:i.sdp,type:i.type,target:Xs.SUBSCRIBER},consumerIds:n,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=JR.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,ds).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:n})=>n)})}}Zl=new WeakMap,ds=new WeakMap;class ap{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return Oi(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,f;const c=ap.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:Xs.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(h=i.screenShare)!=null?h:!1,mimeType:`${e}/${(f=n[0])==null?void 0:f.name}`,producingTransportId:o},{answer:l,producerId:u}=await this.socketHandler.produce(d);return{answer:l,producerId:u}}}function O1(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 D1 extends A1{constructor(e,r){super(e,r);m(this,fc);m(this,tu);m(this,su);m(this,ru);m(this,iu);m(this,di,void 0);m(this,li,void 0);m(this,Da,void 0);m(this,gc,void 0);m(this,Bs,void 0);m(this,eu,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});m(this,Er,[]);m(this,Na,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{g(this,gc,new ap(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{a(this,Da).clear(),g(this,Bs,new M1(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return a(this,di)}get consumers(){return a(this,li)}get producerIdToConsumerIdMap(){return a(this,Da)}get logger(){return this.context.getValue("logger")}reset(){g(this,di,new Map),g(this,li,new Map),g(this,Da,new Map)}async createProducer(e,r){var i,n;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const o=await this.sendTransport.produce(e,N(this,tu,Wv).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(_.E2EE_ACTIVE_PRODUCER,o),N(this,su,Jv).call(this,o,r),o}catch(o){throw this.logger.error(`Failed to create ${((n=e==null?void 0:e.track)==null?void 0:n.kind)||"unknown"} producer`,{error:o}),a(this,eu).producerCreationFailureCount+=1,o}}async closeProducer(e,r){var n;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),(n=this.context.getValue("modules").e2ee)!=null&&n.enabled&&this.context.getValue("peerSessionStore").emit(_.E2EE_INACTIVE_PRODUCER,i)}catch(o){this.logger.error("Failed to close producer on server",{error:o,producer:i})}}closeAllProducers(){return Promise.all(Array.from(a(this,di).entries()).map(([,e])=>e.close()))}async closeAllProducersLocally(){var r;const e=(r=this.sendTransport)==null?void 0:r.handler;await Promise.all(Array.from(a(this,di).values()).map(async i=>{try{if(e){const n=e.midTransceiverMap.get(i.localId);n&&(await n.sender.replaceTrack(null),n.direction="inactive")}}catch(n){this.logger.warn("closeAllProducersLocally: failed to deactivate transceiver",{producer:{id:i.id,kind:i.kind,appData:i.appData},error:n})}await i.close(Eo)}))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){a(this,Na)||clearTimeout(a(this,Na)),g(this,Er,a(this,Er).concat(e)),await N(this,fc,Vp).call(this)}closeConsumer(e){return this.closeConsumers([e])}async closeConsumers(e){if(!a(this,Bs))return;const r=e.map(i=>this.consumers.get(i)).filter(i=>i!==void 0);r.length!==0&&await a(this,Bs).close(r)}closeAllConsumers(){return this.closeConsumers(Array.from(a(this,li).keys()))}async switchConsumersToLayer(e,r){a(this,Bs).switchConsumersToLayer(e,r)}}di=new WeakMap,li=new WeakMap,Da=new WeakMap,gc=new WeakMap,Bs=new WeakMap,eu=new WeakMap,Er=new WeakMap,Na=new WeakMap,fc=new WeakSet,Vp=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=a(this,Er).splice(0,a(this,Er).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,N(this,ru,Kv).bind(this),a(this,Bs).negotiate.bind(a(this,Bs)));if(o.forEach(N(this,iu,zv).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);g(this,Er,a(this,Er).concat(d)),g(this,Na,setTimeout(N(this,fc,Vp).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}=O1(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})}}},tu=new WeakSet,Wv=function(e){return a(this,gc).create(e)},su=new WeakSet,Jv=function(e,r){e.on("close",async(i,n)=>{const{offer:o,reason:c}=i;if(this.logger.info("producer::closing",{debuggingHint:c,producer:{...e,status:"closing"}}),c!==Eo){const d={producerId:e.id,description:{sdp:o.sdp,type:o.type,target:Xs.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,di).set(e.id,e)},ru=new WeakSet,Kv=async function(e){try{return await this.recvTransport.canConsume(),await a(this,Bs).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},iu=new WeakSet,zv=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,li).delete(e.id),this.context.getValue("peerSessionStore").emit(_.CONSUMER_CLOSED,{id:e.id})}),a(this,li).set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),this.context.getValue("peerSessionStore").emit(_.NEW_CONSUMER_CREATED,{id:e.id,appData:e.appData,peerId:e.peerId})};const du=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,nu);m(this,au);m(this,Sc,void 0);m(this,vc,void 0);m(this,Tc,void 0);m(this,La,void 0);m(this,Va,void 0);m(this,xa,void 0);m(this,yc,void 0);m(this,Ec,void 0);m(this,Ua,void 0);m(this,At,void 0);m(this,_s,void 0);m(this,ks,!1);m(this,cn,0);m(this,dn,0);m(this,br,[]);m(this,bc,void 0);g(this,La,t),g(this,At,t),g(this,Sc,e),g(this,vc,r),g(this,Tc,i),g(this,Va,n),g(this,xa,o),g(this,yc,c),g(this,Ec,d),g(this,Ua,l),g(this,bc,u),g(this,_s,t/2)}get voiceDetected(){return a(this,ks)}processAudioChunk(t){var o,c;const e=N(o=du,ou,Xv).call(o,t),r=N(c=du,cu,Zv).call(c,t);return N(this,nu,Yv).call(this,e),e/a(this,_s)>a(this,Ua)&&e>a(this,At)&&r>a(this,Sc)?(g(this,cn,a(this,cn)+1),g(this,dn,a(this,Tc)),a(this,cn)>=a(this,vc)&&g(this,ks,!0)):(g(this,cn,0),a(this,dn)>0?g(this,dn,a(this,dn)-1):a(this,ks)&&g(this,ks,!1),a(this,ks)||N(this,au,Qv).call(this,e)),{energy:e,isVoice:a(this,ks)}}reset(){g(this,ks,!1),g(this,cn,0),g(this,dn,0),g(this,At,a(this,La)),g(this,_s,a(this,La)/2),g(this,br,[])}getThresholdInfo(){return{currentEnergyThreshold:a(this,At),backgroundNoiseEnergy:a(this,_s),energyRatioThreshold:a(this,Ua)}}};let bo=du;Sc=new WeakMap,vc=new WeakMap,Tc=new WeakMap,La=new WeakMap,Va=new WeakMap,xa=new WeakMap,yc=new WeakMap,Ec=new WeakMap,Ua=new WeakMap,At=new WeakMap,_s=new WeakMap,ks=new WeakMap,cn=new WeakMap,dn=new WeakMap,br=new WeakMap,bc=new WeakMap,nu=new WeakSet,Yv=function(t){a(this,ks)?g(this,At,a(this,xa)*a(this,At)+(1-a(this,xa))*t):g(this,At,a(this,Va)*a(this,At)+(1-a(this,Va))*a(this,_s)),g(this,At,Math.max(a(this,yc),Math.min(a(this,Ec),a(this,At))))},au=new WeakSet,Qv=function(t){if(t<a(this,At)*1.2)if(a(this,br).push(t),a(this,br).length>a(this,bc)&&a(this,br).shift(),a(this,br).length>=10){const e=[...a(this,br)].sort((i,n)=>i-n),r=Math.floor(e.length/2);g(this,_s,e[r])}else g(this,_s,.95*a(this,_s)+.05*t)},ou=new WeakSet,Xv=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},cu=new WeakSet,Zv=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(bo,ou),m(bo,cu);class OS{constructor(t){p(this,"RNAudioSampleHandler");m(this,wc,void 0);g(this,wc,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,wc).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()}}wc=new WeakMap;class DS{constructor(t){p(this,"audioContext");p(this,"analyser");m(this,Pc,void 0);g(this,Pc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return a(this,Pc).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)}}Pc=new WeakMap;class NS{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 N1=60,L1=400,Cc=class{constructor(t,e){m(this,lu);m(this,uu);m(this,wr,void 0);m(this,Pr,void 0);m(this,_r,void 0);m(this,_c,void 0);m(this,$a,void 0);m(this,Ba,void 0);m(this,ui,void 0);m(this,ln,void 0);m(this,Fa,void 0);m(this,un,void 0);m(this,kr,void 0);m(this,Fs,void 0);this.reportRequest=e,g(this,un,t),g(this,Ba,new bo);const{isReactNative:r}=navigator;g(this,kr,r?new OS(a(this,un)):new DS(a(this,un))),g(this,Fs,r?NS:jh)}get logger(){return a(this,un).getValue("logger")}set producerId(t){g(this,_r,t)}set audioTrack(t){g(this,_c,t),a(this,kr)instanceof DS&&(a(this,kr).audioTrack=t)}start(){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${a(this,_r)}`),a(this,wr)&&a(this,Fs).clearInterval(a(this,wr)),g(this,wr,a(this,Fs).setInterval(async()=>{var i;if(!a(this,_c)||!a(this,_r))return;const{energy:t}=N(this,lu,eT).call(this),e=N(i=Cc,kc,xp).call(i,t);let r=.9;a(this,Fa)!==e&&a(this,Fa)?r=.9:e?r=.3:r=.5,g(this,$a,(a(this,$a)||0)*(1-r)+t*r)},N1)),a(this,Pr)&&a(this,Fs).clearInterval(a(this,Pr)),g(this,Pr,a(this,Fs).setInterval(N(this,uu,tT).bind(this),L1))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${a(this,_r)}`),a(this,wr)&&(a(this,Fs).clearInterval(a(this,wr)),g(this,wr,void 0)),a(this,Pr)&&(a(this,Fs).clearInterval(a(this,Pr)),g(this,Pr,void 0))}catch(t){}a(this,Ba).reset(),a(this,kr)instanceof OS&&a(this,kr).stop()}};let wo=Cc;wr=new WeakMap,Pr=new WeakMap,_r=new WeakMap,_c=new WeakMap,$a=new WeakMap,Ba=new WeakMap,ui=new WeakMap,ln=new WeakMap,Fa=new WeakMap,un=new WeakMap,kr=new WeakMap,Fs=new WeakMap,lu=new WeakSet,eT=function(){var o;const{samples:t}=a(this,kr),{energy:e,isVoice:r}=a(this,Ba).processAudioChunk(t),i=N(o=Cc,hu,sT).call(o,e);return i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,ui)||i<a(this,ui))&&g(this,ui,i),(!a(this,ln)||i>a(this,ln))&&g(this,ln,i),{energy:(i-a(this,ui))/(a(this,ln)-a(this,ui))*10||0,isVoice:r})},kc=new WeakSet,xp=function(t){return t<5},uu=new WeakSet,tT=function(t=a(this,$a)){var r;if(!a(this,_r)||!t)return;const e={producerId:a(this,_r),energy:Math.round(t),silent:N(r=Cc,kc,xp).call(r,t)};g(this,Fa,e.silent),this.reportRequest(e)},hu=new WeakSet,sT=function(t){const e=Math.log10(t);return Math.round(e)},m(wo,kc),m(wo,hu);var V1=Object.defineProperty,x1=Object.getOwnPropertyDescriptor,ce=(s,t,e,r)=>{for(var i=r>1?void 0:r?x1(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&&V1(t,e,i),i};class ae{constructor(t,e){m(this,Cr);m(this,mu);m(this,gu);m(this,fu);m(this,Mc);m(this,Su);m(this,vu);m(this,wt);m(this,gn);m(this,Tu);m(this,yu);m(this,Eu);p(this,"context");p(this,"authToken");p(this,"e2ee");m(this,Rc,void 0);m(this,Ic,void 0);m(this,ut,void 0);m(this,H,void 0);m(this,pu,void 0);m(this,bt,void 0);m(this,hn,void 0);m(this,pn,void 0);m(this,mn,void 0);m(this,Ac,void 0);m(this,Gt,null);m(this,Hs,void 0);m(this,ht,void 0);m(this,Mt,void 0);var i,n;this.context=t;const{socket:r}=e;this.mediaJoined=!1,g(this,ut,r),g(this,hn,!1),g(this,H,new D1(t,r)),g(this,bt,a(this,H).events),g(this,Hs,new Set),g(this,ht,new Map),g(this,pn,!1),g(this,mn,new ep(t.getValue("logger"))),g(this,Mt,new wo(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(),g(this,Ac,nh(async()=>{if(!a(this,Cr,kn).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(a(this,Ic),a(this,Rc),!0);o&&(this.context.getValue("peerSessionStore").emit(_.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(_.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,Cr,kn).mediaJoined}set mediaJoined(t){a(this,Cr,kn).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,ht).clear(),a(this,Hs).clear(),g(this,Gt,null),t&&a(this,mn).stop(),a(this,H).stopAllTransports(),a(this,H).reset(),t&&g(this,mn,new ep)}async joinRoom(t,e,r=!1,i={}){a(this,Cr,kn).mediaJoinAttempted=!0,g(this,hn,!0);try{return await a(this,mn).push(()=>N(this,mu,rT).call(this,t,e,r,i),"joinRoom")}catch(n){return this.logger.error("Error in room joining process",{error:n}),this.context.getValue("peerSessionStore").emit(_.ROOM_NODE_FAILED),{roomJoined:!1,error:n}}}async initializeConnection(t,e,r=!1,i={}){return a(this,Gt)?a(this,Gt):(g(this,Gt,(async()=>{try{await N(this,Mc,Up).call(this,t,e,r,i)}catch(n){throw g(this,Gt,null),n}})()),a(this,Gt))}getConsumers(){return a(this,H).consumers}getProducers(){return a(this,H).producers}async leaveRoom(){a(this,H).stopAllTransports(),g(this,pn,!1),a(this,Cr,kn).mediaJoinAttempted=!1;const t={closeRoom:!1};try{a(this,ut).sendMessage(a(this,bt).leaveRoom,WC.toBinary(t))||this.logger.warn("MediaNodeClient.leaveRoom: media leave was not sent")}catch(r){this.logger.error("MediaNodeClient.leaveRoom: media leave failed",{error:r})}this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct().catch(r=>{this.logger.error("leaveRoom::telemetry_destruct_failed",{error:r})})}async activatePeers(t){return this.createConsumers(t)}async createConsumers(t){return t.length===0?Promise.resolve():a(this,H).createConsumers(t)}async closeConsumers(t){if(!t.length)return;const e=t.reduce((r,i)=>{const n=a(this,H).producerIdToConsumerIdMap.get(i.producerId);return n?(r.push(n),r):(this.logger.warn(`consumer not found in close consumers: ${i.producerId}`),r)},[]);await this.closeConsumersById(e)}async closeConsumersById(t){t.length&&await a(this,H).closeConsumers(t)}async _shareWebcam(t){var u,h,f,S;const e=Ie.WEBCAM,r=N(this,wt,Yt).call(this,e);if(r){const E=await r;if(a(this,H).producers.has(E)){const k=a(this,H).producers.get(E);if(!k.closed)return await k.replaceTrack({track:t}),await this.resumeWebcam(e),t;await this.disableWebcam()}return this._shareWebcam(t)}const i=N(this,Eu,lT).call(this,t),n=ao(this.context,"disableSimulcast"),o=(h=(u=this.context)==null?void 0:u.getValue("overrides"))==null?void 0:h.simulcastConfig;n||o&&o.disable||!((S=(f=this.context)==null?void 0:f.getValue("theme"))!=null&&S.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),i.encodings=yD(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,ht).delete(e)},l=a(this,H).createProducer(i,d);return N(this,gn,ud).call(this,e,l.then(E=>E.id)),l.then(E=>E.track)}async shareWebcam(t){return t===void 0?null:(this.logger.debug("Calling _shareWebcam with VP8 codec"),this._shareWebcam(t))}async shareScreen(t){const{video:e,audio:r}=t;if(e===void 0)return;const i={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ye.isElectron()},stopTracks:!1},n=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,ht).delete(Ie.SCREENSHARE_VIDEO),a(this,ht).delete(Ie.SCREENSHARE_AUDIO)},o=a(this,H).createProducer(i,n);N(this,gn,ud).call(this,Ie.SCREENSHARE_VIDEO,o.then(d=>d.id));let c;if(r){const d={track:r,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ye.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},l=()=>{};c=a(this,H).createProducer(d,l),N(this,gn,ud).call(this,Ie.SCREENSHARE_AUDIO,c.then(u=>u.id))}await Promise.all([o,c||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()}async shareMic(t){try{if(t===void 0)throw new Rt("track undefined");const e=N(this,wt,Yt).call(this,Ie.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,Mt)&&(a(this,Mt).audioTrack=t,a(this,Mt).producerId=o,a(this,Mt).start());return}await a(this,H).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=N(this,yu,dT).call(this,t),i=()=>{a(this,ht).delete(Ie.MIC)},n=a(this,H).createProducer(r,i);N(this,gn,ud).call(this,Ie.MIC,n.then(o=>o.id)),await n.then(o=>{a(this,Mt)&&(a(this,Mt).audioTrack=o.track,a(this,Mt).producerId=o.id,a(this,Mt).start())})}catch(e){throw new P(e)}}async pauseMic(){var i;const t=await N(this,wt,Yt).call(this,Ie.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,Mt))==null||i.stop();const r={producerId:e.id,pause:!0};a(this,ut).sendMessage(a(this,bt).toggleProducer,Jd.toBinary(r))}async pauseWebcam(){const t=await N(this,wt,Yt).call(this,Ie.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,ut).sendMessage(a(this,bt).toggleProducer,Jd.toBinary(r))}async resumeMic(){const t=await N(this,wt,Yt).call(this,Ie.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(_.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,ut).sendMessage(a(this,bt).toggleProducer,Jd.toBinary(r))}async resumeWebcam(t=Ie.WEBCAM){const e=await N(this,wt,Yt).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(_.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};a(this,ut).sendMessage(a(this,bt).toggleProducer,Jd.toBinary(i))}async disableWebcam(){const t=Ie.WEBCAM,e=await N(this,wt,Yt).call(this,t);N(this,Tu,cT).call(this,t),e&&await a(this,H).closeProducer(e)}async disableMic(){var e;const t=await N(this,wt,Yt).call(this,Ie.MIC);t&&await a(this,H).closeProducer(t),(e=a(this,Mt))==null||e.stop(),a(this,ht).delete(Ie.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await N(this,wt,Yt).call(this,Ie.SCREENSHARE_VIDEO),e=await N(this,wt,Yt).call(this,Ie.SCREENSHARE_AUDIO);t&&await a(this,H).closeProducer(t),e&&await a(this,H).closeProducer(e),a(this,Hs).clear(),a(this,ht).delete(Ie.SCREENSHARE_VIDEO),a(this,ht).delete(Ie.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await N(this,wt,Yt).call(this,Ie.WEBCAM);await a(this,H).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await N(this,wt,Yt).call(this,Ie.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,ut).sendMessagePromise(a(this,bt).globalPinPeer,aR.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,Hs).add(t.consumerPeerId),a(this,Hs).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));a(this,H).switchConsumersToLayer(r,e)}async handleSocketEvents(){a(this,ut).on(a(this,bt).peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:r}=dI.fromBinary(t);if(e===this.peerId)return;r!=null&&r.mimeType||(r.mimeType=r.kind===Zs.AUDIO?"audio/opus":"video/VP8"),this.logger.info(`producer created broadcast: ${e}, producer state: ${r}`),this.context.getValue("peerSessionStore").emit(_.NEW_PRODUCER,{peerId:e,producer:{...r,kind:r.kind===Zs.AUDIO?"audio":"video",producingPeerId:e}})}catch(e){this.logger.error("error in peer-producer-create-broadcast",{error:e})}}),a(this,ut).on(a(this,bt).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:r,producerState:{kind:i,pause:n,producerId:o,screenShare:c}}=yh.fromBinary(t);if(c)return;const d=i===Zs.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${o}, kind:${d}, paused:${n} payload: ${yh.toJsonString(yh.fromBinary(t))}`),e===this.peerId&&r!==this.peerId&&n&&this.context.getValue("peerSessionStore").emit(d==="audio"?_.MUTE_SELF:_.MUTE_SELF_VIDEO),e===this.peerId)return;this.context.getValue("peerSessionStore").emit(_.PRODUCER_TOGGLE,{peerId:e,producerId:o,paused:n,kind:d}),Array.from(this.getConsumers().values()).filter(u=>u.producerId===o).forEach(u=>{u.kind==="video"&&n||u.paused!==n&&(this.logger.debug(`consumer state mismatched for ${u.id}. updating consumer pause state ${u.paused} to ${n}`),n?(u.pause(),this.context.getValue("peerSessionStore").emit(_.CONSUMER_PAUSED,{id:u.id})):(u.resume(),this.context.getValue("peerSessionStore").emit(_.CONSUMER_RESUMED,{id:u.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),a(this,ut).on(a(this,bt).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=Eh.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),a(this,Hs).delete(e),a(this,H).consumers.forEach(r=>{r.peerId===e&&r.close()}),this.context.getValue("peerSessionStore").emit(_.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast",{error:e})}}),a(this,ut).on(a(this,bt).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=hI.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(_.PRODUCER_CLOSED,{peerId:e,producerId:r});const i=a(this,H).producerIdToConsumerIdMap.get(r);if(!i){this.logger.warn(`no consumer found for producer:${r}`);return}this.logger.info(`closing consumer ${i}, producer id: ${r}`),a(this,H).closeConsumer(i).then(()=>{this.logger.info(`closed consumer: ${i}`),a(this,H).producerIdToConsumerIdMap.delete(r),this.context.getValue("peerSessionStore").emit(_.CONSUMER_CLOSED,{id:i})}).catch(n=>{this.logger.error("error closing consumer",{error:n})})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),a(this,ut).on(a(this,bt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,hn)&&!a(this,pn)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(_.ROOM_NODE_DISCONNECTED),a(this,Ac).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(_.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(_.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:e.score,scoreStats:e})})})}}Rc=new WeakMap,Ic=new WeakMap,ut=new WeakMap,H=new WeakMap,pu=new WeakMap,bt=new WeakMap,hn=new WeakMap,pn=new WeakMap,mn=new WeakMap,Ac=new WeakMap,Gt=new WeakMap,Hs=new WeakMap,ht=new WeakMap,Mt=new WeakMap,Cr=new WeakSet,kn=function(){return this.context.getValue("connectionHandler")},mu=new WeakSet,rT=async function(t,e,r,i){var o;g(this,Ic,t);let n=!1;if(r){const{recv:c,send:d}=(o=a(this,Cr,kn).mediaState)!=null?o:{};(d==null?void 0:d.state)===Fr.CONNECTED&&(c==null?void 0:c.state)===Fr.CONNECTED?(this.logger.info("MediaNodeClient.joinRoom: transports healthy — partial reset (producers only)"),await a(this,H).closeAllProducersLocally(),a(this,ht).clear(),a(this,Hs).clear(),g(this,Gt,null),n=!0):(this.logger.info("MediaNodeClient.joinRoom: transports unhealthy — full reset"),this.reset({resetTransportQueue:!1}))}try{a(this,Gt)?await a(this,Gt):await N(this,Mc,Up).call(this,t,e,r,i,n),N(this,fu,nT).call(this,e);const{joined:c,error:d}=await N(this,gu,iT).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{g(this,Gt,null)}},gu=new WeakSet,iT=async function(){try{this.mediaJoined=!0;const{roomState:t}=await a(this,H).socketHandler.notifySelfJoinComplete();return g(this,Rc,t.roomUuid),g(this,pn,!0),g(this,hn,!1),{joined:!0}}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,{joined:!1,error:t}}},fu=new WeakSet,nT=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const r={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:{...ye.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)},Mc=new WeakSet,Up=async function(t,e,r,i,n=!1){try{const o=N(this,Su,aT).call(this);await N(this,vu,oT).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}},Su=new WeakSet,aT=function(){const t=g1("video/VP8");return g(this,pu,t),t},vu=new WeakSet,oT=async function(t,e,r,i){await IS(async(n,o)=>{if(!a(this,ut).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})},wt=new WeakSet,Yt=function(t){return a(this,ht).get(t)},gn=new WeakSet,ud=function(t,e){return a(this,ht).set(t,e)},Tu=new WeakSet,cT=function(t){return a(this,ht).delete(t)},yu=new WeakSet,dT=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},Eu=new WeakSet,lT=function(t){return{track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},ce([y.trace("MediaNodeClient.reset")],ae.prototype,"reset",1),ce([y.trace("MediaNodeClient.joinRoom")],ae.prototype,"joinRoom",1),ce([y.trace("MediaNodeClient.leaveRoom")],ae.prototype,"leaveRoom",1),ce([y.trace("MediaNodeClient.activatePeers")],ae.prototype,"activatePeers",1),ce([y.trace("MediaNodeClient.createConsumers")],ae.prototype,"createConsumers",1),ce([y.trace("MediaNodeClient.closeConsumers")],ae.prototype,"closeConsumers",1),ce([y.trace("MediaNodeClient.closeConsumersById")],ae.prototype,"closeConsumersById",1),ce([y.trace("MediaNodeClient._shareWebcam")],ae.prototype,"_shareWebcam",1),ce([y.trace("MediaNodeClient.shareWebcam")],ae.prototype,"shareWebcam",1),ce([y.trace("MediaNodeClient.shareScreen")],ae.prototype,"shareScreen",1),ce([y.trace("MediaNodeClient.shareMic")],ae.prototype,"shareMic",1),ce([y.trace("MediaNodeClient.pauseMic")],ae.prototype,"pauseMic",1),ce([y.trace("MediaNodeClient.pauseWebcam")],ae.prototype,"pauseWebcam",1),ce([y.trace("MediaNodeClient.resumeMic")],ae.prototype,"resumeMic",1),ce([y.trace("MediaNodeClient.resumeWebcam")],ae.prototype,"resumeWebcam",1),ce([y.trace("MediaNodeClient.disableWebcam")],ae.prototype,"disableWebcam",1),ce([y.trace("MediaNodeClient.disableMic")],ae.prototype,"disableMic",1),ce([y.trace("MediaNodeClient.disableScreenShare")],ae.prototype,"disableScreenShare",1),ce([y.trace("MediaNodeClient.muteSelf")],ae.prototype,"muteSelf",1),ce([y.trace("MediaNodeClient.resetVideoProducers")],ae.prototype,"resetVideoProducers",1),ce([y.trace("MediaNodeClient.changeDisplayName")],ae.prototype,"changeDisplayName",1),ce([y.trace("MediaNodeClient.kickPeer")],ae.prototype,"kick",1),ce([y.trace("MediaNodeClient.kickAllPeers")],ae.prototype,"kickAll",1),ce([y.trace("MediaNodeClient.muteAll")],ae.prototype,"muteAll",1),ce([y.trace("MediaNodeClient.muteAllVideo")],ae.prototype,"muteAllVideo",1),ce([y.trace("MediaNodeClient.disableAudio")],ae.prototype,"disableAudio",1),ce([y.trace("MediaNodeClient.disableVideo")],ae.prototype,"disableVideo",1),ce([y.trace("MediaNodeClient.pinPeer")],ae.prototype,"pinPeer",1),ce([y.trace("MediaNodeClient.validateScreenShare")],ae.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 ae(s,t);return s.setValue("roomNodeClient",r),r}function U1(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 $1=Object.defineProperty,B1=Object.getOwnPropertyDescriptor,Di=(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&&$1(t,e,i),i};const VS=(kv=class{constructor(s,t,e,r){m(this,Ot);p(this,"self");p(this,"authToken");m(this,Oc,void 0);p(this,"viewType");m(this,ls,void 0);m(this,te,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,g(this,te,s),this.viewType=r,this.authToken=n,g(this,Oc,i),g(this,ls,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=Vt(),o=!!s.getValue("cachedUserDetails"),c=await We.__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:ye.getDeviceInfo().engineName,env:s.getValue("env")==="prod"?"prod":"devel",iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:{},logger:d,apiHostnames:uk(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 VS(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,Ot,us).shareMic(s),this.self.audioEnabled||a(this,Ot,us).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,Ot,us).shareWebcam(t),this.self.videoEnabled||a(this,Ot,us).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,Ot,us))==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){a(this,te).getValue("callstats").callEnded(),s?(this.logger.info("Resetting Self post reconnect. Peer has earlier tried joining the meeting. State cleanup will be done during room rejoin."),await this.joinRoom(s)):(this.logger.info("Resetting Self post reconnect. User never joined the room so doing full reset."),a(this,Ot,us).reset({resetTransportQueue:!0}))}setupEvents(){a(this,te).getValue("peerSessionStore").on(_.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),a(this,te).getValue("peerSessionStore").on(_.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,te).getValue("peerSessionStore").on(_.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,te).getValue("peerSessionStore").on(_.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(_.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(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(_.SOCKET_SERVICE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,te).getValue("peerSessionStore").on(_.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,ls).on($.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,ls).on(Zd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,te).getValue("peerSessionStore").emit(_.UPDATE_PERMISSIONS,t.patch)})}),a(this,ls).on($.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,ls).on($.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,ls).on($.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,te).getValue("peerSessionStore").onAsync(_.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,te).getValue("peerSessionStore").on(_.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(_.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,te).getValue("callstats").audioOff())}),a(this,te).getValue("peerSessionStore").on(_.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,te).getValue("callstats").videoOff())}),a(this,te).getValue("peerSessionStore").onAsync(_.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,te).getValue("peerSessionStore").on(_.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{this.logger.info("Joining socket room.");const{peer:t}=await a(this,ls).joinRoom(this.self);this.logger.info("Joined socket room."),a(this,ls).socket.flush();const e=$h(t.stageType);if(a(this,te).setValue("stageStatus",e,!1),t.waitlisted){this.logger.info("Peer was waitlisted. Skipped joining media room."),this.waitlistedHandler();return}}catch(t){throw this.logger.error("SelfController.joinRoom: socket join failed",{error:t}),new P("Check the network and try again.","0002")}try{this.logger.info("Joining media room."),await this.joinMediaRoom(s),this.logger.info("Joined media room."),a(this,te).notify("stageStatus")}catch(t){throw this.logger.error("SelfController.joinRoom: media room join failed",{error:t}),t instanceof Br&&t.message==="ice connection failed"?new P("A firewall or network restriction may be blocking the connection.","0014"):new P("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,ls).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===Ys.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}LS(a(this,te),{socket:a(this,Oc),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u,error:h}=(o=await((n=a(this,Ot,us))==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===Ys.Webinar)&&a(this,Ot,us)&&(a(this,Ot,us).mediaJoined&&s!=="disconnected"&&await a(this,Ot,us).leaveRoom(),!(s==="stageLeft"&&t===Ys.Livestream)&&(a(this,Ot,us).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()}},Oc=new WeakMap,ls=new WeakMap,te=new WeakMap,Ot=new WeakSet,us=function(){return a(this,te).getValue("roomNodeClient")},kv);let Hr=VS;Di([y.trace("SelfController.resetSelf")],Hr.prototype,"resetSelf",1),Di([y.trace("SelfController.setupEvents")],Hr.prototype,"setupEvents",1),Di([y.trace("SelfController.joinRoom")],Hr.prototype,"joinRoom",1),Di([y.trace("SelfController.leaveRoom")],Hr.prototype,"leaveRoom",1),Di([y.trace("SelfController.joinMediaRoom")],Hr.prototype,"joinMediaRoom",1),Di([y.trace("SelfController.leaveMediaRoom")],Hr.prototype,"leaveMediaRoom",1),Di([y.trace("SelfController.init")],Hr,"init",1);class F1{constructor(t){m(this,Dc,void 0);g(this,Dc,t)}on(t,e){let r;t===$.roomPeerCount?r=Af.fromBinary.bind(Af):r=jf.fromBinary.bind(jf),a(this,Dc).on(t,({payload:i})=>{if(t===$.roomPeerCount&&!i)return;const n=r(i);e(n)})}}Dc=new WeakMap;class H1{constructor(t,e){m(this,Nc,void 0);m(this,Lc,void 0);g(this,Nc,e),g(this,Lc,t)}get logger(){return a(this,Lc).getValue("logger")}on(t,e){let r,i;switch(t){case $.transcript:{r=bh.fromBinary.bind(bh),i=bh.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Nc).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)})}}Nc=new WeakMap,Lc=new WeakMap;var q1=Object.defineProperty,j1=Object.getOwnPropertyDescriptor,op=(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};class ml{constructor(t,e){m(this,Rr,void 0);m(this,Ha,void 0);g(this,Rr,e),g(this,Ha,t)}get logger(){return a(this,Ha).getValue("logger")}get telemetry(){return a(this,Ha).getValue("telemetry")}getPolls(){return a(this,Rr).sendMessagePromise(sr.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Rr).sendMessage(sr.createPoll,FM.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Rr).sendMessage(sr.votePoll,qM.toBinary(r))}on(t,e){let r,i;switch(t){case sr.updatePoll:case sr.createPoll:case sr.votePoll:{r=Nh.fromBinary.bind(Nh),i=Nh.create();break}}a(this,Rr).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,Rr).removeListeners(t)}}Rr=new WeakMap,Ha=new WeakMap,op([y.trace("PollSocketHandler.getPolls")],ml.prototype,"getPolls",1),op([y.trace("PollSocketHandler.createPoll")],ml.prototype,"createPoll",1),op([y.trace("PollSocketHandler.votePoll")],ml.prototype,"votePoll",1);var G1=Object.defineProperty,W1=Object.getOwnPropertyDescriptor,J1=(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};class xS{constructor(t,e){p(this,"socket");m(this,Wt,void 0);g(this,Wt,t),this.socket=e,this.handleSocketEvents(),a(this,Wt).setValue("roomSocketHandler",this)}get telemetry(){return a(this,Wt).getValue("telemetry")}get logger(){return a(this,Wt).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($.joinRoom,FI.toBinary(e));try{const{peer:n}=Nn.fromBinary((await r).payload);a(this,Wt).getValue("connectionHandler").socketJoined=!0,a(this,Wt).getValue("peerSessionStore").emit(_.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,Wt).getValue("peerSessionStore").emit(_.ROOM_STATE,d),a(this,Wt).getValue("peerSessionStore").emit(_.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),n}}async getAllAddedParticipants(){try{return _0.fromBinary((await this.socket.sendMessagePromise($.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($.getRoomPeersInfo,MI.toBinary(n));i=_h.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($.getRoomPeersInfo);t=_h.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($.getRoomPeersInfo);t=_h.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($.getPeerInfo,Df.toBinary({peerId:t}));e=Nn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=Of.create();try{const e=await this.socket.sendMessagePromise($.getRoomInfo);t=Of.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=$f.create();try{const e=await this.socket.sendMessagePromise($.getRoomStageState);t=$f.fromBinary(e.payload)}catch(e){this.logger.error("getRoomStageState::binary_decode_error",{error:e})}return t}async broadcastMessage(t,e){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise($.broadcastMessage,lo.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($.broadcastToEntity,lo.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($.broadcastToEntity,lo.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($.leaveRoom,qI.toBinary(e))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage($.kick,xf.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage($.kickAll,wf.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage($.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage($.acceptWaitingRoomRequests,M0.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage($.denyWaitingRoomRequests,D0.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Zd.updateUserPreset,cA.toBinary(r))}handleSocketEvents(){this.socket.on($.broadcastMessage,({payload:t})=>{try{const e=lo.fromBinary(t);a(this,Wt).getValue("peerSessionStore").emit(_.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($.broadcastToEntity,({payload:t})=>{try{const e=lo.fromBinary(t);a(this,Wt).getValue("peerSessionStore").emit(_.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 $.joinRoom:case $.leaveRoom:case $.kick:case $.kickAll:{r=Nn.fromBinary.bind(Nn),i=Nn.create();break}case $.getWaitingRoomRequests:{r=(n,o)=>n?Uf.fromBinary(n,o):{requests:[]},i=Uf.create();break}case $.recordingPaused:case $.recordingStarted:case $.recordingStopped:{r=Kf.fromBinary.bind(Kf);break}case Zd.updateUserPreset:{r=Ff.fromBinary.bind(Ff);break}case fs.peerJoinedBroadcast:case Lr.peerJoinedBroadcast:{r=kf.fromBinary.bind(kf);break}case fs.selfJoinComplete:case Lr.selfJoinComplete:{r=Th.fromBinary.bind(Th);break}case fs.globalPeerPinBroadcast:case Lr.globalPeerPinBroadcast:{r=Rf.fromBinary.bind(Rf);break}case fs.selectedPeer:case Lr.selectedPeer:{r=vh.fromBinary.bind(vh);break}case fs.selectedPeerDiff:case Lr.selectedPeerDiff:{r=_f.fromBinary.bind(_f);break}case fs.leaveRoom:case Lr.leaveRoom:{r=Eh.fromBinary.bind(Eh);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(Zd.getUserPresets,tA.toBinary(e)),i=nA.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}}}Wt=new WeakMap,J1([y.trace("RoomSocketHandler.joinRoom")],xS.prototype,"joinRoom",1);class K1{constructor(t){m(this,Dt,void 0);g(this,Dt,t)}async getStageRequests(){const{payload:t}=await a(this,Dt).sendMessagePromise($.getStageRequests);return t?Dh.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,Dt).sendMessage($.requestStageAccess)}cancelRequestAccess(){a(this,Dt).sendMessage($.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,Dt).sendMessage($.grantStageAccess,MM.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,Dt).sendMessage($.denyStageAccess,DM.toBinary(e))}joinStage(){return a(this,Dt).sendMessagePromise($.joinStage,void 0,void 0,$.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,Dt).sendMessagePromise($.leaveStage,Wf.toBinary(e),void 0,$.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,Dt).sendMessagePromise($.leaveStage,Wf.toBinary(e))}on(t,e){let r;switch(t){case $.grantStageAccess:case $.denyStageAccess:{r=void 0;break}case $.getStagePeers:{r=Gf.fromBinary.bind(Gf);break}case $.getStageRequests:case $.requestStageAccess:case $.cancelStageRequest:{r=Dh.fromBinary.bind(Dh);break}case $.peerStageStatusUpdate:{r=If.fromBinary.bind(If);break}}a(this,Dt).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,Dt).sendMessagePromise($.getPeerInfo,Df.toBinary({peerId:t}));return Nn.fromBinary(e.payload)}}Dt=new WeakMap;class z1{constructor(t,e){m(this,hi,void 0);m(this,qa,void 0);g(this,hi,e),g(this,qa,t)}get logger(){return a(this,qa).getValue("logger")}get peerId(){return a(this,qa).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,hi).sendMessage(tr.storeInsertKeys,uM.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,hi).sendMessage(tr.storeGetKeys,pM.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,hi).sendMessage(tr.storeDeleteKeys,gM.toBinary(n),i)}on(t,e){const r=qf.fromBinary.bind(qf);a(this,hi).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}hi=new WeakMap,qa=new WeakMap;var Y1=Object.defineProperty,Q1=(s,t,e)=>t in s?Y1(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,X1=(s,t,e)=>(Q1(s,typeof t!="symbol"?t+"":t,e),e),cp=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},M=(s,t,e)=>(cp(s,t,"read from private field"),e?e.call(s):t.get(s)),ue=(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)},ne=(s,t,e,r)=>(cp(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),oe=(s,t,e)=>(cp(s,t,"access private method"),e),gl={},Z1={get exports(){return gl},set exports(s){gl=s}},Bn=typeof Reflect=="object"?Reflect:null,US=Bn&&typeof Bn.apply=="function"?Bn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},fl;Bn&&typeof Bn.ownKeys=="function"?fl=Bn.ownKeys:Object.getOwnPropertySymbols?fl=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:fl=function(s){return Object.getOwnPropertyNames(s)};function eN(s){console&&console.warn&&console.warn(s)}var $S=Number.isNaN||function(s){return s!==s};function he(){he.init.call(this)}Z1.exports=he,gl.once=iN,he.EventEmitter=he,he.prototype._events=void 0,he.prototype._eventsCount=0,he.prototype._maxListeners=void 0;var BS=10;function Sl(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(he,"defaultMaxListeners",{enumerable:!0,get:function(){return BS},set:function(s){if(typeof s!="number"||s<0||$S(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");BS=s}}),he.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},he.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||$S(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?he.defaultMaxListeners:s._maxListeners}he.prototype.getMaxListeners=function(){return FS(this)},he.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=WS(c,d),e=0;e<d;++e)US(l[e],this,t);return!0};function HS(s,t,e,r){var i,n,o;if(Sl(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,eN(c)}return s}he.prototype.addListener=function(s,t){return HS(this,s,t,!1)},he.prototype.on=he.prototype.addListener,he.prototype.prependListener=function(s,t){return HS(this,s,t,!0)};function tN(){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 qS(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=tN.bind(r);return i.listener=e,r.wrapFn=i,i}he.prototype.once=function(s,t){return Sl(t),this.on(s,qS(this,s,t)),this},he.prototype.prependOnceListener=function(s,t){return Sl(t),this.prependListener(s,qS(this,s,t)),this},he.prototype.removeListener=function(s,t){var e,r,i,n,o;if(Sl(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():sN(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this},he.prototype.off=he.prototype.removeListener,he.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 jS(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?rN(i):WS(i,i.length)}he.prototype.listeners=function(s){return jS(this,s,!0)},he.prototype.rawListeners=function(s){return jS(this,s,!1)},he.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):GS.call(s,t)},he.prototype.listenerCount=GS;function GS(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}he.prototype.eventNames=function(){return this._eventsCount>0?fl(this._events):[]};function WS(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function sN(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function rN(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function iN(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))}JS(s,t,n,{once:!0}),t!=="error"&&nN(s,i,{once:!0})})}function nN(s,t,e){typeof s.on=="function"&&JS(s,"error",t,e)}function JS(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 aN extends v{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 KS=new aN;class zS{static encode(t){return KS.toBinary(t)}static decode(t){return KS.fromBinary(new Uint8Array(t))}}function oN(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var qr;class cN{constructor(t={}){X1(this,"opts"),ue(this,qr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ne(this,qr,0)}async wait(){ne(this,qr,M(this,qr)+1);const t=oN(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**M(this,qr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return M(this,qr)}reset(){ne(this,qr,0)}}qr=new WeakMap;const jr={debug:0,info:1,warn:2,error:3};var Ni,Li;class dN{constructor(t){ue(this,Ni,void 0),ue(this,Li,void 0),ne(this,Ni,console),ne(this,Li,t)}debug(...t){jr[M(this,Li)]>jr.debug||M(this,Ni).debug("[Sockrates]:",...t)}info(...t){jr[M(this,Li)]>jr.info||M(this,Ni).info("[Sockrates]:",...t)}warn(...t){jr[M(this,Li)]>jr.warn||M(this,Ni).warn("[Sockrates]:",...t)}error(...t){jr[M(this,Li)]>jr.error||M(this,Ni).error("[Sockrates]:",...t)}}Ni=new WeakMap,Li=new WeakMap;var YS=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(YS||{});const QS="2",XS="3";var Me,Fn,pe,Re,Gr,Je,cr,Wr,vs,Hn,qn,dr,dp,ZS,Po,vl,lp,ev,Tl,up,yl,hp,pp,tv,_o,El,jn,ko,bl,mp,Gn,Co,gp,sv,Ro,wl,Io,Pl;class lN{constructor(t,e){var E,k,I,R,U,D,x,B,q,Z,se,at;ue(this,dp),ue(this,Po),ue(this,lp),ue(this,Tl),ue(this,yl),ue(this,pp),ue(this,_o),ue(this,jn),ue(this,bl),ue(this,Gn),ue(this,gp),ue(this,Ro),ue(this,Io),ue(this,Me,void 0),ue(this,Fn,void 0),ue(this,pe,void 0),ue(this,Re,void 0),ue(this,Gr,void 0),ue(this,Je,void 0),ue(this,cr,void 0),ue(this,Wr,void 0),ue(this,vs,void 0),ue(this,Hn,void 0),ue(this,qn,void 0),ue(this,dr,void 0);var r,i,n,o,c,d,l,u,h,f,S;ne(this,Fn,t),ne(this,Gr,[]),ne(this,Je,new gl),ne(this,cr,!0),ne(this,vs,!1),ne(this,pe,e!=null?e:{}),(E=(r=M(this,pe)).autoReconnect)!=null||(r.autoReconnect=!0),(k=(i=M(this,pe)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(I=(n=M(this,pe)).pingTimeout)!=null||(n.pingTimeout=3e4),(R=(o=M(this,pe)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(U=(c=M(this,pe)).debug)!=null||(c.debug=!0),(D=(d=M(this,pe)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(x=(l=M(this,pe)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(B=(u=M(this,pe)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(q=(h=M(this,pe)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),(Z=(f=M(this,pe)).clientInitiatedPings)!=null||(f.clientInitiatedPings=!1),(se=(S=M(this,pe)).clientInitiatedPingInterval)!=null||(S.clientInitiatedPingInterval=3e4),ne(this,Wr,{code:void 0,reason:void 0}),ne(this,Re,(at=M(this,pe).logger)!=null?at:new dN(M(this,pe).debug?"debug":"info")),ne(this,dr,new cN)}get readyState(){var t;return(t=M(this,Me))==null?void 0:t.readyState}get url(){return M(this,Fn)}updateURL(t){ne(this,Fn,t),oe(this,pp,tv).call(this)}get config(){return M(this,pe)}get sendQueue(){return M(this,Gr)}flush(){if(!M(this,pe).queueOnDisconnect)return!1;const t=[];return M(this,Gr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ne(this,Gr,t),M(this,Gr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){M(this,Re).debug("Websocket was already connecting or connected.");return}if(M(this,cr)!==!1)return new Promise((e,r)=>{oe(this,Gn,Co).call(this),oe(this,Io,Pl).call(this);try{ne(this,Me,new WebSocket(oe(this,dp,ZS).call(this,M(this,Fn)))),M(this,Me).binaryType="arraybuffer",M(this,Re).debug("Connecting");const i=setTimeout(()=>{M(this,Re).debug("Connection timeout. Closing socket"),ne(this,cr,!0),oe(this,Io,Pl).call(this),M(this,Me).close(3001,"Connection Timeout"),M(this,pe).autoReconnect&&!M(this,vs)&&(M(this,Je).emit("reconnecting"),oe(this,_o,El).call(this)),r(new Error("Connection timed out!"))},M(this,pe).connectionTimeout);M(this,Me).onopen=()=>{M(this,Re).debug(`Ready State: ${YS[M(this,Me).readyState]}`),i&&clearTimeout(i),oe(this,bl,mp).call(this),oe(this,gp,sv).call(this),ne(this,Wr,{code:void 0,reason:void 0}),M(this,Je).emit("connected"),M(this,pe).flushOnReconnect&&this.flush(),e()},M(this,Me).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),M(this,Re).debug("Socket closed. Close event:",{event:n}),M(this,Re).debug(`Connection closed code: ${o}`),M(this,Re).debug(`Connection closed reason: ${c}`),M(this,vs)||oe(this,yl,hp).call(this,o,c)}catch(o){oe(this,Po,vl).call(this,o)}},M(this,Me).onerror=n=>{oe(this,Po,vl).call(this,n)},M(this,Me).onmessage=n=>oe(this,lp,ev).call(this,n)}catch(i){oe(this,Po,vl).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(M(this,pe).queueOnDisconnect&&(!M(this,Me)||M(this,Me).readyState!==1))return M(this,Re).debug("Queuing message since socket is not connected!",n),M(this,Gr).push(n),!1;const o=zS.encode(n);return oe(this,jn,ko).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return oe(this,jn,ko).call(this,t)}receive(t,e){return M(this,Je).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,Je).on(t,e);return}this.receive(t,e)}removeAllListeners(){M(this,Je).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){M(this,Je).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){M(this,Je).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ne(this,cr,!1),oe(this,Gn,Co).call(this),oe(this,Ro,wl).call(this),this.removeAllListeners(),ne(this,Wr,{code:1e3,reason:"Sockrates disconnect method called"}),M(this,Me).close(1e3,"Sockrates disconnect method called.")}}Me=new WeakMap,Fn=new WeakMap,pe=new WeakMap,Re=new WeakMap,Gr=new WeakMap,Je=new WeakMap,cr=new WeakMap,Wr=new WeakMap,vs=new WeakMap,Hn=new WeakMap,qn=new WeakMap,dr=new WeakMap,dp=new WeakSet,ZS=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)://.")},Po=new WeakSet,vl=function(s,t){M(this,Re).error("Error:",{error:s}),M(this,Je).emit("errored",{error:s}),t==null||t(s)},lp=new WeakSet,ev=function(s){if(oe(this,bl,mp).call(this),s.data===QS){M(this,Re).debug("Received ping from server"),oe(this,jn,ko).call(this,XS);return}if(s.data===XS){M(this,Re).debug("Received pong from server");return}const t=zS.decode(s.data),{id:e,payload:r}=t;M(this,Re).debug("Received message",{event:t.event,messageID:e}),M(this,Je).emit(t.event.toString(),{id:e,payload:r})},Tl=new WeakSet,up=function(){return M(this,Me).readyState===1},yl=new WeakSet,hp=function(s,t){ne(this,Wr,{reason:t,code:s}),M(this,Je).emit("disconnected",{code:s,reason:t})},pp=new WeakSet,tv=function(){const{reason:s,code:t}=M(this,Wr);t&&t!==1e3&&M(this,cr)&&M(this,pe).autoReconnect&&!M(this,vs)&&(M(this,Re).debug(`Triggering reconnection due to ${s}.`),M(this,Je).emit("reconnecting"),oe(this,_o,El).call(this))},_o=new WeakSet,El=async function(s=!0){if(s&&M(this,vs)){M(this,Re).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(M(this,vs)||M(this,dr).reset(),M(this,pe).maxReconnectionAttempts!==null&&M(this,dr).getAttempts()>=M(this,pe).maxReconnectionAttempts){M(this,Je).emit("failed"),ne(this,vs,!1);return}ne(this,vs,!0),oe(this,Io,Pl).call(this),oe(this,Gn,Co).call(this);try{if(await M(this,dr).wait(),M(this,cr)===!1)return;if(M(this,Re).debug(`Reconnection attempt ${M(this,dr).getAttempts()}`),M(this,Je).emit("reconnectAttempt",{attempt:M(this,dr).getAttempts()}),await this.connect(),!oe(this,Tl,up).call(this))throw Error("Reconnect Failed");ne(this,vs,!1),ne(this,Wr,{code:void 0,reason:void 0}),M(this,Je).emit("reconnected")}catch(t){M(this,Re).debug("Failed to reconnect."),M(this,Je).emit("reconnectFailure",{attempt:M(this,dr).getAttempts()}),oe(this,_o,El).call(this,!1)}},jn=new WeakSet,ko=function(s){try{return M(this,Me).send(s),!0}catch(t){return M(this,Re).error(t.message),!1}},bl=new WeakSet,mp=function(){this.config.disconnectOnPingTimeout&&(M(this,Re).debug("Resetting ping timeout"),oe(this,Gn,Co).call(this),ne(this,Hn,setTimeout(()=>{var s;M(this,Re).debug("Disconnecting the socket due to ping timeout"),ne(this,cr,!0);const t=3002,e="Ping timeout";(s=M(this,Me))==null||s.close(t,e),oe(this,yl,hp).call(this,t,e)},M(this,pe).pingTimeout)))},Gn=new WeakSet,Co=function(){M(this,Hn)&&(clearTimeout(M(this,Hn)),ne(this,Hn,void 0))},gp=new WeakSet,sv=function(){oe(this,Ro,wl).call(this),M(this,pe).clientInitiatedPings&&ne(this,qn,setInterval(()=>{oe(this,Tl,up).call(this)&&(M(this,Re).debug("Sending client-initiated ping"),oe(this,jn,ko).call(this,QS))},M(this,pe).clientInitiatedPingInterval))},Ro=new WeakSet,wl=function(){M(this,qn)&&(clearInterval(M(this,qn)),ne(this,qn,void 0))},Io=new WeakSet,Pl=function(){oe(this,Ro,wl).call(this),M(this,Me)&&(M(this,Me).onopen=void 0,M(this,Me).onerror=void 0,M(this,Me).onmessage=void 0,M(this,Me).onclose=void 0)};function rv(s){return`${s.slice(0,10)}...${s.slice(-10)}`}function uN(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://docs.realtime.cloudflare.com/api#/operations/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=Pi.baseURI.prod;t&&(n=t);const o=`https://${Ld({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new P("Invalid auth token","0004")}}var hN=Object.defineProperty,pN=Object.getOwnPropertyDescriptor,_l=(s,t,e,r)=>{for(var i=r>1?void 0:r?pN(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&&hN(t,e,i),i};const iv=65535,mN=3,gN=15e3,fN=8e3,SN=50,vN=1e3,TN=1e4,nv=(Tp=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){m(this,tt);m(this,Vc);m(this,bu);m(this,wu);m(this,Pu);m(this,xc);m(this,Uc);m(this,yn);m(this,ku);m(this,$c);m(this,Bc);m(this,Fc);m(this,Cu);m(this,Hc);m(this,qc);m(this,qs,void 0);m(this,ja,void 0);m(this,Pe,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");m(this,fn,[]);m(this,pi,void 0);m(this,Sn,!1);m(this,vn,void 0);m(this,mi,void 0);m(this,js,void 0);m(this,Gs,void 0);m(this,gi,void 0);m(this,Tn,void 0);m(this,Pt,0);m(this,fi,void 0);m(this,_t,!0);m(this,qe,void 0);if(!t||!e||!r)throw new P("peerId, meetingId, or authToken can not be empty","0404");g(this,qe,s),g(this,Gs,navigator.isReactNative?NS:jh),this.capabilities=i,this.roomName=e,this.authToken=r,g(this,qs,N(this,Vc,$p).call(this,t)),g(this,ja,t);const n=i.includes("PING");g(this,Pe,new lN(a(this,qs),{autoReconnect:!1,disconnectOnPingTimeout:n,queueOnDisconnect:!1,flushOnReconnect:!1,logger:this.logger,clientInitiatedPings:!n,clientInitiatedPingInterval:15e3})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,tt,mt).socketJoinAttempted}set joinAttempted(s){a(this,tt,mt).socketJoinAttempted=s}get telemetry(){return a(this,qe).getValue("telemetry")}get logger(){return a(this,qe).getValue("logger")}get peerId(){return a(this,qe).getValue("peerId")}updateCallstatsPeerId(s){const t=a(this,qe).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;g(this,qs,N(this,Vc,$p).call(this,s)),g(this,ja,s),a(this,qe).getValue("telemetry").resetPeerId(s),(t=a(this,qe).getValue("apiClient"))==null||t.setHeader("tracing-id",s),this.updateCallstatsPeerId(s),Or.remapContext(s,a(this,qe)),this.logger.info(`Attempting websocket connection with URL: ${a(this,yn,hd)}`),a(this,Pe).updateURL(a(this,qs))}get url(){return a(this,qs)}async connect(){var t;const s=a(this,Pt)+1;g(this,Pt,s),N(this,$c,Hp).call(this),a(this,tt,mt).socketJoinAttempted=!0,g(this,_t,!0),N(this,Pu,pT).call(this);try{if(await a(this,Pe).connect(),!a(this,_t)||s!==a(this,Pt))throw new Error("Socket connection was canceled");N(this,Uc,Fp).call(this,this.peerId),(t=a(this,js))!=null||g(this,js,this.peerId),a(this,tt,mt).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}catch(e){throw this.logger.error(`Websocket connection failed with URL: ${a(this,yn,hd)}`,{error:e}),a(this,_t)&&s===a(this,Pt)&&N(this,Fc,jp).call(this,s),e}}disconnect(){a(this,tt,mt).socketJoinAttempted=!1,g(this,Pt,a(this,Pt)+1),g(this,_t,!1),N(this,$c,Hp).call(this),N(this,xc,Bp).call(this),g(this,js,void 0),a(this,Pe).disconnect(),a(this,tt,mt).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Pe).readyState===1}catch(s){return!1}}sendMessage(s,t,e){if(!a(this,Hc,Gp))return!1;const r={};return a(this,qe).getValue("telemetry").injectContext(r),a(this,Pe).send(s,e!=null?e:N(this,qc,Wp).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,Hc,Gp))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,R)=>{d&&clearTimeout(d),a(this,Pe).removeListener(n,I),a(this,Pe).removeListener(iv,R),a(this,Pe).removeListener(Lr.errorResponse,R),a(this,Pe).removeListener(fs.errorResponse,R)},u=r!=null?r:N(this,qc,Wp).call(this),h={};a(this,qe).getValue("telemetry").injectContext(h);const S=({id:I,payload:R})=>{if(u===I){let U;try{const D=PR.fromBinary(R);U=new Error(D.errorMessage)}catch(D){U=new Error("failed to parse error message",{cause:D});try{const x=PI.fromBinary(R);U=new Error(x.message)}catch(x){U=new Error("failed to parse error message",{cause:x})}}c(U),l(E,S)}},E=({id:I,payload:R})=>{u===I&&(o({id:I,payload:R}),l(E,S))};a(this,Pe).on(n,E),a(this,Pe).on(iv,S),a(this,Pe).on(Lr.errorResponse,S),a(this,Pe).on(fs.errorResponse,S),d=setTimeout(()=>{l(E,S),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Pe).send(s,u,e,new TextEncoder().encode(JSON.stringify(h)))||(l(E,S),c(new Error("Socket message could not be sent for the current peer ID")))})}on(s,t){a(this,Pe).on(s,t)}onStateEvent(s,t){a(this,Pe).on(s,t)}removeListener(s,t){a(this,Pe).removeListener(s,t)}removeListeners(s){a(this,Pe).removeListeners(s)}flush(){return a(this,Pe).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{var s;this.logger.info(`Websocket connected with URL: ${a(this,yn,hd)}`),(s=a(this,js))!=null||g(this,js,this.peerId),a(this,tt,mt).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{!a(this,_t)||a(this,fi)===a(this,Pt)||(this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t}}),a(this,tt,mt).updateSocketConnectionState("disconnected"),a(this,qe).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,tt,mt).joinAttempted}),N(this,Fc,jp).call(this,a(this,Pt)))})}},qs=new WeakMap,ja=new WeakMap,Pe=new WeakMap,tt=new WeakSet,mt=function(){return a(this,qe).getValue("connectionHandler")},fn=new WeakMap,pi=new WeakMap,Sn=new WeakMap,vn=new WeakMap,mi=new WeakMap,js=new WeakMap,Gs=new WeakMap,gi=new WeakMap,Tn=new WeakMap,Pt=new WeakMap,fi=new WeakMap,_t=new WeakMap,qe=new WeakMap,Vc=new WeakSet,$p=function(s){let t=ch({servicePrefix:"ws",baseURI:a(this,qe).getValue("baseURI")});const e=ao(a(this,qe),"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,fn).length>0&&{oldPeerIds:a(this,fn).join(",")},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(n=>Kd[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},bu=new WeakSet,uT=function(){if(!a(this,js))return;const s=new URL(a(this,qs));return s.protocol=s.protocol==="ws:"?"http:":"https:",s.pathname=`${s.pathname.replace(/\/+$/,"")}/ping`,s.search="",s.searchParams.set("peerId",a(this,js)),s.href},wu=new WeakSet,hT=async function(){const s=N(this,bu,uT).call(this);if(!s||a(this,Sn))return;const t={},e=typeof AbortController=="function"?new AbortController:void 0;let r;g(this,Sn,!0),g(this,mi,t),g(this,vn,e);try{e&&(r=a(this,Gs).setTimeout(()=>e.abort(),fN));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,mi)===t&&this.logger.warn("SocketService::API ping request failed",{error:i,networkCall:{url:s}})}finally{r!==void 0&&a(this,Gs).clearTimeout(r),a(this,mi)===t&&(g(this,Sn,!1),g(this,mi,void 0),g(this,vn,void 0))}},Pu=new WeakSet,pT=function(){a(this,pi)===void 0&&g(this,pi,a(this,Gs).setInterval(()=>N(this,wu,hT).call(this),gN))},xc=new WeakSet,Bp=function(){var s;a(this,pi)!==void 0&&a(this,Gs).clearInterval(a(this,pi)),(s=a(this,vn))==null||s.abort(),g(this,pi,void 0),g(this,Sn,!1),g(this,mi,void 0),g(this,vn,void 0)},Uc=new WeakSet,Fp=function(s){g(this,fn,[s,...a(this,fn).filter(t=>t!==s)].slice(0,mN))},yn=new WeakSet,hd=function(){const s=new URL(a(this,qs)),t=s.searchParams.get("authToken");return t&&s.searchParams.set("authToken",rv(t)),s.href},_u=new WeakSet,mT=function(s){const t=Math.min(TN,vN*2**(s-1));return Math.floor(Math.random()*(t+1))},ku=new WeakSet,gT=function(s){return new Promise(t=>{var e;g(this,Tn,t),g(this,gi,a(this,Gs).setTimeout(()=>{g(this,gi,void 0),g(this,Tn,void 0),t()},N(e=nv,_u,mT).call(e,s)))})},$c=new WeakSet,Hp=function(){var s;a(this,gi)!==void 0&&(a(this,Gs).clearTimeout(a(this,gi)),g(this,gi,void 0)),(s=a(this,Tn))==null||s.call(this),g(this,Tn,void 0)},Bc=new WeakSet,qp=function(s,t){!a(this,_t)||s!==a(this,Pt)||(t&&this.logger.error("SocketService::Reconnect loop failed",{error:t}),g(this,_t,!1),N(this,xc,Bp).call(this),g(this,js,void 0),a(this,tt,mt).updateSocketConnectionState("failed"),a(this,qe).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_FAILED))},Fc=new WeakSet,jp=function(s){!a(this,_t)||a(this,fi)===s||(g(this,fi,s),a(this,tt,mt).updateSocketConnectionState("reconnecting"),N(this,Cu,fT).call(this,s).catch(t=>N(this,Bc,qp).call(this,s,t)))},Cu=new WeakSet,fT=async function(s){try{for(let t=1;t<=SN;t+=1){if(!a(this,_t)||s!==a(this,Pt)||(await N(this,ku,gT).call(this,t),!a(this,_t)||s!==a(this,Pt)))return;this.updateURL(Cn()),this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:t}}),a(this,tt,mt).updateSocketConnectionState("reconnectAttempt",t);try{if(await a(this,Pe).connect(!0),!a(this,_t)||s!==a(this,Pt))return;if(!this.isConnected)throw new Error("Reconnect failed");N(this,Uc,Fp).call(this,this.peerId),g(this,js,this.peerId),a(this,tt,mt).updateSocketConnectionState("reconnected"),a(this,qe).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,tt,mt).mediaJoinAttempted});return}catch(e){if(!a(this,_t)||s!==a(this,Pt))return;this.logger.error(`Websocket connection retry attempt ${t} failed with URL: ${a(this,yn,hd)}`,{error:e,socket:{retryAttempt:t}}),a(this,tt,mt).updateSocketConnectionState("reconnectFailure",t)}}N(this,Bc,qp).call(this,s)}finally{a(this,fi)===s&&g(this,fi,void 0)}},Hc=new WeakSet,Gp=function(){return this.isConnected&&a(this,ja)===this.peerId},qc=new WeakSet,Wp=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},m(Tp,_u),Tp);let Ao=nv;_l([y.trace("SocketService.connect")],Ao.prototype,"connect",1),_l([y.trace("SocketService.disconnect")],Ao.prototype,"disconnect",1),_l([y.trace("SocketService.sendMessagePromise")],Ao.prototype,"sendMessagePromise",1),_l([y.trace("SocketService.sendMessagePromiseWithTimeout")],Ao.prototype,"sendMessagePromiseWithTimeout",1);class yN{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=QI.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=w0.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=Vf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return Lf.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return p0.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise($.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise($.createConnectedRooms,t0.toBinary({payloads:t}));return Lf.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))}async updateConnectedRooms(t){}async disableConnectedRooms(t){const e=t.map(i=>({id:i})),r=await this.socketService.sendMessagePromise($.deleteConnectedRooms,u0.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise($.movePeers,T0.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 EN=Object.defineProperty,bN=Object.getOwnPropertyDescriptor,wN=(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 av extends Nt{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);m(this,Jt,void 0);g(this,Jt,e)}get isActive(){return this.meetings.length!==0}validateAlterAction(){const e=a(this,Jt).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,Jt).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,Jt).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,Jt).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,Jt).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)}`),await a(this,Jt).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title}))),this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`)}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,Jt).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,Jt).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,Jt).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})}}Jt=new WeakMap,wN([xt({maxInvocations:60,period:60})],av.prototype,"getConnectedMeetings",1);var PN=Object.defineProperty,_N=Object.getOwnPropertyDescriptor,fp=(s,t,e,r)=>{for(var i=r>1?void 0:r?_N(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 ov=(Cv=class{constructor(s){p(this,"connectedMeetings");m(this,Te,void 0);g(this,Te,s),this.connectedMeetings=new av(s)}get telemetry(){return a(this,Te).getValue("telemetry")}get logger(){return a(this,Te).getValue("logger")}static init(s){const t=new ov(s);return s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings()),t.setupEvents(),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,Te).getValue("connectedMeetingsSocketHandler").socketService.on($.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,Te).getValue("connectedMeetingsSocketHandler").socketService.on($.transferPeer,this.handleTransferPeer.bind(this)),a(this,Te).getValue("connectedMeetingsSocketHandler").socketService.on($.movedPeer,this.handleMovedPeer.bind(this)),a(this,Te).getValue("connectedMeetingsSocketHandler").socketService.on($.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,Te).getValue("connectedMeetingsSocketHandler").socketService.on($.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=a(this,Te).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,Te).getValue("self").videoEnabled,audio:a(this,Te).getValue("self").audioEnabled};try{a(this,Te).getValue("self").cleanupEvents(),await a(this,Te).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,Te).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 dv.init({...a(this,Te).getValue("options"),cachedUserDetails:null,defaults:{...a(this,Te).getValue("options").defaults,...e,mediaHandler:a(this,Te).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,Te).getValue("self");r.self.setName(a(this,Te).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,Te).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,Te).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=a(this,Te).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(s),e=new Map;this.connectedMeetings.meetings.forEach(r=>{e.set(r.id,r)}),t.forEach(r=>{e.has(r.id)?e.get(r.id).title=r.title:e.set(r.id,{...r,participants:[]})}),this.connectedMeetings.meetings=Array.from(e.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=a(this,Te).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})}},Te=new WeakMap,Cv);let kl=ov;fp([y.trace("ConnectedMeetingsController.getConnectedMeetings")],kl.prototype,"getConnectedMeetings",1),fp([y.trace("ConnectedMeetingsController.setupEvents")],kl.prototype,"setupEvents",1),fp([y.trace("ConnectedMeetingsController.switchMeeting")],kl.prototype,"switchMeeting",1);var kN=Object.defineProperty,CN=Object.getOwnPropertyDescriptor,Sp=(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&&kN(t,e,i),i};const Mo=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 D,x;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(U1(s),ye.isSupported()===!1)throw new P("Browser not supported","0010",c,!0);const d=vO(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 eD(s);s.setValue("connectionHandler",l);let u="",h=null;c.info("CF SFU is being used.");const f=Mo.createSocketService(s),S=f.connect();S.catch(()=>{});const E=d.getUserDetails();try{h=await E,u=((D=h.meeting)==null?void 0:D.title)||"",s.setValue("presetName",h.preset.name)}catch(B){throw c.error("Failed to get user details",{error:B}),f.disconnect(),B instanceof el?B.status===401?new P("Unauthorized. The auth token may be invalid or expired. (401)","0004"):B.status===403?new P("Access denied. Insufficient permissions to join the meeting. (403)","0004"):B.status===404?(c.error("[ERROR:0004] participant-details returned 404."),new P("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")):B.status>=500?new P(`The server encountered an error. Try again. (${B.status})`,"0001"):B.isHttpError?new P(`Request rejected by the server. (${B.status})`,"0001"):B.isTimeout?new P("Connection timed out. Check the network and try again.","0001"):new P("Unable to connect to the server. Check the internet connection.","0001"):new P((B==null?void 0:B.message)||"Failed to initialize.","0001")}try{await S}catch(B){c.error("[Controller]: Failed to connect to socket server:",{error:B})}const k=zh.init(h.preset,!s.getValue("modules").theme);s.setValue("theme",k);const I=Qh.init(s,k.viewType,h.preset.permissions),R=Mo.setupControllers(f,s,h,u,k,I);HO(k)&&((x=Mo.createRoomNodeClient(s,f).initializeConnection(h.participant.name,i,!1,I))==null||x.catch(q=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:q})}));const{controllers:U}=await R;return Ok(),new Mo(e,U,s)}static async setupControllers(s,t,e,r,i,n){var Le,V,C;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:(Le=h.enableHighBitrate)!=null?Le:!1,enableStereo:(V=h.enableStereo)!=null?V:!1}},...d}),t.setValue("maxPreferredStreams",ye.isMobile()?i.maxVideoStreams.mobile:i.maxVideoStreams.desktop);let f,S,E,k,I,R,U,D,x;const B=new H1(t,s),q=new yN(s);t.setValue("connectedMeetingsSocketHandler",q);const Z=new ml(t,s),se=new rr(t,s),at=new K1(s),kt=new xS(t,s),Kt=new z1(t,s),A=new F1(s),T=await Hr.init(t,kt,c,n,i);t.setValue("selfController",T);const w=await rS.init(t,T.self,kt,B,r);o.participant&&(D=new or(t,T.self,kt)),(C=o.e2ee)!=null&&C.enabled&&o.e2ee.manager.init(l,t.getValue("peerSessionStore")),o.chat&&(S=await ho.init(t,se,T.self,D.participants)),o.internals&&(I=await qh.init(t)),o.livestream&&i.viewType===Ys.Livestream&&(U=new PS(t,T.self,A)),o.poll&&(f=await Zf.init(t,T.self,Z)),o.recording&&(R=new lS(t,T.self,kt)),o.stage&&(E=new iS(t,at,kt,T.self,D.participants));const F=new XD(t,Kt);if(o.plugin){if(!D)throw new P("The plugin module cannot be initialized without the `participant` module","0102");const Be=d.plugins||[];k=await cS.init(t,Be,T.self,F)}if(o.connectedMeetings&&(x=await kl.init(t)),o.pip){const Be=await uh._init(t,T.self);t.setValue("pip",Be)}return{theme:i,permissions:n,controllers:{storesManager:F,pollController:f,selfController:T,metaController:w,chatController:S,stageController:E,pluginController:k,recordingController:R,internalsController:I,livestreamController:U,participantController:D,connectedMeetingsController:x}}}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 s.getValue("logger").info(`Socket service capabilities: ${JSON.stringify(i)}`),new Ao(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Cl=Mo;Sp([y.trace("Controller.init")],Cl,"init",1),Sp([y.trace("Controller.createRoomNodeClient")],Cl,"createRoomNodeClient",1),Sp([y.trace("Controller.createSocketService")],Cl,"createSocketService",1);class RN{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 cv=new RN;class IN{constructor(){m(this,Ru);m(this,Si,new Audio);m(this,En,new MediaStream);m(this,bn,new Map);m(this,jc,void 0);a(this,Si).srcObject=a(this,En),a(this,Si).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,bn).has(e.id)||(a(this,En).addTrack(e),a(this,bn).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,Si).setSinkId(t)}removeTrack(t){const e=a(this,bn).get(t);e&&(a(this,En).removeTrack(e),a(this,bn).delete(t))}async play(){return a(this,Si).srcObject=a(this,En),a(this,Si).play().catch(t=>{N(this,Ru,ST).call(this,t)})}onError(t){g(this,jc,t)}}Si=new WeakMap,En=new WeakMap,bn=new WeakMap,jc=new WeakMap,Ru=new WeakSet,ST=function(t){var e;(e=a(this,jc))==null||e.call(this,t)};class AN extends IN{constructor(){super();m(this,wn,void 0);g(this,wn,new Map)}addParticipantTrack(e,r){a(this,wn).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,wn).get(e);r&&this.removeTrack(r),a(this,wn).delete(e)}}wn=new WeakMap;var MN=Object.defineProperty,ON=Object.getOwnPropertyDescriptor,Rl=(s,t,e,r)=>{for(var i=r>1?void 0:r?ON(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&&MN(t,e,i),i};let Jr=(Rv=class{constructor(t,e){m(this,Fe,void 0);m(this,Pn,void 0);g(this,Pn,t),g(this,Fe,e)}get peerId(){return a(this,Pn).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:Cn(),n=Or.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new CS(n,o);return await c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var f,S,E,k,I,R,U;ye.init();const e=(S=(f=t==null?void 0:t.cachedUserDetails)==null?void 0:f.peerId)!=null?S:Cn(),{authToken:r,baseURI:i}=t,{meetingId:n,...o}=uN(r,i);if((E=o.baseURI)!=null&&E.includes("dyte.io"))throw new P("Dyte Base URIs are no longer supported. Use RealtimeKit Base URIs.","0001");window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=Jr.setupContext(e,t,n,o),d=c.getValue("telemetry"),l=c.getValue("logger");ET(l),cv.init(l),d.init(c,{roomName:n,userId:o.participantId,organizationId:o.orgId,peerId:e},(I=(k=t.modules)==null?void 0:k.tracing)!=null?I:!0,(U=(R=t==null?void 0:t.modules)==null?void 0:R.devTools)==null?void 0:U.logLevel),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:rv(t.authToken)}});const u=await Cl.init(c),h=new Jr(c,u);return c.setValue("meeting",h),h}static setupContext(t,e,r,i){var d,l;const n=Or.createContext(t,e),o={...dk,...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",lk({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Ms(e.cachedUserDetails)),n.setValue("sdkVersion","2.0.3-staging.6"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new AN),n}async join(){const{selfController:t}=a(this,Fe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){var r;cv.cleanup(),a(this,Pn).getValue("peerSessionStore").reset(),(r=a(this,Fe).pluginController)==null||r.cleanup();const{selfController:e}=a(this,Fe);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,Fe).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,Fe).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,Fe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,Fe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,Fe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,Fe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,Fe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Fe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,Fe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,Fe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,Fe).stageController)==null?void 0:t.stage}get stores(){return a(this,Fe).storesManager}get audio(){return a(this,Pn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,Fe).internalsController)==null?void 0:t.internals}},Fe=new WeakMap,Pn=new WeakMap,Rv);Rl([ct("0002"),nr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Jr.prototype,"join",1),Rl([ct("0003")],Jr.prototype,"leave",1),Rl([ct("0001"),nr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Jr,"init",1),Jr=Rl([ct("0000")],Jr);const dv=Jr;return dv}();
|
|
16
|
+
`},Mi=VS,M1=A1,ml=M1,Oi=Mi.parse;Mi.parseParams,Mi.parseFmtpConfig,Mi.parsePayloads,Mi.parseRemoteCandidates,Mi.parseImageAttributes,Mi.parseSimulcastStreamList;function O1(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}class D1 extends hl{constructor(e,r){var i;super(e);m(this,Us);m(this,dc);m(this,Jl);m(this,Kl);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,cc,void 0);m(this,sn,void 0);m(this,xs,void 0);m(this,Wl,void 0);this.id=r.id,this.localId=r.localId,g(this,cc,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,g(this,xs,!1),this.producerId=r.producerId,this.track=r.track,g(this,sn,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,D(this,Jl,Wv).call(this),g(this,Wl,e)}get closed(){return a(this,xs)}get kind(){return this.track.kind}get paused(){return a(this,sn)}close(e,r){a(this,xs)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,a(this,Us,vi)),g(this,xs,!0),r&&(D(this,Kl,Jv).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(a(this,xs))throw new It("closed");return a(this,cc).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",a(this,Us,vi)),a(this,xs)){this.logger.error("consumer::pause() | Consumer closed",a(this,Us,vi));return}g(this,sn,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",a(this,Us,vi)),a(this,xs)){this.logger.error("Consumer::resume() | Consumer closed",a(this,Us,vi));return}g(this,sn,!1),this.track.enabled=!0,this.safeEmit("resume")}}cc=new WeakMap,sn=new WeakMap,xs=new WeakMap,Wl=new WeakMap,Us=new WeakSet,vi=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},dc=new WeakSet,xp=function(){this.logger.debug('Consumer::track "ended" event',a(this,Us,vi)),this.safeEmit("trackended")},Jl=new WeakSet,Wv=function(){this.track.addEventListener("ended",D(this,dc,xp).bind(this))},Kl=new WeakSet,Jv=function(){try{this.track.removeEventListener("ended",D(this,dc,xp)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...a(this,Us,vi),error:e})}};const np="transport closed",Ca=class extends hl{constructor(e,{id:r,direction:i,handlerFactory:n,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:u,config:h}){var C,I,R;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,ka,void 0);g(this,ka,e);const f=e.getValue("logger");f.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const S=O1(l,{});delete S.iceServers,delete S.iceTransportPolicy,delete S.bundlePolicy,delete S.rtcpMuxPolicy,delete S.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new rp(f,!0),this.handler=n(),this.handler.enableHighBitrate=(C=h==null?void 0:h.enableHighBitrate)!=null?C:!1,this.handler.enableStereo=(I=h==null?void 0:h.enableStereo)!=null?I:!1,this.handler.enableDtx=(R=h==null?void 0:h.enableDtx)!=null?R:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:o,iceTransportPolicy:c,additionalSettings:l,proprietaryConstraints:d}),this.appData=u||{};const E=3e4;this.transportConnectionPromise=new Promise(U=>{const N=setTimeout(()=>{f.error("ICE connection timeout - possible firewall blocking WebRTC or TURN unreachable",{transport:{id:this.id,type:this.direction}}),U(!1)},E);this.once("connected",()=>{clearTimeout(N),U(!0)}),this.once("disconnect",()=>{clearTimeout(N),U(!1)}),this.once("close",()=>{clearTimeout(N),U(!1)})}),this.handler.on("@connectionstatechange",U=>{U!==this.connectionState&&(this.logger.debug(`connection state changed to ${U}`),this.connectionState=U,U==="connected"&&(this.connected=!0,this.emit("connected")),U==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(U==="failed"||U==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",U))}),this.handler.on("@icecandidate",({candidate:U})=>{this.closed||this.safeEmit("icecandidate",U)})}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(np).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(np)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new It("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 It("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new Eo("not a sending Transport");if(r.readyState==="ended")throw new It("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 Fr("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:f,localId:S,rtpSender:E}=await this.awaitQueue.push(async()=>{const{offerSdp:C,callback:I,sender:R,mid:U}=await this.handler.send({track:n,encodings:o,codecOptions:c,screenShare:h==null?void 0:h.screenShare}),{answer:N,producerId:x}=await r({offer:C,kind:n.kind,paused:l?!n.enabled||Object.hasOwn(n,"fakeTracks"):!1,appData:{...h||{},mid:U},codecOptions:c,producingTransportId:this.serverId}),B=await I(N);return{producerId:x,localId:B,rtpSender:R}},"Transport.produce");return this.createProducerObject({id:f,localId:S,track:n,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:u,appData:h,handler:this.handler,rtpSender:E})}async createProducerObject(e){const r=new N1(a(this,ka),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 It("closed");if(this.direction!=="recv")throw new Eo("not a receiving transport");if(!await this.transportConnectionPromise)throw new Fr("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(f=>l.push(f)).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=Oi(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=Oi(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=Oi(e.sdp),i={};return r.media.forEach(n=>{i[n.mid]=n.ext}),i}static setHeaderExtensionMappings(e,r){const i=Oi(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=Ca.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=Ca.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=Ca.setCodecAndFmtpMappings(c,i,n),c=Ca.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=Oi(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:f}=e,S=`${c}:${h}`,E={...e,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(C,I)=>{const R=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${S} producingPeerId: ${n}`),this.consumerTrackEvents.delete(S),E.isTimedout=!0,I(E)},5e3),U=(x,B)=>{try{if(x.readyState==="ended")clearTimeout(R),I(E);else{const q=x;q.enabled=!0,this.handler.midTransceiverMap.set(B.mid,B);const Z=new D1(a(this,ka),{id:r,localId:B.mid,transceiver:B,track:q,paused:d,producerId:i,producingPeerId:n,producingTransportId:o,handler:this.handler,appData:{...u,screenShare:l,peerId:n},rtpReceiver:B.receiver,mimeType:f});this.consumers.set(r,Z),Z.once("close",()=>{this.consumers.delete(Z.id),this.handler.midTransceiverMap.delete(B.mid)}),this.logger.info(`consumer created for peerId: ${n} of kind: ${h} with screenShare: ${l}`,{consumer:{id:r,kind:h,appData:{screenShare:l},peerId:n,producerId:i}}),this.emit("newconsumer",Z),clearTimeout(R),C(Z)}}catch(q){this.logger.warn("error while creating consumer:",q),clearTimeout(R),I(E)}},N=this.unknownTracksMap.get(S);N?(this.logger.info(`track event already received [trackId: ${N.track.id}] [mid: ${N.transceiver.mid}]`),this.unknownTracksMap.delete(S),U(N.track,N.transceiver)):(this.logger.info(`Registering onTrack handler for key ${S} [producingPeerId: ${n}]`),this.consumerTrackEvents.set(S,U))})}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 ap=Ca;ka=new WeakMap;const gl="OLD_PEER_PRODUCER";function US(s){return s===np||s===gl}class N1 extends hl{constructor(e,r){var i,n;super(e);m(this,Gt);p(this,"id");p(this,"localId");m(this,Ps,void 0);p(this,"kind");p(this,"appData");p(this,"rtpSender");m(this,Ra,void 0);m(this,Ia,void 0);m(this,rn,void 0);m(this,ds,!1);m(this,nt,void 0);m(this,ci,void 0);m(this,Aa,void 0);m(this,zl,void 0);this.id=r.id,this.localId=r.localId,g(this,nt,r.track),this.kind=(i=r.track)==null?void 0:i.kind,g(this,ci,r.disableTrackOnPause?!((n=r.track)!=null&&n.enabled):!1),g(this,Aa,void 0),g(this,Ra,r.stopTracks),g(this,Ia,r.disableTrackOnPause),g(this,rn,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),g(this,Ps,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),g(this,zl,e)}get closed(){return a(this,ds)}get track(){return a(this,nt)}get paused(){return a(this,ci)}get maxSpatialLayer(){return a(this,Aa)}async close(e){if(a(this,ds))return;if(e!==gl&&this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,a(this,Gt,Cs)),g(this,ds,!0),this._destroyTrack(),US(e)){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await a(this,Ps).stopSending(this.localId),{answer:n}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(n)}async getStats(){if(a(this,ds))throw new It("closed");return a(this,Ps).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",a(this,Gt,Cs)),a(this,ds)&&this.logger.error("Producer::pause() | Producer closed",a(this,Gt,Cs)),g(this,ci,!0),a(this,nt)&&a(this,Ia)&&(a(this,nt).enabled=!1),a(this,rn)&&a(this,Ps).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",a(this,Gt,Cs)),a(this,ds)){this.logger.error("Producer::resume() | Producer closed",a(this,Gt,Cs));return}g(this,ci,!1),a(this,nt)&&a(this,Ia)&&(a(this,nt).enabled=!0),a(this,rn)&&a(this,Ps).replaceTrack(this.localId,a(this,nt)),this.emit("resume")}async replaceTrack({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,a(this,Gt,Cs)),a(this,ds)){if(e&&a(this,Ra))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...a(this,Gt,Cs),error:r})}throw new It("closed")}else if(e&&e.readyState==="ended")throw new It("track ended");if(e===a(this,nt)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,a(this,Gt,Cs));return}(!a(this,rn)||!a(this,ci))&&await a(this,Ps).replaceTrack(this.localId,e),this._destroyTrack(),g(this,nt,e),this._handleTrack()}async setMaxSpatialLayer(e){if(a(this,ds))throw new It("closed");if(this.kind!=="video")throw new Eo("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await a(this,Ps).setMaxSpatialLayer(this.localId,e),g(this,Aa,e)}async setRtpEncodingParameters(e){if(a(this,ds))throw new It("closed");if(typeof e!="object")throw new TypeError("invalid params");await a(this,Ps).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,a(this,Gt,Cs)),this.safeEmit("trackended",this.track.id)}_handleTrack(){a(this,nt)&&a(this,nt).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(a(this,nt))try{a(this,nt).removeEventListener("ended",this._onTrackEnded),a(this,Ra)&&a(this,nt).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...a(this,Gt,Cs),error:r})}}}Ps=new WeakMap,Ra=new WeakMap,Ia=new WeakMap,rn=new WeakMap,ds=new WeakMap,nt=new WeakMap,ci=new WeakMap,Aa=new WeakMap,zl=new WeakMap,Gt=new WeakSet,Cs=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};class L1{constructor(t){m(this,Xe,void 0);p(this,"events");g(this,Xe,t),this.events=fs}async joinRoom(t,e,r,i=!1){const n={roomUuid:t,displayName:e,prejoined:i,capabilities:r};return(await a(this,Xe).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:QC.toBinary(n),timeout:5e3})).payload}async connectTransport(t){const e=(await a(this,Xe).sendMessagePromise(this.events.createWebRTCTransport,_C.toBinary(t))).payload,{transportId:r,description:i,producerIds:n}=bf.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,Xe).sendMessagePromise(this.events.produce,hR.toBinary(t))).payload,r=JR.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,Xe).sendMessagePromise(this.events.consume,aR.toBinary(t))).payload,{consumerIdsMap:{map:r},description:i}=GR.fromBinary(e);return{consumerStateMap:r,sessionDescription:i}}async closeProducer(t){const e=(await a(this,Xe).sendMessagePromise(this.events.closeProducer,TR.toBinary(t))).payload,{description:r}=eI.fromBinary(e);return r}async closeConsumer(t){return(await a(this,Xe).sendMessagePromise(this.events.closeConsumer,ER.toBinary(t))).payload}async updateConsumersSimulcastConfig(t){return(await a(this,Xe).sendMessagePromise(this.events.updateConsumersSimulcastConfig,lR.toBinary(t))).payload}async hostControlForPeer(t,e){const r={audio:e==="audio",screeShare:!1,video:e==="video",participantId:t},i=(await a(this,Xe).sendMessagePromise(this.events.hostControlPeer,CR.toBinary(r))).payload;if(!i)return!1;const{status:n}=oI.fromBinary(i);return n==="success"}async hostControlForAll(t){const e={audio:t==="audio",screenShare:!1,video:t==="video"},r=(await a(this,Xe).sendMessagePromise(this.events.hostControlAllPeers,IR.toBinary(e))).payload;if(!r)return!1;const{status:i}=dI.fromBinary(r);return i==="success"}async kickAll(){const t={propagateKickAcrossRooms:!1};a(this,Xe).sendMessagePromise($.kickAll,Rf.toBinary(t))}async kickPeer(t){a(this,Xe).sendMessagePromise($.kick,qf.toBinary(t))}async changeDisplayName(t){const e=(await a(this,Xe).sendMessagePromise(this.events.changeDisplayName,_R.toBinary(t))).payload;if(!e)return!1;const{status:r}=uI.fromBinary(e);return r==="success"}async notifySelfJoinComplete(){const t={},e=(await a(this,Xe).sendMessagePromise(this.events.selfJoinComplete,ZC.toBinary(t))).payload;return wh.fromBinary(e)}async audioActivity(t){a(this,Xe).sendMessage(this.events.audioActivity,CC.toBinary(t))}}Xe=new WeakMap;var Hr=(s=>(s.NEW="new",s.CONNECTING="connecting",s.RECONNECTING="reconnecting",s.DISCONNECTED="disconnected",s.CONNECTED="connected",s.FAILED="failed",s.CLOSED="closed",s))(Hr||{});class op extends hl{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 cp extends op{static createFactory(t){return()=>new cp(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=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e});if(!navigator.isReactNative){this.logger.debug("creating new transceiver");const d=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`senders available params: ${JSON.stringify(d)}`);const l=[];r&&r.length&&r.forEach(u=>{var f;const h=d.codecs.find(S=>S.mimeType.includes(u.name));if(u.parameters){this.logger.debug(`codecOption.parameters:${JSON.stringify(u.parameters)}`);const S=((f=h.sdpFmtpLine)==null?void 0:f.split(";"))||[];S.push(...u.parameters);const E=Array.from(new Set(S).values());h.sdpFmtpLine=E.join(";")}l.push(h)}),this.logger.info(`selected codecs: ${JSON.stringify(l)}`),n.setCodecPreferences(l)}const o=await this.pc.createOffer();if(await this.pc.setLocalDescription(o),r&&r.findIndex(({name:d})=>d==="opus")>=0){const{enableDtx:d,enableStereo:l}=this,u=this.enableHighBitrate?l?128e3:64e3:l?64e3:32e3;o.sdp=o.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${d?"usedtx=1;":""}${l?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${u}`),o.sdp+=`a=rtcp-fb:111 nack\r
|
|
17
|
+
`}this.midTransceiverMap.set(n.mid,n);const c=async d=>(this.logger.debug(`[SDP] send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),await this.pc.setRemoteDescription(d),n.mid);return this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(o,void 0,2)}]`),{offerSdp:o,callback:c,sender:n.sender,mid:n.mid}}}class fl extends op{constructor(e,r){super(e);p(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new fl(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,f)=>{var N;const S=Oi(h),E=S.media[S.media.length-1],C=E.rtp.filter(x=>f.some(B=>B.name===x.codec)),I=E.fmtp.filter(x=>C.some(B=>B.payload===x.payload)),R=(N=E.rtcpFb)==null?void 0:N.filter(x=>C.some(B=>B.payload===x.payload)),U=C.map(x=>x.payload);return S.media[S.media.length-1].rtp=C,S.media[S.media.length-1].fmtp=I,S.media[S.media.length-1].rtcpFb=R,S.media[S.media.length-1].payloads=U.join(" "),ml(S)},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),e==="audio"||e.kind==="audio"){const{enableDtx:h,enableStereo:f}=this,S=this.enableHighBitrate?f?128e3:64e3:f?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${f?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${S}`)}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 dp extends op{static createFactory(t){return()=>new dp(t)}get name(){return"Safari12"}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection(),this.logger.debug("Safari12::creating new transceiver");const n=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e}),o=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`Safari12::senders available params: ${JSON.stringify(o)}`);const c=[];r&&r.length>0&&r.forEach(u=>{var f;const h=o.codecs.find(S=>S.mimeType.includes(u.name));if(u.parameters){this.logger.info(`Safari12::codecOption.parameters:, ${JSON.stringify(u.parameters)}`);const S=((f=h.sdpFmtpLine)==null?void 0:f.split(";"))||[];S.push(...u.parameters);const E=[...new Set(S).values()];h.sdpFmtpLine=E.join(";")}c.push(h)}),this.logger.info(`Safari12::selected codecs: ${JSON.stringify(c)}`),n.setCodecPreferences(c);const d=await this.pc.createOffer();if(await this.pc.setLocalDescription(d),t==="audio"||t.kind==="audio"){const{enableStereo:u,enableDtx:h}=this,f=this.enableHighBitrate?u?128e3:64e3:u?64e3:32e3;d.sdp=d.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${u?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${f}`)}return this.midTransceiverMap.set(n.mid,n),{offerSdp:d,callback:async u=>(this.logger.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(u)}]`),await this.pc.setRemoteDescription(u),n.mid),sender:n.sender,mid:n.mid}}}function V1(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=em.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 x1{constructor(t,{handlerName:e,handlerFactory:r}={}){p(this,"handlerFactory");m(this,Er,void 0);m(this,nn,void 0);const i=t.getValue("logger");if(i.debug("constructor()"),g(this,Er,t),g(this,nn,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,nn).debug(`Device::constructor() | handler given: ${e}`);else if(e=V1(a(this,nn)),e)a(this,nn).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=cp.createFactory(a(this,Er));break;case"Safari12":this.handlerFactory=dp.createFactory(a(this,Er));break;case"Firefox60":this.handlerFactory=fl.createFactory(a(this,Er),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=fl.createFactory(a(this,Er),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=In();return new ap(a(this,Er),{id:e,...t,handlerFactory:this.handlerFactory})}}Er=new WeakMap,nn=new WeakMap;const U1=2e3;class $1 extends ft.EventEmitter{constructor(e,r){super();m(this,Na);m(this,pc);m(this,Yl);m(this,mc);m(this,Ql);m(this,Xl);m(this,Zl);m(this,eu);m(this,tu);m(this,gc);m(this,di);p(this,"context");m(this,Ma,void 0);m(this,Ze,void 0);m(this,et,void 0);m(this,lc,void 0);m(this,uc,void 0);m(this,an,void 0);m(this,Oa,void 0);m(this,hc,void 0);m(this,Da,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});m(this,on,void 0);m(this,$s,"all");this.context=e,g(this,an,r),g(this,Ma,new x1(e)),g(this,Oa,new L1(r)),g(this,hc,fs),a(this,Na,xu).mediaState={send:{state:Hr.NEW},recv:{state:Hr.NEW}},co(this.context,"forceRelay")&&g(this,$s,"relay"),this.logger.info(`ICE Transport Policy initially set to ${a(this,$s)}`),D(this,pc,Up).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return a(this,an)}get socketHandler(){return a(this,Oa)}get sendTransport(){return a(this,Ze)}get recvTransport(){return a(this,et)}get events(){return a(this,hc)}set sendTransportConnectedCallback(e){g(this,lc,e)}set recvTransportConnectedCallback(e){g(this,uc,e)}async setupTransports(e){await D(this,Yl,Kv).call(this,e);let r,i;e.send&&(r=D(this,mc,$p).call(this,a(this,Ze)).then(n=>{try{a(this,lc).call(this,n)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=D(this,mc,$p).call(this,a(this,et)).then(n=>{try{a(this,uc).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,Ze);this.logger.info("Closing send transport",{transport:{id:n,serverId:o,type:c}}),a(this,Ze).close(),a(this,Ze).removeAllListeners(),g(this,Ze,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,et);this.logger.info("Closing recv transport",{transport:{id:n,serverId:o,type:c}}),(r=a(this,et))==null||r.close(),(i=a(this,et))==null||i.removeAllListeners(),g(this,et,void 0)}D(this,pc,Up).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}Ma=new WeakMap,Ze=new WeakMap,et=new WeakMap,lc=new WeakMap,uc=new WeakMap,an=new WeakMap,Oa=new WeakMap,hc=new WeakMap,Da=new WeakMap,on=new WeakMap,$s=new WeakMap,Na=new WeakSet,xu=function(){return this.context.getValue("connectionHandler")},pc=new WeakSet,Up=function(){g(this,on,{send:void 0,recv:void 0})},Yl=new WeakSet,Kv=async function(e){var o,c,d,l,u,h,f,S;co(this.context,"forceRelay")&&g(this,$s,"relay"),this.logger.info(`ICE Transport Policy set to ${a(this,$s)}`);const n=await xt().getICEServers().catch(E=>(this.logger.warn(`failed to get iceservers from server: ${E.message}`),[]));e.send&&D(this,Xl,Yv).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:(f=(h=(u=this.context.getValue("defaults").mediaConfiguration)==null?void 0:u.audio)==null?void 0:h.enableStereo)!=null?f:!1,enableDtx:!1},iceTransportPolicy:a(this,$s)}),e.recv&&D(this,Zl,Qv).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(S=this.context.getValue("modules").e2ee)==null?void 0:S.enabled},iceTransportPolicy:a(this,$s)})},mc=new WeakSet,$p=async function(e){const{id:r,serverId:i,direction:n}=e;D(this,eu,Xv).call(this,e);try{return await LS(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 Fr("Cannot reconnect closed transport");await D(this,Ql,zv).call(this,e)}catch(l){if(l instanceof Fr){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}},Ql=new WeakSet,zv=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!a(this,an).isConnected)throw new Fr("Socket is not connected");if(e.connectionState==="closed")throw new Fr("Transport is closed");try{await e.connect(n=>D(this,tu,Zv).call(this,i,n)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(n){throw a(this,Da).transportFailureCount[i]+=1,n.message==="ice connection failed"?new Fr(n.message):n}},Xl=new WeakSet,Yv=function(e){var r,i;if(a(this,Ze)&&a(this,Ze).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=a(this,Ze))==null?void 0:r.id,serverId:(i=a(this,Ze))==null?void 0:i.serverId,type:"send"}});return}g(this,Ze,a(this,Ma).createTransport({...e,direction:"send"})),D(this,di,Ka).call(this,{state:Hr.NEW,direction:"send",sfuSessionId:a(this,Ze).serverId}),this.context.getValue("callstats").configureSendTransport(a(this,Ze))},Zl=new WeakSet,Qv=function(e){var r,i;if(a(this,et)&&a(this,et).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=a(this,et))==null?void 0:r.id,serverId:(i=a(this,et))==null?void 0:i.serverId,type:"recv"}});return}g(this,et,a(this,Ma).createTransport({...e,direction:"recv"})),D(this,di,Ka).call(this,{state:Hr.NEW,direction:"recv",sfuSessionId:a(this,et).serverId}),this.context.getValue("callstats").configureRecvTransport(a(this,et))},eu=new WeakSet,Xv=function(e){const{direction:r,id:i}=e;e.on("serveridchange",n=>{D(this,di,Ka).call(this,{state:e.connectionState,direction:r,sfuSessionId:n})}),e.on("connectionstatechange",async n=>{D(this,di,Ka).call(this,{state:n,direction:r,sfuSessionId:e.serverId}),this.logger.info(`Transport connection state changed for ${r} transport`,{transport:{id:i,serverId:e.serverId,type:r,status:n}});const o=()=>{const c=a(this,on)[r];c!==void 0&&(clearTimeout(c),a(this,on)[r]=void 0)};switch(n){case"connected":o(),a(this,Da).lastConnectionTime=performance.now();break;case"disconnected":a(this,on)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await D(this,gc,Bp).call(this,e.direction)},U1);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 D(this,gc,Bp).call(this,e.direction);break}}),e.on("icecandidate",async n=>{this.logger.debug("Sending iceCandidate:",{iceCandidate:n})})},tu=new WeakSet,Zv=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?Zs.SUBSCRIBER:Zs.PUBLISHER},producers:[]};return a(this,Oa).connectTransport(c)}catch(n){throw this.logger.error(`Error in ${e} transport connection:`,{error:n}),n}},gc=new WeakSet,Bp=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),a(this,an).isConnected&&a(this,Da).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),g(this,$s,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:a(this,Ze)}),this.context.getValue("peerSessionStore").emit(_.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:a(this,et)}),this.context.getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}const r=e==="send"?a(this,Ze):a(this,et);D(this,di,Ka).call(this,{state:Hr.CONNECTED,direction:e,sfuSessionId:r.serverId})},di=new WeakSet,Ka=function(e){const{state:r,direction:i,sfuSessionId:n}=e;a(this,Na,xu).mediaState[i]={state:r,sfuSessionId:n},this.context.getValue("peerSessionStore").emit(_.TRANSPORT_STATE_UPDATE,{transport:i,...a(this,Na,xu).mediaState[i]})};class B1{constructor(t,e,r,i,n){m(this,su,void 0);m(this,ls,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=n,g(this,su,t),g(this,ls,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,f={simulcast:{preferredRid:"f",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}};e.set(u,l),r.push({producingPeerId:l,producerId:u,producingTransportId:h,...f})});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,ls).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(f){}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,ls).info("Negotiating socket consumer",{transport:this.recvTransport}),a(this,ls).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:Zs.SUBSCRIBER}};return a(this,ls).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,AC.toBinary(r)),a(this,ls).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){a(this,ls).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,ls).info(`Closing consumers: ${JSON.stringify(n)}`);const o={description:{sdp:i.sdp,type:i.type,target:Zs.SUBSCRIBER},consumerIds:n,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=sI.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,ls).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:n})=>n)})}}su=new WeakMap,ls=new WeakMap;class lp{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return Oi(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,f;const c=lp.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:Zs.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(h=i.screenShare)!=null?h:!1,mimeType:`${e}/${(f=n[0])==null?void 0:f.name}`,producingTransportId:o},{answer:l,producerId:u}=await this.socketHandler.produce(d);return{answer:l,producerId:u}}}function F1(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 H1 extends $1{constructor(e,r){super(e,r);m(this,Sc);m(this,iu);m(this,nu);m(this,au);m(this,ou);m(this,cn,void 0);m(this,li,void 0);m(this,La,void 0);m(this,fc,void 0);m(this,Bs,void 0);m(this,ru,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});m(this,br,[]);m(this,Va,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{g(this,fc,new lp(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{a(this,La).clear(),g(this,Bs,new B1(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return a(this,cn)}get consumers(){return a(this,li)}get producerIdToConsumerIdMap(){return a(this,La)}get logger(){return this.context.getValue("logger")}reset(){g(this,cn,new Map),g(this,li,new Map),g(this,La,new Map)}async createProducer(e,r){var i,n;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const o=await this.sendTransport.produce(e,D(this,iu,eT).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(_.E2EE_ACTIVE_PRODUCER,o),D(this,nu,tT).call(this,o,r),o}catch(o){throw this.logger.error(`Failed to create ${((n=e==null?void 0:e.track)==null?void 0:n.kind)||"unknown"} producer`,{error:o}),a(this,ru).producerCreationFailureCount+=1,o}}async closeProducer(e,r){var n;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),(n=this.context.getValue("modules").e2ee)!=null&&n.enabled&&this.context.getValue("peerSessionStore").emit(_.E2EE_INACTIVE_PRODUCER,i)}catch(o){this.logger.error("Failed to close producer on server",{error:o,producer:i})}}closeAllProducers(){return Promise.all(Array.from(a(this,cn).entries()).map(([,e])=>e.close()))}async closeProducersLocally(e){var i;const r=(i=this.sendTransport)==null?void 0:i.handler;await Promise.all(e.map(async n=>{if(!n.closed){try{if(r){const o=r.midTransceiverMap.get(n.localId);o&&(await o.sender.replaceTrack(null),o.direction="inactive")}}catch(o){this.logger.warn("closeProducersLocally: failed to deactivate transceiver",{producer:{id:n.id,kind:n.kind,appData:n.appData},error:o})}try{await n.close(gl)}catch(o){this.logger.warn("closeProducersLocally: failed to close producer",{producer:{id:n.id,kind:n.kind,appData:n.appData},error:o})}}}))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){a(this,Va)||clearTimeout(a(this,Va)),g(this,br,a(this,br).concat(e)),await D(this,Sc,Fp).call(this)}closeConsumer(e){return this.closeConsumers([e])}async closeConsumers(e){if(!a(this,Bs))return;const r=e.map(i=>this.consumers.get(i)).filter(i=>i!==void 0);r.length!==0&&await a(this,Bs).close(r)}closeAllConsumers(){return this.closeConsumers(Array.from(a(this,li).keys()))}async switchConsumersToLayer(e,r){a(this,Bs).switchConsumersToLayer(e,r)}}cn=new WeakMap,li=new WeakMap,La=new WeakMap,fc=new WeakMap,Bs=new WeakMap,ru=new WeakMap,br=new WeakMap,Va=new WeakMap,Sc=new WeakSet,Fp=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=a(this,br).splice(0,a(this,br).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,D(this,au,sT).bind(this),a(this,Bs).negotiate.bind(a(this,Bs)));if(o.forEach(D(this,ou,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);g(this,br,a(this,br).concat(d)),g(this,Va,setTimeout(D(this,Sc,Fp).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}=F1(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})}}},iu=new WeakSet,eT=function(e){return a(this,fc).create(e)},nu=new WeakSet,tT=function(e,r){e.on("close",async(i,n)=>{const{reason:o}=i;if(o===gl)return;const{offer:c}=i;if(this.logger.info("producer::closing",{debuggingHint:o,producer:{...e,status:"closing"}}),!US(o)){const d={producerId:e.id,description:{sdp:c.sdp,type:c.type,target:Zs.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,cn).set(e.id,e)},au=new WeakSet,sT=async function(e){try{return await this.recvTransport.canConsume(),await a(this,Bs).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},ou=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,li).delete(e.id),this.context.getValue("peerSessionStore").emit(_.CONSUMER_CLOSED,{id:e.id})}),a(this,li).set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),this.context.getValue("peerSessionStore").emit(_.NEW_CONSUMER_CREATED,{id:e.id,appData:e.appData,peerId:e.peerId})};const hu=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,cu);m(this,du);m(this,vc,void 0);m(this,Tc,void 0);m(this,yc,void 0);m(this,xa,void 0);m(this,Ua,void 0);m(this,$a,void 0);m(this,Ec,void 0);m(this,bc,void 0);m(this,Ba,void 0);m(this,Mt,void 0);m(this,_s,void 0);m(this,ks,!1);m(this,dn,0);m(this,ln,0);m(this,wr,[]);m(this,wc,void 0);g(this,xa,t),g(this,Mt,t),g(this,vc,e),g(this,Tc,r),g(this,yc,i),g(this,Ua,n),g(this,$a,o),g(this,Ec,c),g(this,bc,d),g(this,Ba,l),g(this,wc,u),g(this,_s,t/2)}get voiceDetected(){return a(this,ks)}processAudioChunk(t){var o,c;const e=D(o=hu,lu,aT).call(o,t),r=D(c=hu,uu,oT).call(c,t);return D(this,cu,iT).call(this,e),e/a(this,_s)>a(this,Ba)&&e>a(this,Mt)&&r>a(this,vc)?(g(this,dn,a(this,dn)+1),g(this,ln,a(this,yc)),a(this,dn)>=a(this,Tc)&&g(this,ks,!0)):(g(this,dn,0),a(this,ln)>0?g(this,ln,a(this,ln)-1):a(this,ks)&&g(this,ks,!1),a(this,ks)||D(this,du,nT).call(this,e)),{energy:e,isVoice:a(this,ks)}}reset(){g(this,ks,!1),g(this,dn,0),g(this,ln,0),g(this,Mt,a(this,xa)),g(this,_s,a(this,xa)/2),g(this,wr,[])}getThresholdInfo(){return{currentEnergyThreshold:a(this,Mt),backgroundNoiseEnergy:a(this,_s),energyRatioThreshold:a(this,Ba)}}};let wo=hu;vc=new WeakMap,Tc=new WeakMap,yc=new WeakMap,xa=new WeakMap,Ua=new WeakMap,$a=new WeakMap,Ec=new WeakMap,bc=new WeakMap,Ba=new WeakMap,Mt=new WeakMap,_s=new WeakMap,ks=new WeakMap,dn=new WeakMap,ln=new WeakMap,wr=new WeakMap,wc=new WeakMap,cu=new WeakSet,iT=function(t){a(this,ks)?g(this,Mt,a(this,$a)*a(this,Mt)+(1-a(this,$a))*t):g(this,Mt,a(this,Ua)*a(this,Mt)+(1-a(this,Ua))*a(this,_s)),g(this,Mt,Math.max(a(this,Ec),Math.min(a(this,bc),a(this,Mt))))},du=new WeakSet,nT=function(t){if(t<a(this,Mt)*1.2)if(a(this,wr).push(t),a(this,wr).length>a(this,wc)&&a(this,wr).shift(),a(this,wr).length>=10){const e=[...a(this,wr)].sort((i,n)=>i-n),r=Math.floor(e.length/2);g(this,_s,e[r])}else g(this,_s,.95*a(this,_s)+.05*t)},lu=new WeakSet,aT=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},uu=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(wo,lu),m(wo,uu);class $S{constructor(t){p(this,"RNAudioSampleHandler");m(this,Pc,void 0);g(this,Pc,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,Pc).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()}}Pc=new WeakMap;class BS{constructor(t){p(this,"audioContext");p(this,"analyser");m(this,_c,void 0);g(this,_c,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return a(this,_c).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)}}_c=new WeakMap;class FS{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 q1=60,j1=400,Rc=class{constructor(t,e){m(this,pu);m(this,mu);m(this,Pr,void 0);m(this,_r,void 0);m(this,kr,void 0);m(this,kc,void 0);m(this,Fa,void 0);m(this,Ha,void 0);m(this,ui,void 0);m(this,un,void 0);m(this,qa,void 0);m(this,hn,void 0);m(this,Cr,void 0);m(this,Fs,void 0);this.reportRequest=e,g(this,hn,t),g(this,Ha,new wo);const{isReactNative:r}=navigator;g(this,Cr,r?new $S(a(this,hn)):new BS(a(this,hn))),g(this,Fs,r?FS:Jh)}get logger(){return a(this,hn).getValue("logger")}set producerId(t){g(this,kr,t)}set audioTrack(t){g(this,kc,t),a(this,Cr)instanceof BS&&(a(this,Cr).audioTrack=t)}start(){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${a(this,kr)}`),a(this,Pr)&&a(this,Fs).clearInterval(a(this,Pr)),g(this,Pr,a(this,Fs).setInterval(async()=>{var i;if(!a(this,kc)||!a(this,kr))return;const{energy:t}=D(this,pu,cT).call(this),e=D(i=Rc,Cc,Hp).call(i,t);let r=.9;a(this,qa)!==e&&a(this,qa)?r=.9:e?r=.3:r=.5,g(this,Fa,(a(this,Fa)||0)*(1-r)+t*r)},q1)),a(this,_r)&&a(this,Fs).clearInterval(a(this,_r)),g(this,_r,a(this,Fs).setInterval(D(this,mu,dT).bind(this),j1))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${a(this,kr)}`),a(this,Pr)&&(a(this,Fs).clearInterval(a(this,Pr)),g(this,Pr,void 0)),a(this,_r)&&(a(this,Fs).clearInterval(a(this,_r)),g(this,_r,void 0))}catch(t){}a(this,Ha).reset(),a(this,Cr)instanceof $S&&a(this,Cr).stop()}};let Po=Rc;Pr=new WeakMap,_r=new WeakMap,kr=new WeakMap,kc=new WeakMap,Fa=new WeakMap,Ha=new WeakMap,ui=new WeakMap,un=new WeakMap,qa=new WeakMap,hn=new WeakMap,Cr=new WeakMap,Fs=new WeakMap,pu=new WeakSet,cT=function(){var o;const{samples:t}=a(this,Cr),{energy:e,isVoice:r}=a(this,Ha).processAudioChunk(t),i=D(o=Rc,gu,lT).call(o,e);return i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,ui)||i<a(this,ui))&&g(this,ui,i),(!a(this,un)||i>a(this,un))&&g(this,un,i),{energy:(i-a(this,ui))/(a(this,un)-a(this,ui))*10||0,isVoice:r})},Cc=new WeakSet,Hp=function(t){return t<5},mu=new WeakSet,dT=function(t=a(this,Fa)){var r;if(!a(this,kr)||!t)return;const e={producerId:a(this,kr),energy:Math.round(t),silent:D(r=Rc,Cc,Hp).call(r,t)};g(this,qa,e.silent),this.reportRequest(e)},gu=new WeakSet,lT=function(t){const e=Math.log10(t);return Math.round(e)},m(Po,Cc),m(Po,gu);var G1=Object.defineProperty,W1=Object.getOwnPropertyDescriptor,de=(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};const HS=(wp=class{constructor(s,t){m(this,Rr);m(this,Su);m(this,vu);m(this,Tu);m(this,Oc);m(this,yu);m(this,Eu);m(this,Pt);m(this,fn);m(this,wu);m(this,Sn);m(this,Pu);m(this,_u);p(this,"context");p(this,"authToken");p(this,"e2ee");m(this,Ic,void 0);m(this,Ac,void 0);m(this,ut,void 0);m(this,H,void 0);m(this,fu,void 0);m(this,wt,void 0);m(this,pn,void 0);m(this,mn,void 0);m(this,gn,void 0);m(this,Mc,void 0);m(this,Wt,null);m(this,Hs,void 0);m(this,ht,void 0);m(this,qs,void 0);m(this,Ot,void 0);var r,i;this.context=s;const{socket:e}=t;this.mediaJoined=!1,g(this,ut,e),g(this,pn,!1),g(this,H,new H1(s,e)),g(this,wt,a(this,H).events),g(this,Hs,new Set),g(this,ht,new Map),g(this,qs,new Map),g(this,mn,!1),g(this,gn,new rp(s.getValue("logger"))),g(this,Ot,new Po(this.context,a(this,H).socketHandler.audioActivity.bind(a(this,H).socketHandler))),this.e2ee=(i=(r=s.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?i:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),g(this,Mc,dh(async()=>{if(!a(this,Rr,Rn).mediaJoinAttempted)return;const{roomJoined:n}=await this.joinRoom(a(this,Ac),a(this,Ic),!0);n&&(this.context.getValue("peerSessionStore").emit(_.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(_.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,Rr,Rn).mediaJoined}set mediaJoined(s){a(this,Rr,Rn).mediaJoined=s}reset({resetTransportQueue:s}){this.logger.info(`Resetting media node client: closing all transports, producers, consumers, and queues(resetTransportQueue: ${s}).`),this.closePreReconnectProducers(),a(this,H).closeAllProducers(),a(this,H).closeAllConsumers(),a(this,ht).clear(),a(this,Hs).clear(),g(this,Wt,null),s&&a(this,gn).stop(),a(this,H).stopAllTransports(),a(this,H).reset(),s&&g(this,gn,new rp)}async joinRoom(s,t,e=!1,r={}){a(this,Rr,Rn).mediaJoinAttempted=!0,g(this,pn,!0);try{return await a(this,gn).push(()=>D(this,Su,uT).call(this,s,t,e,r),"joinRoom")}catch(i){return this.logger.error("Error in room joining process",{error:i}),this.context.getValue("peerSessionStore").emit(_.ROOM_NODE_FAILED),{roomJoined:!1,error:i}}}async initializeConnection(s,t,e=!1,r={}){return a(this,Wt)?a(this,Wt):(g(this,Wt,(async()=>{try{await D(this,Oc,qp).call(this,s,t,e,r)}catch(i){throw g(this,Wt,null),i}})()),a(this,Wt))}getConsumers(){return a(this,H).consumers}getProducers(){return a(this,H).producers}async closePreReconnectProducers(){const s=[];a(this,qs).forEach(t=>{s.push(...t)}),a(this,qs).clear(),await a(this,H).closeProducersLocally(s)}async leaveRoom(){a(this,H).stopAllTransports(),g(this,mn,!1),a(this,Rr,Rn).mediaJoinAttempted=!1;const s={closeRoom:!1};try{a(this,ut).sendMessage(a(this,wt).leaveRoom,tR.toBinary(s))||this.logger.warn("MediaNodeClient.leaveRoom: media leave was not sent")}catch(e){this.logger.error("MediaNodeClient.leaveRoom: media leave failed",{error:e})}this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct().catch(e=>{this.logger.error("leaveRoom::telemetry_destruct_failed",{error:e})})}async activatePeers(s){return this.createConsumers(s)}async createConsumers(s){return s.length===0?Promise.resolve():a(this,H).createConsumers(s)}async closeConsumers(s){if(!s.length)return;const t=s.reduce((e,r)=>{const i=a(this,H).producerIdToConsumerIdMap.get(r.producerId);return i?(e.push(i),e):(this.logger.warn(`consumer not found in close consumers: ${r.producerId}`),e)},[]);await this.closeConsumersById(t)}async closeConsumersById(s){s.length&&await a(this,H).closeConsumers(s)}async _shareWebcam(s){var l,u,h,f;const t=ce.WEBCAM,e=D(this,Pt,Qt).call(this,t);if(e){const S=await e;if(a(this,H).producers.has(S)){const E=a(this,H).producers.get(S);if(!E.closed)return await E.replaceTrack({track:s}),await this.resumeWebcam(t),s;await this.disableWebcam()}return this._shareWebcam(s)}const r=D(this,_u,TT).call(this,s),i=co(this.context,"disableSimulcast"),n=(u=(l=this.context)==null?void 0:l.getValue("overrides"))==null?void 0:u.simulcastConfig;i||n&&n.disable||!((f=(h=this.context)==null?void 0:h.getValue("theme"))!=null&&f.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),r.encodings=ID(this.context,s),this.logger.info(`Simulcast encodings: ${JSON.stringify(r.encodings)}`));const c=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,ht).delete(t)},d=a(this,H).createProducer(r,c);return D(this,fn,hd).call(this,t,d.then(S=>S.id)),d.then(async S=>(await D(this,Sn,pd).call(this,t),S.track))}async shareWebcam(s){return s===void 0?null:(this.logger.debug("Calling _shareWebcam with VP8 codec"),this._shareWebcam(s))}async shareScreen(s){const{video:t,audio:e}=s;if(t===void 0)return;const r={track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ee.isElectron()},stopTracks:!1},i=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,ht).delete(ce.SCREENSHARE_VIDEO),a(this,ht).delete(ce.SCREENSHARE_AUDIO)},n=a(this,H).createProducer(r,i);D(this,fn,hd).call(this,ce.SCREENSHARE_VIDEO,n.then(c=>c.id));let o;if(e){const c={track:e,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ee.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},d=()=>{};o=a(this,H).createProducer(c,d),D(this,fn,hd).call(this,ce.SCREENSHARE_AUDIO,o.then(l=>l.id))}await Promise.all([n,o||Promise.resolve()]),await Promise.all([D(this,Sn,pd).call(this,ce.SCREENSHARE_VIDEO),D(this,Sn,pd).call(this,ce.SCREENSHARE_AUDIO)]),this.context.getValue("callstats").screenShareStart()}async shareMic(s){try{if(s===void 0)throw new It("track undefined");const t=D(this,Pt,Qt).call(this,ce.MIC);if(t){const n=await t;if(a(this,H).producers.has(n)){const o=a(this,H).producers.get(n);if(!o.closed){await o.replaceTrack({track:s}),await this.resumeMic(),a(this,Ot)&&(a(this,Ot).audioTrack=s,a(this,Ot).producerId=n,a(this,Ot).start());return}await a(this,H).closeProducer(n,{stopTrack:!1})}await this.shareMic(s);return}const e=D(this,Pu,vT).call(this,s),r=()=>{a(this,ht).delete(ce.MIC)},i=a(this,H).createProducer(e,r);D(this,fn,hd).call(this,ce.MIC,i.then(n=>n.id)),await i.then(async n=>{await D(this,Sn,pd).call(this,ce.MIC),a(this,Ot)&&(a(this,Ot).audioTrack=n.track,a(this,Ot).producerId=n.id,a(this,Ot).start())})}catch(t){throw new P(t)}}async pauseMic(){var r;const s=await D(this,Pt,Qt).call(this,ce.MIC),t=a(this,H).producers.get(s);if(!t){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(t.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}t.pause(),(r=a(this,Ot))==null||r.stop();const e={producerId:t.id,pause:!0};a(this,ut).sendMessage(a(this,wt).toggleProducer,zd.toBinary(e))}async pauseWebcam(){const s=await D(this,Pt,Qt).call(this,ce.WEBCAM),t=a(this,H).producers.get(s);if(!t){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}t.pause();const e={producerId:t.id,pause:!0};a(this,ut).sendMessage(a(this,wt).toggleProducer,zd.toBinary(e))}async resumeMic(){const s=await D(this,Pt,Qt).call(this,ce.MIC),t=a(this,H).producers.get(s);if(!t){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!t.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}t.resume(),t.appData.e2ee&&this.context.getValue("peerSessionStore").emit(_.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};a(this,ut).sendMessage(a(this,wt).toggleProducer,zd.toBinary(e))}async resumeWebcam(s=ce.WEBCAM){const t=await D(this,Pt,Qt).call(this,s),e=a(this,H).producers.get(t);if(!e){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!e.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(_.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,ut).sendMessage(a(this,wt).toggleProducer,zd.toBinary(r))}async disableWebcam(){const s=ce.WEBCAM,t=await D(this,Pt,Qt).call(this,s);D(this,wu,ST).call(this,s),t&&await a(this,H).closeProducer(t)}async disableMic(){var t;const s=await D(this,Pt,Qt).call(this,ce.MIC);s&&await a(this,H).closeProducer(s),(t=a(this,Ot))==null||t.stop(),a(this,ht).delete(ce.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const s=await D(this,Pt,Qt).call(this,ce.SCREENSHARE_VIDEO),t=await D(this,Pt,Qt).call(this,ce.SCREENSHARE_AUDIO);s&&await a(this,H).closeProducer(s),t&&await a(this,H).closeProducer(t),a(this,Hs).clear(),a(this,ht).delete(ce.SCREENSHARE_VIDEO),a(this,ht).delete(ce.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(s,t){if(s){const e=await D(this,Pt,Qt).call(this,ce.WEBCAM);await a(this,H).closeProducer(e,{stopTrack:!1}),this.shareWebcam(s)}if(t){const e=await D(this,Pt,Qt).call(this,ce.SCREENSHARE_VIDEO);await a(this,H).closeProducer(e,{stopTrack:!1}),this.shareScreen({video:t})}}async changeDisplayName(s,t){const e={displayName:s,participantId:t!=null?t:this.peerId};if(!await a(this,H).socketHandler.changeDisplayName(e))throw new Error("failed to change display name!")}kick(s){const t={peerIds:[s]};a(this,H).socketHandler.kickPeer(t)}kickAll(){a(this,H).socketHandler.kickAll()}async muteAll(s){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(s){if(!await a(this,H).socketHandler.hostControlForPeer(s,"audio"))throw new Error("failed to mute given participant")}async disableVideo(s){if(!await a(this,H).socketHandler.hostControlForPeer(s,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(s){const t={participantId:s!=null?s:""};try{await a(this,ut).sendMessagePromise(a(this,wt).globalPinPeer,gR.toBinary(t))}catch(e){this.logger.error("Error in pinning peer:",{error:e})}}validateScreenShare(s){return this.peerId===s.peerId&&a(this,H).producers.get(s.producerId)&&a(this,Hs).add(s.consumerPeerId),a(this,Hs).size}async switchConsumersToLayer(s,t){const e=s.map(r=>this.getConsumers().get(r));a(this,H).switchConsumersToLayer(e,t)}async handleSocketEvents(){a(this,ut).on(a(this,wt).peerProducerCreateBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,producerState:e}=vI.fromBinary(s);if(t===this.peerId)return;e!=null&&e.mimeType||(e.mimeType=e.kind===er.AUDIO?"audio/opus":"video/VP8"),this.logger.info(`producer created broadcast: ${t}, producer state: ${e}`),this.context.getValue("peerSessionStore").emit(_.NEW_PRODUCER,{peerId:t,producer:{...e,kind:e.kind===er.AUDIO?"audio":"video",producingPeerId:t}})}catch(t){this.logger.error("error in peer-producer-create-broadcast",{error:t})}}),a(this,ut).on(a(this,wt).peerProducerToggleBroadcast,({payload:s})=>{if(this.mediaJoined)try{const t=Df.fromBinary(s),{participantId:e,initiatorParticipantId:r,producerState:{kind:i,pause:n,producerId:o,screenShare:c}}=t;if(c)return;const d=i===er.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${o}, kind:${d}, paused:${n} payload: ${Df.toJsonString(t)}`),e===this.peerId&&r!==this.peerId&&n&&this.context.getValue("peerSessionStore").emit(d==="audio"?_.MUTE_SELF:_.MUTE_SELF_VIDEO),e===this.peerId)return;this.context.getValue("peerSessionStore").emit(_.PRODUCER_TOGGLE,{peerId:e,producerId:o,paused:n,kind:d}),Array.from(this.getConsumers().values()).filter(u=>u.producerId===o).forEach(u=>{u.kind==="video"&&n||u.paused!==n&&(this.logger.debug(`consumer state mismatched for ${u.id}. updating consumer pause state ${u.paused} to ${n}`),n?(u.pause(),this.context.getValue("peerSessionStore").emit(_.CONSUMER_PAUSED,{id:u.id})):(u.resume(),this.context.getValue("peerSessionStore").emit(_.CONSUMER_RESUMED,{id:u.id})))})}catch(t){this.logger.error("error in producer toggle broadcast handler",{error:t})}}),a(this,ut).on(a(this,wt).peerLeaveBroadcast,async({payload:s})=>{if(this.mediaJoined)try{const{participantId:t}=Ph.fromBinary(s);if(t===this.peerId)return;this.logger.info(`peer left broadcast:${t}`),a(this,Hs).delete(t),a(this,H).consumers.forEach(e=>{e.peerId===t&&e.close()}),this.context.getValue("peerSessionStore").emit(_.PEER_CLOSED,{id:t})}catch(t){this.logger.error("error in peer left broadcast",{error:t})}}),a(this,ut).on(a(this,wt).peerProducerCloseBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,producerState:{producerId:e}}=EI.fromBinary(s);if(t===this.peerId)return;this.logger.info(`producer closed broadcast:${t}`),this.context.getValue("peerSessionStore").emit(_.PRODUCER_CLOSED,{peerId:t,producerId:e});const r=a(this,H).producerIdToConsumerIdMap.get(e);if(!r){this.logger.warn(`no consumer found for producer:${e}`);return}this.logger.info(`closing consumer ${r}, producer id: ${e}`),a(this,H).closeConsumer(r).then(()=>{this.logger.info(`closed consumer: ${r}`),a(this,H).producerIdToConsumerIdMap.delete(e),this.context.getValue("peerSessionStore").emit(_.CONSUMER_CLOSED,{id:r})}).catch(i=>{this.logger.error("error closing consumer",{error:i})})}catch(t){this.logger.error("error on producer close broadcast",{error:t})}}),a(this,ut).on(a(this,wt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,pn)&&!a(this,mn)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(_.ROOM_NODE_DISCONNECTED),a(this,Mc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(s=>{s.forEach((t,e)=>{const r=a(this,H).consumers.get(e);r&&this.context.getValue("peerSessionStore").emit(_.CONSUMER_SCORE_UPDATE,{id:e,kind:r.kind,peerId:r.peerId,score:t.score,scoreStats:t})})}),this.context.getValue("callstats").onProducerScore(s=>{s.forEach((t,e)=>{const r=Array.from(a(this,H).producers.values()).find(i=>i.id===e);r&&this.context.getValue("peerSessionStore").emit(_.PRODUCER_SCORE_UPDATE,{id:e,kind:r.kind,appData:r.appData,score:t.score,scoreStats:t})})})}},Ic=new WeakMap,Ac=new WeakMap,ut=new WeakMap,H=new WeakMap,fu=new WeakMap,wt=new WeakMap,pn=new WeakMap,mn=new WeakMap,gn=new WeakMap,Mc=new WeakMap,Wt=new WeakMap,Hs=new WeakMap,ht=new WeakMap,qs=new WeakMap,Ot=new WeakMap,Rr=new WeakSet,Rn=function(){return this.context.getValue("connectionHandler")},Su=new WeakSet,uT=async function(s,t,e,r){var n;g(this,Ac,s);let i=!1;if(e){const{recv:o,send:c}=(n=a(this,Rr,Rn).mediaState)!=null?n:{};(c==null?void 0:c.state)===Hr.CONNECTED&&(o==null?void 0:o.state)===Hr.CONNECTED?(this.logger.info("MediaNodeClient.joinRoom: transports healthy — preserving producers until replacements are created"),await this.closePreReconnectProducers(),a(this,H).producers.forEach(l=>{var f,S;const u=D(f=HS,bu,fT).call(f,l),h=(S=a(this,qs).get(u))!=null?S:[];h.push(l),a(this,qs).set(u,h)}),a(this,H).producers.clear(),a(this,ht).clear(),a(this,Hs).clear(),g(this,Wt,null),i=!0):(this.logger.info("MediaNodeClient.joinRoom: transports unhealthy — full reset"),this.reset({resetTransportQueue:!1}))}try{a(this,Wt)?await a(this,Wt):await D(this,Oc,qp).call(this,s,t,e,r,i),D(this,Tu,pT).call(this,t);const{joined:o,error:c}=await D(this,vu,hT).call(this);return{roomJoined:o,error:c}}catch(o){return this.logger.error("Failed to complete room join",{error:o}),{roomJoined:!1,error:o}}finally{g(this,Wt,null)}},vu=new WeakSet,hT=async function(){try{this.mediaJoined=!0;const{roomState:s}=await a(this,H).socketHandler.notifySelfJoinComplete();return g(this,Ic,s.roomUuid),g(this,mn,!0),g(this,pn,!1),{joined:!0}}catch(s){return this.logger.error("Error completing room join",{error:s}),this.mediaJoined=!1,{joined:!1,error:s}}},Tu=new WeakSet,pT=function(s){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:s,roomViewType:"groupCall",deviceInfo:{...Ee.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(e)}catch(t){this.logger.error("Error reporting room joined analytics",{error:t})}},0)},Oc=new WeakSet,qp=async function(s,t,e,r,i=!1){try{const n=D(this,yu,mT).call(this);await D(this,Eu,gT).call(this,s,t,e,n),i?this.logger.info("MediaNodeClient: reusing existing transports on rejoin"):await a(this,H).setupTransports({send:!0,recv:!0})}catch(n){throw this.logger.error("Failed to initialize connection",{error:n}),n}},yu=new WeakSet,mT=function(){const s=P1("video/VP8");return g(this,fu,s),s},Eu=new WeakSet,gT=async function(s,t,e,r){await LS(async(i,n)=>{if(!a(this,ut).isConnected){n(new Error("Socket is not connected"));return}i>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${i}`});try{await a(this,H).socketHandler.joinRoom(t,s,r,e)}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}},{delayTime:1e3,strategy:"exponential",maxRetryCount:15})},bu=new WeakSet,fT=function(s){const t=s.appData.screenShare===!0;return s.kind==="audio"?t?ce.SCREENSHARE_AUDIO:ce.MIC:t?ce.SCREENSHARE_VIDEO:ce.WEBCAM},Pt=new WeakSet,Qt=function(s){return a(this,ht).get(s)},fn=new WeakSet,hd=function(s,t){return a(this,ht).set(s,t)},wu=new WeakSet,ST=function(s){return a(this,ht).delete(s)},Sn=new WeakSet,pd=async function(s){var e;const t=(e=a(this,qs).get(s))!=null?e:[];a(this,qs).delete(s),await a(this,H).closeProducersLocally(t)},Pu=new WeakSet,vT=function(s){return{track:s,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},_u=new WeakSet,TT=function(s){return{track:s,codecOptions:[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},m(wp,bu),wp);let ae=HS;de([y.trace("MediaNodeClient.reset")],ae.prototype,"reset",1),de([y.trace("MediaNodeClient.joinRoom")],ae.prototype,"joinRoom",1),de([y.trace("MediaNodeClient.leaveRoom")],ae.prototype,"leaveRoom",1),de([y.trace("MediaNodeClient.activatePeers")],ae.prototype,"activatePeers",1),de([y.trace("MediaNodeClient.createConsumers")],ae.prototype,"createConsumers",1),de([y.trace("MediaNodeClient.closeConsumers")],ae.prototype,"closeConsumers",1),de([y.trace("MediaNodeClient.closeConsumersById")],ae.prototype,"closeConsumersById",1),de([y.trace("MediaNodeClient._shareWebcam")],ae.prototype,"_shareWebcam",1),de([y.trace("MediaNodeClient.shareWebcam")],ae.prototype,"shareWebcam",1),de([y.trace("MediaNodeClient.shareScreen")],ae.prototype,"shareScreen",1),de([y.trace("MediaNodeClient.shareMic")],ae.prototype,"shareMic",1),de([y.trace("MediaNodeClient.pauseMic")],ae.prototype,"pauseMic",1),de([y.trace("MediaNodeClient.pauseWebcam")],ae.prototype,"pauseWebcam",1),de([y.trace("MediaNodeClient.resumeMic")],ae.prototype,"resumeMic",1),de([y.trace("MediaNodeClient.resumeWebcam")],ae.prototype,"resumeWebcam",1),de([y.trace("MediaNodeClient.disableWebcam")],ae.prototype,"disableWebcam",1),de([y.trace("MediaNodeClient.disableMic")],ae.prototype,"disableMic",1),de([y.trace("MediaNodeClient.disableScreenShare")],ae.prototype,"disableScreenShare",1),de([y.trace("MediaNodeClient.muteSelf")],ae.prototype,"muteSelf",1),de([y.trace("MediaNodeClient.resetVideoProducers")],ae.prototype,"resetVideoProducers",1),de([y.trace("MediaNodeClient.changeDisplayName")],ae.prototype,"changeDisplayName",1),de([y.trace("MediaNodeClient.kickPeer")],ae.prototype,"kick",1),de([y.trace("MediaNodeClient.kickAllPeers")],ae.prototype,"kickAll",1),de([y.trace("MediaNodeClient.muteAll")],ae.prototype,"muteAll",1),de([y.trace("MediaNodeClient.muteAllVideo")],ae.prototype,"muteAllVideo",1),de([y.trace("MediaNodeClient.disableAudio")],ae.prototype,"disableAudio",1),de([y.trace("MediaNodeClient.disableVideo")],ae.prototype,"disableVideo",1),de([y.trace("MediaNodeClient.pinPeer")],ae.prototype,"pinPeer",1),de([y.trace("MediaNodeClient.validateScreenShare")],ae.prototype,"validateScreenShare",1);function qS(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 ae(s,t);return s.setValue("roomNodeClient",r),r}function J1(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 K1=Object.defineProperty,z1=Object.getOwnPropertyDescriptor,Di=(s,t,e,r)=>{for(var i=r>1?void 0:r?z1(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&&K1(t,e,i),i};const jS=(Nv=class{constructor(s,t,e,r){m(this,pt);p(this,"self");p(this,"authToken");m(this,Dc,void 0);p(this,"viewType");m(this,us,void 0);m(this,te,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,g(this,te,s),this.viewType=r,this.authToken=n,g(this,Dc,i),g(this,us,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=xt(),o=!!s.getValue("cachedUserDetails"),c=await We.__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:Ee.getDeviceInfo().engineName,env:s.getValue("env")==="prod"?"prod":"devel",iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:{},logger:d,apiHostnames:yk(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 jS(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,pt,Nt).shareMic(s),this.self.audioEnabled||a(this,pt,Nt).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,pt,Nt).shareWebcam(t),this.self.videoEnabled||a(this,pt,Nt).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,pt,Nt))==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){a(this,te).getValue("callstats").callEnded(),s?(this.logger.info("Resetting Self post reconnect. Peer has earlier tried joining the meeting. State cleanup will be done during room rejoin."),await this.joinRoom(s)):(this.logger.info("Resetting Self post reconnect. User never joined the room so doing full reset."),a(this,pt,Nt).reset({resetTransportQueue:!0}))}setupEvents(){a(this,te).getValue("peerSessionStore").on(_.RESET_PRODUCER_STATE,async()=>{if(this.mediaJoined)try{await this.shareMediaTracks()}finally{await a(this,pt,Nt).closePreReconnectProducers()}}),a(this,te).getValue("peerSessionStore").on(_.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,te).getValue("peerSessionStore").on(_.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,te).getValue("peerSessionStore").on(_.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(_.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(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(_.SOCKET_SERVICE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,te).getValue("peerSessionStore").on(_.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,us).on($.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,us).on(tl.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,te).getValue("peerSessionStore").emit(_.UPDATE_PERMISSIONS,t.patch)})}),a(this,us).on($.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,us).on($.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,us).on($.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,te).getValue("peerSessionStore").onAsync(_.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,te).getValue("peerSessionStore").on(_.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(_.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,te).getValue("callstats").audioOff())}),a(this,te).getValue("peerSessionStore").on(_.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,te).getValue("callstats").videoOff())}),a(this,te).getValue("peerSessionStore").onAsync(_.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,te).getValue("peerSessionStore").on(_.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{this.logger.info("Joining socket room.");const{peer:t}=await a(this,us).joinRoom(this.self);this.logger.info("Joined socket room."),a(this,us).socket.flush();const e=Hh(t.stageType);if(a(this,te).setValue("stageStatus",e,!1),t.waitlisted){this.logger.info("Peer was waitlisted. Skipped joining media room."),this.waitlistedHandler();return}}catch(t){throw this.logger.error("SelfController.joinRoom: socket join failed",{error:t}),new P("Check the network and try again.","0002")}try{this.logger.info("Joining media room."),await this.joinMediaRoom(s),this.logger.info("Joined media room."),a(this,te).notify("stageStatus")}catch(t){throw this.logger.error("SelfController.joinRoom: media room join failed",{error:t}),t instanceof Fr&&t.message==="ice connection failed"?new P("A firewall or network restriction may be blocking the connection.","0014"):new P("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,us).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===Qs.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}qS(a(this,te),{socket:a(this,Dc),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u,error:h}=(o=await((n=a(this,pt,Nt))==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(),await a(this,pt,Nt).closePreReconnectProducers(),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===Qs.Webinar)&&a(this,pt,Nt)&&(a(this,pt,Nt).mediaJoined&&s!=="disconnected"&&await a(this,pt,Nt).leaveRoom(),!(s==="stageLeft"&&t===Qs.Livestream)&&(a(this,pt,Nt).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()}},Dc=new WeakMap,us=new WeakMap,te=new WeakMap,pt=new WeakSet,Nt=function(){return a(this,te).getValue("roomNodeClient")},Nv);let qr=jS;Di([y.trace("SelfController.resetSelf")],qr.prototype,"resetSelf",1),Di([y.trace("SelfController.setupEvents")],qr.prototype,"setupEvents",1),Di([y.trace("SelfController.joinRoom")],qr.prototype,"joinRoom",1),Di([y.trace("SelfController.leaveRoom")],qr.prototype,"leaveRoom",1),Di([y.trace("SelfController.joinMediaRoom")],qr.prototype,"joinMediaRoom",1),Di([y.trace("SelfController.leaveMediaRoom")],qr.prototype,"leaveMediaRoom",1),Di([y.trace("SelfController.init")],qr,"init",1);class Y1{constructor(t){m(this,Nc,void 0);g(this,Nc,t)}on(t,e){let r;t===$.roomPeerCount?r=Vf.fromBinary.bind(Vf):r=Yf.fromBinary.bind(Yf),a(this,Nc).on(t,({payload:i})=>{if(t===$.roomPeerCount&&!i)return;const n=r(i);e(n)})}}Nc=new WeakMap;class Q1{constructor(t,e){m(this,Lc,void 0);m(this,Vc,void 0);g(this,Lc,e),g(this,Vc,t)}get logger(){return a(this,Vc).getValue("logger")}on(t,e){let r,i;switch(t){case $.transcript:{r=_h.fromBinary.bind(_h),i=_h.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Lc).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)})}}Lc=new WeakMap,Vc=new WeakMap;var X1=Object.defineProperty,Z1=Object.getOwnPropertyDescriptor,up=(s,t,e,r)=>{for(var i=r>1?void 0:r?Z1(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&&X1(t,e,i),i};class Sl{constructor(t,e){m(this,Ir,void 0);m(this,ja,void 0);g(this,Ir,e),g(this,ja,t)}get logger(){return a(this,ja).getValue("logger")}get telemetry(){return a(this,ja).getValue("telemetry")}getPolls(){return a(this,Ir).sendMessagePromise(rr.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Ir).sendMessage(rr.createPoll,YM.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Ir).sendMessage(rr.votePoll,XM.toBinary(r))}on(t,e){let r,i;switch(t){case rr.updatePoll:case rr.createPoll:case rr.votePoll:{r=xh.fromBinary.bind(xh),i=xh.create();break}}a(this,Ir).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,Ir).removeListeners(t)}}Ir=new WeakMap,ja=new WeakMap,up([y.trace("PollSocketHandler.getPolls")],Sl.prototype,"getPolls",1),up([y.trace("PollSocketHandler.createPoll")],Sl.prototype,"createPoll",1),up([y.trace("PollSocketHandler.votePoll")],Sl.prototype,"votePoll",1);var eN=Object.defineProperty,tN=Object.getOwnPropertyDescriptor,sN=(s,t,e,r)=>{for(var i=r>1?void 0:r?tN(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 GS{constructor(t,e){p(this,"socket");m(this,Jt,void 0);g(this,Jt,t),this.socket=e,this.handleSocketEvents(),a(this,Jt).setValue("roomSocketHandler",this)}get telemetry(){return a(this,Jt).getValue("telemetry")}get logger(){return a(this,Jt).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($.joinRoom,YI.toBinary(e));try{const{peer:n}=Vn.fromBinary((await r).payload);a(this,Jt).getValue("connectionHandler").socketJoined=!0,a(this,Jt).getValue("peerSessionStore").emit(_.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,Jt).getValue("peerSessionStore").emit(_.ROOM_STATE,d),a(this,Jt).getValue("peerSessionStore").emit(_.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),n}}async getAllAddedParticipants(){try{return N0.fromBinary((await this.socket.sendMessagePromise($.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($.getRoomPeersInfo,BI.toBinary(n));i=Rh.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($.getRoomPeersInfo);t=Rh.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($.getRoomPeersInfo);t=Rh.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($.getPeerInfo,$f.toBinary({peerId:t}));e=Vn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=Uf.create();try{const e=await this.socket.sendMessagePromise($.getRoomInfo);t=Uf.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=Gf.create();try{const e=await this.socket.sendMessagePromise($.getRoomStageState);t=Gf.fromBinary(e.payload)}catch(e){this.logger.error("getRoomStageState::binary_decode_error",{error:e})}return t}async broadcastMessage(t,e){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise($.broadcastMessage,ho.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($.broadcastToEntity,ho.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($.broadcastToEntity,ho.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($.leaveRoom,XI.toBinary(e))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage($.kick,qf.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage($.kickAll,Rf.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage($.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage($.acceptWaitingRoomRequests,B0.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage($.denyWaitingRoomRequests,H0.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(tl.updateUserPreset,SA.toBinary(r))}handleSocketEvents(){this.socket.on($.broadcastMessage,({payload:t})=>{try{const e=ho.fromBinary(t);a(this,Jt).getValue("peerSessionStore").emit(_.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($.broadcastToEntity,({payload:t})=>{try{const e=ho.fromBinary(t);a(this,Jt).getValue("peerSessionStore").emit(_.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 $.joinRoom:case $.leaveRoom:case $.kick:case $.kickAll:{r=Vn.fromBinary.bind(Vn),i=Vn.create();break}case $.getWaitingRoomRequests:{r=(n,o)=>n?jf.fromBinary(n,o):{requests:[]},i=jf.create();break}case $.recordingPaused:case $.recordingStarted:case $.recordingStopped:{r=eS.fromBinary.bind(eS);break}case tl.updateUserPreset:{r=Jf.fromBinary.bind(Jf);break}case fs.peerJoinedBroadcast:case Vr.peerJoinedBroadcast:{r=Mf.fromBinary.bind(Mf);break}case fs.selfJoinComplete:case Vr.selfJoinComplete:{r=wh.fromBinary.bind(wh);break}case fs.globalPeerPinBroadcast:case Vr.globalPeerPinBroadcast:{r=Nf.fromBinary.bind(Nf);break}case fs.selectedPeer:case Vr.selectedPeer:{r=bh.fromBinary.bind(bh);break}case fs.selectedPeerDiff:case Vr.selectedPeerDiff:{r=Af.fromBinary.bind(Af);break}case fs.leaveRoom:case Vr.leaveRoom:{r=Ph.fromBinary.bind(Ph);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(tl.getUserPresets,lA.toBinary(e)),i=mA.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}}}Jt=new WeakMap,sN([y.trace("RoomSocketHandler.joinRoom")],GS.prototype,"joinRoom",1);class rN{constructor(t){m(this,Dt,void 0);g(this,Dt,t)}async getStageRequests(){const{payload:t}=await a(this,Dt).sendMessagePromise($.getStageRequests);return t?Vh.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,Dt).sendMessage($.requestStageAccess)}cancelRequestAccess(){a(this,Dt).sendMessage($.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,Dt).sendMessage($.grantStageAccess,BM.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,Dt).sendMessage($.denyStageAccess,HM.toBinary(e))}joinStage(){return a(this,Dt).sendMessagePromise($.joinStage,void 0,void 0,$.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,Dt).sendMessagePromise($.leaveStage,Xf.toBinary(e),void 0,$.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,Dt).sendMessagePromise($.leaveStage,Xf.toBinary(e))}on(t,e){let r;switch(t){case $.grantStageAccess:case $.denyStageAccess:{r=void 0;break}case $.getStagePeers:{r=Qf.fromBinary.bind(Qf);break}case $.getStageRequests:case $.requestStageAccess:case $.cancelStageRequest:{r=Vh.fromBinary.bind(Vh);break}case $.peerStageStatusUpdate:{r=Lf.fromBinary.bind(Lf);break}}a(this,Dt).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,Dt).sendMessagePromise($.getPeerInfo,$f.toBinary({peerId:t}));return Vn.fromBinary(e.payload)}}Dt=new WeakMap;class iN{constructor(t,e){m(this,hi,void 0);m(this,Ga,void 0);g(this,hi,e),g(this,Ga,t)}get logger(){return a(this,Ga).getValue("logger")}get peerId(){return a(this,Ga).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,hi).sendMessage(sr.storeInsertKeys,yM.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,hi).sendMessage(sr.storeGetKeys,bM.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,hi).sendMessage(sr.storeDeleteKeys,PM.toBinary(n),i)}on(t,e){const r=zf.fromBinary.bind(zf);a(this,hi).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}hi=new WeakMap,Ga=new WeakMap;var nN=Object.defineProperty,aN=(s,t,e)=>t in s?nN(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,oN=(s,t,e)=>(aN(s,typeof t!="symbol"?t+"":t,e),e),hp=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},M=(s,t,e)=>(hp(s,t,"read from private field"),e?e.call(s):t.get(s)),he=(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)},ne=(s,t,e,r)=>(hp(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),oe=(s,t,e)=>(hp(s,t,"access private method"),e),vl={},cN={get exports(){return vl},set exports(s){vl=s}},Hn=typeof Reflect=="object"?Reflect:null,WS=Hn&&typeof Hn.apply=="function"?Hn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},Tl;Hn&&typeof Hn.ownKeys=="function"?Tl=Hn.ownKeys:Object.getOwnPropertySymbols?Tl=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:Tl=function(s){return Object.getOwnPropertyNames(s)};function dN(s){console&&console.warn&&console.warn(s)}var JS=Number.isNaN||function(s){return s!==s};function pe(){pe.init.call(this)}cN.exports=pe,vl.once=pN,pe.EventEmitter=pe,pe.prototype._events=void 0,pe.prototype._eventsCount=0,pe.prototype._maxListeners=void 0;var KS=10;function yl(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(pe,"defaultMaxListeners",{enumerable:!0,get:function(){return KS},set:function(s){if(typeof s!="number"||s<0||JS(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");KS=s}}),pe.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},pe.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||JS(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 zS(s){return s._maxListeners===void 0?pe.defaultMaxListeners:s._maxListeners}pe.prototype.getMaxListeners=function(){return zS(this)},pe.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")WS(c,this,t);else for(var d=c.length,l=ev(c,d),e=0;e<d;++e)WS(l[e],this,t);return!0};function YS(s,t,e,r){var i,n,o;if(yl(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=zS(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,dN(c)}return s}pe.prototype.addListener=function(s,t){return YS(this,s,t,!1)},pe.prototype.on=pe.prototype.addListener,pe.prototype.prependListener=function(s,t){return YS(this,s,t,!0)};function lN(){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 QS(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=lN.bind(r);return i.listener=e,r.wrapFn=i,i}pe.prototype.once=function(s,t){return yl(t),this.on(s,QS(this,s,t)),this},pe.prototype.prependOnceListener=function(s,t){return yl(t),this.prependListener(s,QS(this,s,t)),this},pe.prototype.removeListener=function(s,t){var e,r,i,n,o;if(yl(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},pe.prototype.off=pe.prototype.removeListener,pe.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 XS(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):ev(i,i.length)}pe.prototype.listeners=function(s){return XS(this,s,!0)},pe.prototype.rawListeners=function(s){return XS(this,s,!1)},pe.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):ZS.call(s,t)},pe.prototype.listenerCount=ZS;function ZS(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}pe.prototype.eventNames=function(){return this._eventsCount>0?Tl(this._events):[]};function ev(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 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 pN(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))}tv(s,t,n,{once:!0}),t!=="error"&&mN(s,i,{once:!0})})}function mN(s,t,e){typeof s.on=="function"&&tv(s,"error",t,e)}function tv(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 v{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 sv=new gN;class rv{static encode(t){return sv.toBinary(t)}static decode(t){return sv.fromBinary(new Uint8Array(t))}}function fN(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var jr;class SN{constructor(t={}){oN(this,"opts"),he(this,jr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ne(this,jr,0)}async wait(){ne(this,jr,M(this,jr)+1);const t=fN(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**M(this,jr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return M(this,jr)}reset(){ne(this,jr,0)}}jr=new WeakMap;const Gr={debug:0,info:1,warn:2,error:3};var Ni,Li;class vN{constructor(t){he(this,Ni,void 0),he(this,Li,void 0),ne(this,Ni,console),ne(this,Li,t)}debug(...t){Gr[M(this,Li)]>Gr.debug||M(this,Ni).debug("[Sockrates]:",...t)}info(...t){Gr[M(this,Li)]>Gr.info||M(this,Ni).info("[Sockrates]:",...t)}warn(...t){Gr[M(this,Li)]>Gr.warn||M(this,Ni).warn("[Sockrates]:",...t)}error(...t){Gr[M(this,Li)]>Gr.error||M(this,Ni).error("[Sockrates]:",...t)}}Ni=new WeakMap,Li=new WeakMap;var iv=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(iv||{});const nv="2",av="3";var Me,qn,me,Ie,Wr,Je,dr,Jr,vs,jn,Gn,lr,pp,ov,_o,El,mp,cv,bl,gp,wl,fp,Sp,dv,ko,Pl,Wn,Co,_l,vp,Jn,Ro,Tp,lv,Io,kl,Ao,Cl;class TN{constructor(t,e){var E,C,I,R,U,N,x,B,q,Z,se,at;he(this,pp),he(this,_o),he(this,mp),he(this,bl),he(this,wl),he(this,Sp),he(this,ko),he(this,Wn),he(this,_l),he(this,Jn),he(this,Tp),he(this,Io),he(this,Ao),he(this,Me,void 0),he(this,qn,void 0),he(this,me,void 0),he(this,Ie,void 0),he(this,Wr,void 0),he(this,Je,void 0),he(this,dr,void 0),he(this,Jr,void 0),he(this,vs,void 0),he(this,jn,void 0),he(this,Gn,void 0),he(this,lr,void 0);var r,i,n,o,c,d,l,u,h,f,S;ne(this,qn,t),ne(this,Wr,[]),ne(this,Je,new vl),ne(this,dr,!0),ne(this,vs,!1),ne(this,me,e!=null?e:{}),(E=(r=M(this,me)).autoReconnect)!=null||(r.autoReconnect=!0),(C=(i=M(this,me)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(I=(n=M(this,me)).pingTimeout)!=null||(n.pingTimeout=3e4),(R=(o=M(this,me)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(U=(c=M(this,me)).debug)!=null||(c.debug=!0),(N=(d=M(this,me)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(x=(l=M(this,me)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(B=(u=M(this,me)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(q=(h=M(this,me)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),(Z=(f=M(this,me)).clientInitiatedPings)!=null||(f.clientInitiatedPings=!1),(se=(S=M(this,me)).clientInitiatedPingInterval)!=null||(S.clientInitiatedPingInterval=3e4),ne(this,Jr,{code:void 0,reason:void 0}),ne(this,Ie,(at=M(this,me).logger)!=null?at:new vN(M(this,me).debug?"debug":"info")),ne(this,lr,new SN)}get readyState(){var t;return(t=M(this,Me))==null?void 0:t.readyState}get url(){return M(this,qn)}updateURL(t){ne(this,qn,t),oe(this,Sp,dv).call(this)}get config(){return M(this,me)}get sendQueue(){return M(this,Wr)}flush(){if(!M(this,me).queueOnDisconnect)return!1;const t=[];return M(this,Wr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ne(this,Wr,t),M(this,Wr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){M(this,Ie).debug("Websocket was already connecting or connected.");return}if(M(this,dr)!==!1)return new Promise((e,r)=>{oe(this,Jn,Ro).call(this),oe(this,Ao,Cl).call(this);try{ne(this,Me,new WebSocket(oe(this,pp,ov).call(this,M(this,qn)))),M(this,Me).binaryType="arraybuffer",M(this,Ie).debug("Connecting");const i=setTimeout(()=>{M(this,Ie).debug("Connection timeout. Closing socket"),ne(this,dr,!0),oe(this,Ao,Cl).call(this),M(this,Me).close(3001,"Connection Timeout"),M(this,me).autoReconnect&&!M(this,vs)&&(M(this,Je).emit("reconnecting"),oe(this,ko,Pl).call(this)),r(new Error("Connection timed out!"))},M(this,me).connectionTimeout);M(this,Me).onopen=()=>{M(this,Ie).debug(`Ready State: ${iv[M(this,Me).readyState]}`),i&&clearTimeout(i),oe(this,_l,vp).call(this),oe(this,Tp,lv).call(this),ne(this,Jr,{code:void 0,reason:void 0}),M(this,Je).emit("connected"),M(this,me).flushOnReconnect&&this.flush(),e()},M(this,Me).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),M(this,Ie).debug("Socket closed. Close event:",{event:n}),M(this,Ie).debug(`Connection closed code: ${o}`),M(this,Ie).debug(`Connection closed reason: ${c}`),M(this,vs)||oe(this,wl,fp).call(this,o,c)}catch(o){oe(this,_o,El).call(this,o)}},M(this,Me).onerror=n=>{oe(this,_o,El).call(this,n)},M(this,Me).onmessage=n=>oe(this,mp,cv).call(this,n)}catch(i){oe(this,_o,El).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(M(this,me).queueOnDisconnect&&(!M(this,Me)||M(this,Me).readyState!==1))return M(this,Ie).debug("Queuing message since socket is not connected!",n),M(this,Wr).push(n),!1;const o=rv.encode(n);return oe(this,Wn,Co).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return oe(this,Wn,Co).call(this,t)}receive(t,e){return M(this,Je).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,Je).on(t,e);return}this.receive(t,e)}removeAllListeners(){M(this,Je).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){M(this,Je).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){M(this,Je).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ne(this,dr,!1),oe(this,Jn,Ro).call(this),oe(this,Io,kl).call(this),this.removeAllListeners(),ne(this,Jr,{code:1e3,reason:"Sockrates disconnect method called"}),M(this,Me).close(1e3,"Sockrates disconnect method called.")}}Me=new WeakMap,qn=new WeakMap,me=new WeakMap,Ie=new WeakMap,Wr=new WeakMap,Je=new WeakMap,dr=new WeakMap,Jr=new WeakMap,vs=new WeakMap,jn=new WeakMap,Gn=new WeakMap,lr=new WeakMap,pp=new WeakSet,ov=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)://.")},_o=new WeakSet,El=function(s,t){M(this,Ie).error("Error:",{error:s}),M(this,Je).emit("errored",{error:s}),t==null||t(s)},mp=new WeakSet,cv=function(s){if(oe(this,_l,vp).call(this),s.data===nv){M(this,Ie).debug("Received ping from server"),oe(this,Wn,Co).call(this,av);return}if(s.data===av){M(this,Ie).debug("Received pong from server");return}const t=rv.decode(s.data),{id:e,payload:r}=t;M(this,Ie).debug("Received message",{event:t.event,messageID:e}),M(this,Je).emit(t.event.toString(),{id:e,payload:r})},bl=new WeakSet,gp=function(){return M(this,Me).readyState===1},wl=new WeakSet,fp=function(s,t){ne(this,Jr,{reason:t,code:s}),M(this,Je).emit("disconnected",{code:s,reason:t})},Sp=new WeakSet,dv=function(){const{reason:s,code:t}=M(this,Jr);t&&t!==1e3&&M(this,dr)&&M(this,me).autoReconnect&&!M(this,vs)&&(M(this,Ie).debug(`Triggering reconnection due to ${s}.`),M(this,Je).emit("reconnecting"),oe(this,ko,Pl).call(this))},ko=new WeakSet,Pl=async function(s=!0){if(s&&M(this,vs)){M(this,Ie).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(M(this,vs)||M(this,lr).reset(),M(this,me).maxReconnectionAttempts!==null&&M(this,lr).getAttempts()>=M(this,me).maxReconnectionAttempts){M(this,Je).emit("failed"),ne(this,vs,!1);return}ne(this,vs,!0),oe(this,Ao,Cl).call(this),oe(this,Jn,Ro).call(this);try{if(await M(this,lr).wait(),M(this,dr)===!1)return;if(M(this,Ie).debug(`Reconnection attempt ${M(this,lr).getAttempts()}`),M(this,Je).emit("reconnectAttempt",{attempt:M(this,lr).getAttempts()}),await this.connect(),!oe(this,bl,gp).call(this))throw Error("Reconnect Failed");ne(this,vs,!1),ne(this,Jr,{code:void 0,reason:void 0}),M(this,Je).emit("reconnected")}catch(t){M(this,Ie).debug("Failed to reconnect."),M(this,Je).emit("reconnectFailure",{attempt:M(this,lr).getAttempts()}),oe(this,ko,Pl).call(this,!1)}},Wn=new WeakSet,Co=function(s){try{return M(this,Me).send(s),!0}catch(t){return M(this,Ie).error(t.message),!1}},_l=new WeakSet,vp=function(){this.config.disconnectOnPingTimeout&&(M(this,Ie).debug("Resetting ping timeout"),oe(this,Jn,Ro).call(this),ne(this,jn,setTimeout(()=>{var s;M(this,Ie).debug("Disconnecting the socket due to ping timeout"),ne(this,dr,!0);const t=3002,e="Ping timeout";(s=M(this,Me))==null||s.close(t,e),oe(this,wl,fp).call(this,t,e)},M(this,me).pingTimeout)))},Jn=new WeakSet,Ro=function(){M(this,jn)&&(clearTimeout(M(this,jn)),ne(this,jn,void 0))},Tp=new WeakSet,lv=function(){oe(this,Io,kl).call(this),M(this,me).clientInitiatedPings&&ne(this,Gn,setInterval(()=>{oe(this,bl,gp).call(this)&&(M(this,Ie).debug("Sending client-initiated ping"),oe(this,Wn,Co).call(this,nv))},M(this,me).clientInitiatedPingInterval))},Io=new WeakSet,kl=function(){M(this,Gn)&&(clearInterval(M(this,Gn)),ne(this,Gn,void 0))},Ao=new WeakSet,Cl=function(){oe(this,Io,kl).call(this),M(this,Me)&&(M(this,Me).onopen=void 0,M(this,Me).onerror=void 0,M(this,Me).onmessage=void 0,M(this,Me).onclose=void 0)};function uv(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://docs.realtime.cloudflare.com/api#/operations/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=Pi.baseURI.prod;t&&(n=t);const o=`https://${xd({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new P("Invalid auth token","0004")}}var EN=Object.defineProperty,bN=Object.getOwnPropertyDescriptor,Rl=(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};const hv=65535,wN=3,PN=15e3,_N=8e3,kN=50,CN=1e3,RN=1e4,pv=(Pp=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){m(this,tt);m(this,xc);m(this,ku);m(this,Cu);m(this,Ru);m(this,Uc);m(this,$c);m(this,bn);m(this,Au);m(this,Bc);m(this,Fc);m(this,Hc);m(this,Mu);m(this,qc);m(this,jc);m(this,js,void 0);m(this,Wa,void 0);m(this,_e,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");m(this,vn,[]);m(this,pi,void 0);m(this,Tn,!1);m(this,yn,void 0);m(this,mi,void 0);m(this,Gs,void 0);m(this,Ws,void 0);m(this,gi,void 0);m(this,En,void 0);m(this,_t,0);m(this,fi,void 0);m(this,kt,!0);m(this,qe,void 0);if(!t||!e||!r)throw new P("peerId, meetingId, or authToken can not be empty","0404");g(this,qe,s),g(this,Ws,navigator.isReactNative?FS:Jh),this.capabilities=i,this.roomName=e,this.authToken=r,g(this,js,D(this,xc,jp).call(this,t)),g(this,Wa,t);const n=i.includes("PING");g(this,_e,new TN(a(this,js),{autoReconnect:!1,disconnectOnPingTimeout:n,queueOnDisconnect:!1,flushOnReconnect:!1,logger:this.logger,clientInitiatedPings:!n,clientInitiatedPingInterval:15e3})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,tt,gt).socketJoinAttempted}set joinAttempted(s){a(this,tt,gt).socketJoinAttempted=s}get telemetry(){return a(this,qe).getValue("telemetry")}get logger(){return a(this,qe).getValue("logger")}get peerId(){return a(this,qe).getValue("peerId")}updateCallstatsPeerId(s){const t=a(this,qe).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;g(this,js,D(this,xc,jp).call(this,s)),g(this,Wa,s),a(this,qe).getValue("telemetry").resetPeerId(s),(t=a(this,qe).getValue("apiClient"))==null||t.setHeader("tracing-id",s),this.updateCallstatsPeerId(s),Dr.remapContext(s,a(this,qe)),this.logger.info(`Attempting websocket connection with URL: ${a(this,bn,md)}`),a(this,_e).updateURL(a(this,js))}get url(){return a(this,js)}async connect(){var t;const s=a(this,_t)+1;g(this,_t,s),D(this,Bc,Jp).call(this),a(this,tt,gt).socketJoinAttempted=!0,g(this,kt,!0),D(this,Ru,bT).call(this);try{if(await a(this,_e).connect(),!a(this,kt)||s!==a(this,_t))throw new Error("Socket connection was canceled");D(this,$c,Wp).call(this,this.peerId),(t=a(this,Gs))!=null||g(this,Gs,this.peerId),a(this,tt,gt).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}catch(e){throw this.logger.error(`Websocket connection failed with URL: ${a(this,bn,md)}`,{error:e}),a(this,kt)&&s===a(this,_t)&&D(this,Hc,zp).call(this,s),e}}disconnect(){a(this,tt,gt).socketJoinAttempted=!1,g(this,_t,a(this,_t)+1),g(this,kt,!1),D(this,Bc,Jp).call(this),D(this,Uc,Gp).call(this),g(this,Gs,void 0),a(this,_e).disconnect(),a(this,tt,gt).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,_e).readyState===1}catch(s){return!1}}sendMessage(s,t,e){if(!a(this,qc,Yp))return!1;const r={};return a(this,qe).getValue("telemetry").injectContext(r),a(this,_e).send(s,e!=null?e:D(this,jc,Qp).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,qc,Yp))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,R)=>{d&&clearTimeout(d),a(this,_e).removeListener(n,I),a(this,_e).removeListener(hv,R),a(this,_e).removeListener(Vr.errorResponse,R),a(this,_e).removeListener(fs.errorResponse,R)},u=r!=null?r:D(this,jc,Qp).call(this),h={};a(this,qe).getValue("telemetry").injectContext(h);const S=({id:I,payload:R})=>{if(u===I){let U;try{const N=DR.fromBinary(R);U=new Error(N.errorMessage)}catch(N){U=new Error("failed to parse error message",{cause:N});try{const x=DI.fromBinary(R);U=new Error(x.message)}catch(x){U=new Error("failed to parse error message",{cause:x})}}c(U),l(E,S)}},E=({id:I,payload:R})=>{u===I&&(o({id:I,payload:R}),l(E,S))};a(this,_e).on(n,E),a(this,_e).on(hv,S),a(this,_e).on(Vr.errorResponse,S),a(this,_e).on(fs.errorResponse,S),d=setTimeout(()=>{l(E,S),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,_e).send(s,u,e,new TextEncoder().encode(JSON.stringify(h)))||(l(E,S),c(new Error("Socket message could not be sent for the current peer ID")))})}on(s,t){a(this,_e).on(s,t)}onStateEvent(s,t){a(this,_e).on(s,t)}removeListener(s,t){a(this,_e).removeListener(s,t)}removeListeners(s){a(this,_e).removeListeners(s)}flush(){return a(this,_e).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{var s;this.logger.info(`Websocket connected with URL: ${a(this,bn,md)}`),(s=a(this,Gs))!=null||g(this,Gs,this.peerId),a(this,tt,gt).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{!a(this,kt)||a(this,fi)===a(this,_t)||(this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t}}),a(this,tt,gt).updateSocketConnectionState("disconnected"),a(this,qe).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,tt,gt).joinAttempted}),D(this,Hc,zp).call(this,a(this,_t)))})}},js=new WeakMap,Wa=new WeakMap,_e=new WeakMap,tt=new WeakSet,gt=function(){return a(this,qe).getValue("connectionHandler")},vn=new WeakMap,pi=new WeakMap,Tn=new WeakMap,yn=new WeakMap,mi=new WeakMap,Gs=new WeakMap,Ws=new WeakMap,gi=new WeakMap,En=new WeakMap,_t=new WeakMap,fi=new WeakMap,kt=new WeakMap,qe=new WeakMap,xc=new WeakSet,jp=function(s){let t=hh({servicePrefix:"ws",baseURI:a(this,qe).getValue("baseURI")});const e=co(a(this,qe),"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,vn).length>0&&{oldPeerIds:a(this,vn).join(",")},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(n=>Yd[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,yT=function(){if(!a(this,Gs))return;const s=new URL(a(this,js));return s.protocol=s.protocol==="ws:"?"http:":"https:",s.pathname=`${s.pathname.replace(/\/+$/,"")}/ping`,s.search="",s.searchParams.set("peerId",a(this,Gs)),s.href},Cu=new WeakSet,ET=async function(){const s=D(this,ku,yT).call(this);if(!s||a(this,Tn))return;const t={},e=typeof AbortController=="function"?new AbortController:void 0;let r;g(this,Tn,!0),g(this,mi,t),g(this,yn,e);try{e&&(r=a(this,Ws).setTimeout(()=>e.abort(),_N));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,mi)===t&&this.logger.warn("SocketService::API ping request failed",{error:i,networkCall:{url:s}})}finally{r!==void 0&&a(this,Ws).clearTimeout(r),a(this,mi)===t&&(g(this,Tn,!1),g(this,mi,void 0),g(this,yn,void 0))}},Ru=new WeakSet,bT=function(){a(this,pi)===void 0&&g(this,pi,a(this,Ws).setInterval(()=>D(this,Cu,ET).call(this),PN))},Uc=new WeakSet,Gp=function(){var s;a(this,pi)!==void 0&&a(this,Ws).clearInterval(a(this,pi)),(s=a(this,yn))==null||s.abort(),g(this,pi,void 0),g(this,Tn,!1),g(this,mi,void 0),g(this,yn,void 0)},$c=new WeakSet,Wp=function(s){g(this,vn,[s,...a(this,vn).filter(t=>t!==s)].slice(0,wN))},bn=new WeakSet,md=function(){const s=new URL(a(this,js)),t=s.searchParams.get("authToken");return t&&s.searchParams.set("authToken",uv(t)),s.href},Iu=new WeakSet,wT=function(s){const t=Math.min(RN,CN*2**(s-1));return Math.floor(Math.random()*(t+1))},Au=new WeakSet,PT=function(s){return new Promise(t=>{var e;g(this,En,t),g(this,gi,a(this,Ws).setTimeout(()=>{g(this,gi,void 0),g(this,En,void 0),t()},D(e=pv,Iu,wT).call(e,s)))})},Bc=new WeakSet,Jp=function(){var s;a(this,gi)!==void 0&&(a(this,Ws).clearTimeout(a(this,gi)),g(this,gi,void 0)),(s=a(this,En))==null||s.call(this),g(this,En,void 0)},Fc=new WeakSet,Kp=function(s,t){!a(this,kt)||s!==a(this,_t)||(t&&this.logger.error("SocketService::Reconnect loop failed",{error:t}),g(this,kt,!1),D(this,Uc,Gp).call(this),g(this,Gs,void 0),a(this,tt,gt).updateSocketConnectionState("failed"),a(this,qe).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_FAILED))},Hc=new WeakSet,zp=function(s){!a(this,kt)||a(this,fi)===s||(g(this,fi,s),a(this,tt,gt).updateSocketConnectionState("reconnecting"),D(this,Mu,_T).call(this,s).catch(t=>D(this,Fc,Kp).call(this,s,t)))},Mu=new WeakSet,_T=async function(s){try{for(let t=1;t<=kN;t+=1){if(!a(this,kt)||s!==a(this,_t)||(await D(this,Au,PT).call(this,t),!a(this,kt)||s!==a(this,_t)))return;this.updateURL(In()),this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:t}}),a(this,tt,gt).updateSocketConnectionState("reconnectAttempt",t);try{if(await a(this,_e).connect(!0),!a(this,kt)||s!==a(this,_t))return;if(!this.isConnected)throw new Error("Reconnect failed");D(this,$c,Wp).call(this,this.peerId),g(this,Gs,this.peerId),a(this,tt,gt).updateSocketConnectionState("reconnected"),a(this,qe).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,tt,gt).mediaJoinAttempted});return}catch(e){if(!a(this,kt)||s!==a(this,_t))return;this.logger.error(`Websocket connection retry attempt ${t} failed with URL: ${a(this,bn,md)}`,{error:e,socket:{retryAttempt:t}}),a(this,tt,gt).updateSocketConnectionState("reconnectFailure",t)}}D(this,Fc,Kp).call(this,s)}finally{a(this,fi)===s&&g(this,fi,void 0)}},qc=new WeakSet,Yp=function(){return this.isConnected&&a(this,Wa)===this.peerId},jc=new WeakSet,Qp=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},m(Pp,Iu),Pp);let Mo=pv;Rl([y.trace("SocketService.connect")],Mo.prototype,"connect",1),Rl([y.trace("SocketService.disconnect")],Mo.prototype,"disconnect",1),Rl([y.trace("SocketService.sendMessagePromise")],Mo.prototype,"sendMessagePromise",1),Rl([y.trace("SocketService.sendMessagePromiseWithTimeout")],Mo.prototype,"sendMessagePromiseWithTimeout",1);class IN{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=O0.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=Hf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return Ff.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return b0.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise($.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise($.createConnectedRooms,l0.toBinary({payloads:t}));return Ff.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))}async updateConnectedRooms(t){}async disableConnectedRooms(t){const e=t.map(i=>({id:i})),r=await this.socketService.sendMessagePromise($.deleteConnectedRooms,y0.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise($.movePeers,R0.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 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 mv extends Lt{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);m(this,Kt,void 0);g(this,Kt,e)}get isActive(){return this.meetings.length!==0}validateAlterAction(){const e=a(this,Kt).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,Kt).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,Kt).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,Kt).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,Kt).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)}`),await a(this,Kt).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title}))),this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`)}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,Kt).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,Kt).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,Kt).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})}}Kt=new WeakMap,ON([Ut({maxInvocations:60,period:60})],mv.prototype,"getConnectedMeetings",1);var DN=Object.defineProperty,NN=Object.getOwnPropertyDescriptor,yp=(s,t,e,r)=>{for(var i=r>1?void 0:r?NN(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&&DN(t,e,i),i};const gv=(Lv=class{constructor(s){p(this,"connectedMeetings");m(this,ye,void 0);g(this,ye,s),this.connectedMeetings=new mv(s)}get telemetry(){return a(this,ye).getValue("telemetry")}get logger(){return a(this,ye).getValue("logger")}static init(s){const t=new gv(s);return s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings()),t.setupEvents(),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,ye).getValue("connectedMeetingsSocketHandler").socketService.on($.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,ye).getValue("connectedMeetingsSocketHandler").socketService.on($.transferPeer,this.handleTransferPeer.bind(this)),a(this,ye).getValue("connectedMeetingsSocketHandler").socketService.on($.movedPeer,this.handleMovedPeer.bind(this)),a(this,ye).getValue("connectedMeetingsSocketHandler").socketService.on($.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,ye).getValue("connectedMeetingsSocketHandler").socketService.on($.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=a(this,ye).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,ye).getValue("self").videoEnabled,audio:a(this,ye).getValue("self").audioEnabled};try{a(this,ye).getValue("self").cleanupEvents(),await a(this,ye).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,ye).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 Sv.init({...a(this,ye).getValue("options"),cachedUserDetails:null,defaults:{...a(this,ye).getValue("options").defaults,...e,mediaHandler:a(this,ye).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,ye).getValue("self");r.self.setName(a(this,ye).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,ye).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,ye).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=a(this,ye).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(s),e=new Map;this.connectedMeetings.meetings.forEach(r=>{e.set(r.id,r)}),t.forEach(r=>{e.has(r.id)?e.get(r.id).title=r.title:e.set(r.id,{...r,participants:[]})}),this.connectedMeetings.meetings=Array.from(e.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=a(this,ye).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})}},ye=new WeakMap,Lv);let Il=gv;yp([y.trace("ConnectedMeetingsController.getConnectedMeetings")],Il.prototype,"getConnectedMeetings",1),yp([y.trace("ConnectedMeetingsController.setupEvents")],Il.prototype,"setupEvents",1),yp([y.trace("ConnectedMeetingsController.switchMeeting")],Il.prototype,"switchMeeting",1);var LN=Object.defineProperty,VN=Object.getOwnPropertyDescriptor,Ep=(s,t,e,r)=>{for(var i=r>1?void 0:r?VN(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&&LN(t,e,i),i};const Oo=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 N,x;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(J1(s),Ee.isSupported()===!1)throw new P("Browser not supported","0010",c,!0);const d=CO(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 f=Oo.createSocketService(s),S=f.connect();S.catch(()=>{});const E=d.getUserDetails();try{h=await E,u=((N=h.meeting)==null?void 0:N.title)||"",s.setValue("presetName",h.preset.name)}catch(B){throw c.error("Failed to get user details",{error:B}),f.disconnect(),B instanceof sl?B.status===401?new P("Unauthorized. The auth token may be invalid or expired. (401)","0004"):B.status===403?new P("Access denied. Insufficient permissions to join the meeting. (403)","0004"):B.status===404?(c.error("[ERROR:0004] participant-details returned 404."),new P("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")):B.status>=500?new P(`The server encountered an error. Try again. (${B.status})`,"0001"):B.isHttpError?new P(`Request rejected by the server. (${B.status})`,"0001"):B.isTimeout?new P("Connection timed out. Check the network and try again.","0001"):new P("Unable to connect to the server. Check the internet connection.","0001"):new P((B==null?void 0:B.message)||"Failed to initialize.","0001")}try{await S}catch(B){c.error("[Controller]: Failed to connect to socket server:",{error:B})}const C=Xh.init(h.preset,!s.getValue("modules").theme);s.setValue("theme",C);const I=ep.init(s,C.viewType,h.preset.permissions),R=Oo.setupControllers(f,s,h,u,C,I);QO(C)&&((x=Oo.createRoomNodeClient(s,f).initializeConnection(h.participant.name,i,!1,I))==null||x.catch(q=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:q})}));const{controllers:U}=await R;return Fk(),new Oo(e,U,s)}static async setupControllers(s,t,e,r,i,n){var Le,V,k;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:(Le=h.enableHighBitrate)!=null?Le:!1,enableStereo:(V=h.enableStereo)!=null?V:!1}},...d}),t.setValue("maxPreferredStreams",Ee.isMobile()?i.maxVideoStreams.mobile:i.maxVideoStreams.desktop);let f,S,E,C,I,R,U,N,x;const B=new Q1(t,s),q=new IN(s);t.setValue("connectedMeetingsSocketHandler",q);const Z=new Sl(t,s),se=new ir(t,s),at=new rN(s),Ct=new GS(t,s),zt=new iN(t,s),A=new Y1(s),T=await qr.init(t,Ct,c,n,i);t.setValue("selfController",T);const w=await dS.init(t,T.self,Ct,B,r);o.participant&&(N=new cr(t,T.self,Ct)),(k=o.e2ee)!=null&&k.enabled&&o.e2ee.manager.init(l,t.getValue("peerSessionStore")),o.chat&&(S=await mo.init(t,se,T.self,N.participants)),o.internals&&(I=await Wh.init(t)),o.livestream&&i.viewType===Qs.Livestream&&(U=new AS(t,T.self,A)),o.poll&&(f=await nS.init(t,T.self,Z)),o.recording&&(R=new fS(t,T.self,Ct)),o.stage&&(E=new lS(t,at,Ct,T.self,N.participants));const F=new o1(t,zt);if(o.plugin){if(!N)throw new P("The plugin module cannot be initialized without the `participant` module","0102");const Be=d.plugins||[];C=await mS.init(t,Be,T.self,F)}if(o.connectedMeetings&&(x=await Il.init(t)),o.pip){const Be=await gh._init(t,T.self);t.setValue("pip",Be)}return{theme:i,permissions:n,controllers:{storesManager:F,pollController:f,selfController:T,metaController:w,chatController:S,stageController:E,pluginController:C,recordingController:R,internalsController:I,livestreamController:U,participantController:N,connectedMeetingsController:x}}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return qS(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=[];return s.getValue("logger").info(`Socket service capabilities: ${JSON.stringify(i)}`),new Mo(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Al=Oo;Ep([y.trace("Controller.init")],Al,"init",1),Ep([y.trace("Controller.createRoomNodeClient")],Al,"createRoomNodeClient",1),Ep([y.trace("Controller.createSocketService")],Al,"createSocketService",1);class xN{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 fv=new xN;class UN{constructor(){m(this,Ou);m(this,Si,new Audio);m(this,wn,new MediaStream);m(this,Pn,new Map);m(this,Gc,void 0);a(this,Si).srcObject=a(this,wn),a(this,Si).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,Pn).has(e.id)||(a(this,wn).addTrack(e),a(this,Pn).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,Si).setSinkId(t)}removeTrack(t){const e=a(this,Pn).get(t);e&&(a(this,wn).removeTrack(e),a(this,Pn).delete(t))}async play(){return a(this,Si).srcObject=a(this,wn),a(this,Si).play().catch(t=>{D(this,Ou,kT).call(this,t)})}onError(t){g(this,Gc,t)}}Si=new WeakMap,wn=new WeakMap,Pn=new WeakMap,Gc=new WeakMap,Ou=new WeakSet,kT=function(t){var e;(e=a(this,Gc))==null||e.call(this,t)};class $N extends UN{constructor(){super();m(this,_n,void 0);g(this,_n,new Map)}addParticipantTrack(e,r){a(this,_n).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,_n).get(e);r&&this.removeTrack(r),a(this,_n).delete(e)}}_n=new WeakMap;var BN=Object.defineProperty,FN=Object.getOwnPropertyDescriptor,Ml=(s,t,e,r)=>{for(var i=r>1?void 0:r?FN(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};let Kr=(Vv=class{constructor(t,e){m(this,Fe,void 0);m(this,kn,void 0);g(this,kn,t),g(this,Fe,e)}get peerId(){return a(this,kn).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:In(),n=Dr.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new DS(n,o);return await c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var f,S,E,C,I,R,U;Ee.init();const e=(S=(f=t==null?void 0:t.cachedUserDetails)==null?void 0:f.peerId)!=null?S:In(),{authToken:r,baseURI:i}=t,{meetingId:n,...o}=yN(r,i);if((E=o.baseURI)!=null&&E.includes("dyte.io"))throw new P("Dyte Base URIs are no longer supported. Use RealtimeKit Base URIs.","0001");window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=Kr.setupContext(e,t,n,o),d=c.getValue("telemetry"),l=c.getValue("logger");AT(l),fv.init(l),d.init(c,{roomName:n,userId:o.participantId,organizationId:o.orgId,peerId:e},(I=(C=t.modules)==null?void 0:C.tracing)!=null?I:!0,(U=(R=t==null?void 0:t.modules)==null?void 0:R.devTools)==null?void 0:U.logLevel),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:uv(t.authToken)}});const u=await Al.init(c),h=new Kr(c,u);return c.setValue("meeting",h),h}static setupContext(t,e,r,i){var d,l;const n=Dr.createContext(t,e),o={...vk,...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",Tk({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Ms(e.cachedUserDetails)),n.setValue("sdkVersion","2.0.3-staging.7"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new $N),n}async join(){const{selfController:t}=a(this,Fe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){var r;fv.cleanup(),a(this,kn).getValue("peerSessionStore").reset(),(r=a(this,Fe).pluginController)==null||r.cleanup();const{selfController:e}=a(this,Fe);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,Fe).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,Fe).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,Fe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,Fe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,Fe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,Fe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,Fe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Fe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,Fe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,Fe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,Fe).stageController)==null?void 0:t.stage}get stores(){return a(this,Fe).storesManager}get audio(){return a(this,kn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,Fe).internalsController)==null?void 0:t.internals}},Fe=new WeakMap,kn=new WeakMap,Vv);Ml([ct("0002"),ar.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Kr.prototype,"join",1),Ml([ct("0003")],Kr.prototype,"leave",1),Ml([ct("0001"),ar.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Kr,"init",1),Kr=Ml([ct("0000")],Kr);const Sv=Kr;return Sv}();
|