@cloudflare/realtimekit 1.3.0 → 1.4.0-staging.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/EncryptionManager.cjs.js +1 -1
- package/dist/EncryptionManager.d.ts +7 -15
- package/dist/EncryptionManager.es.js +224 -224
- package/dist/browser.js +13 -13
- package/dist/dependencies.txt +1 -1
- package/dist/index.cjs.js +10 -10
- package/dist/index.d.ts +7 -15
- package/dist/index.es.js +4189 -4243
- package/dist/index.es5.js +4953 -5014
- package/dist/index.rn.js +11 -11
- package/dist/ts3.4/dist/EncryptionManager.d.ts +7 -15
- package/dist/ts3.4/dist/index.d.ts +7 -15
- package/package.json +2 -3
package/dist/browser.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
var RealtimeKitClient=function(){var BS,No,pr,gr,os,xi,pt,cs,Ne,Cs,mr,bt,Fe,Jn,Kn,fr,zn,Jt,Yn,te,Ui,tt,Qn,wl,ov,Vo,ap,HS,Fi,qS,bl,cv,Pl,dv,Xn,Zn,Lo,jS,Yr,ea,$i,GS,ta,xo,op,Bi,Uo,WS,Fo,JS,Qr,sa,Kt,KS,ds,_l,ne,$o,js,st,Bo,cp,ra,mu,Xr,ks,Zr,Ho,Pt,gt,zt,ia,na,Sr,aa,ei,oa,zS,$e,Hi,ls,ca,Is,YS,qo,da,la,ua,fu,QS,qi,ji,Ke,Ee,fe,vr,us,jo,Ve,Gi,Go,Wi,ti,ha,hs,Be,XS,Ji,Wo,pa,Jo,_t,Ki,Ko,ga,fa,zo,Sa,va,Tr,Gs,mt,si,ri,Rl,lv,zi,Yi,Yo,dp,Qo,ii,Cl,uv,Ta,ya,Yt,Qi,Zc,ni,Ya,Xi,ed,kl,hv,yr,Xo,ai,Zi,td,Er,Il,Zo,lp,Al,pv,Ml,gv,ZS,oi,Re,ec,up,en,sd,Ea,Su,tn,Vt,ev,ps,As,wa,tv,q,ba,Pa,Ol,Rt,es,Qt,Ra,Ct,Ca,We,wr,Rn,ze,ct,ka,vu,He,Xe,Ia,Aa,tc,hp,sv,sc,rt,rc,ic,sn,Ws,Dl,Js,mi,nc,pp,Nl,mv,Vl,fv,Ms,Ma,Oa,rn,gs,nt,ci,Da,Ll,Xt,Fs,di,xl,nn,an,br,on,La,ft,St,ac,oc,cn,xa,cc,Ua,dn,Ks,Fa,Tu,dc,gp,Ul,Sv,lc,mp,Fl,vv,$l,Tv,Bl,yv,Hl,Ev,ql,wv,uc,fp,hc,Sp,jl,ms,ln,li,$a,pc,zs,Gl,Pr,Ba,gc,vp,Wl,bv,Jl,Pv,Kl,_v,zl,Rv,mc,fc,Sc,Ha,qa,ja,vc,Tc,Ga,Lt,Os,Ds,un,hn,_r,yc,Yl,Cv,Ql,kv,Xl,Iv,Zl,Av,Ec,wc,Rr,Cr,Ns,bc,pn,Wa,kr,ui,Ja,Ir,Ar,Ys,tu,Mv,Pc,Tp,su,Ov,ru,Dv,Rc,Cc,vt,j,Ka,kt,gn,mn,fn,kc,fs,Mr,Ic,Sn,vn,It,xt,hi,Qa,iu,Nv,nu,Vv,au,Lv,Ac,yp,ou,rp,xv,cu,Uv,du,Fv,lu,$v,at,Mt,Tn,rd,uu,Bv,hu,Hv,pu,qv,yn,Vs,X,At,ts,rv,Mc,Oc,Dc,Or,za,Zt,Ut,Ye,Nc,pi,Ae,Me,je,Ss,ot,Vc,Ep,Lc,wp,iv,Ls,Se,nv,gi,En,wn,xc,gu,jv,bn,Qe,Pn,av;"use strict";var fN=Object.defineProperty;var SN=(ke,we,Ie)=>we in ke?fN(ke,we,{enumerable:!0,configurable:!0,writable:!0,value:Ie}):ke[we]=Ie;var p=(ke,we,Ie)=>(SN(ke,typeof we!="symbol"?we+"":we,Ie),Ie),np=(ke,we,Ie)=>{if(!we.has(ke))throw TypeError("Cannot "+Ie)};var a=(ke,we,Ie)=>(np(ke,we,"read from private field"),Ie?Ie.call(ke):we.get(ke)),m=(ke,we,Ie)=>{if(we.has(ke))throw TypeError("Cannot add the same private member more than once");we instanceof WeakSet?we.add(ke):we.set(ke,Ie)},f=(ke,we,Ie,id)=>(np(ke,we,"write to private field"),id?id.call(ke,Ie):we.set(ke,Ie),Ie);var x=(ke,we,Ie)=>(np(ke,we,"access private method"),Ie);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 Ie,id=new Uint8Array(16);function Gv(){if(!Ie&&(Ie=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!Ie))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Ie(id)}const Wv=/^(?:[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 yu(s){return typeof s=="string"&&Wv.test(s)}for(var it=[],Eu=0;Eu<256;++Eu)it.push((Eu+256).toString(16).substr(1));function Jv(s){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(it[s[t+0]]+it[s[t+1]]+it[s[t+2]]+it[s[t+3]]+"-"+it[s[t+4]]+it[s[t+5]]+"-"+it[s[t+6]]+it[s[t+7]]+"-"+it[s[t+8]]+it[s[t+9]]+"-"+it[s[t+10]]+it[s[t+11]]+it[s[t+12]]+it[s[t+13]]+it[s[t+14]]+it[s[t+15]]).toLowerCase();if(!yu(e))throw TypeError("Stringified UUID is invalid");return e}function fi(s,t,e){s=s||{};var r=s.random||(s.rng||Gv)();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 Jv(r)}const Kv=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")}))},zv={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},bp={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},Le={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},yt={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},Nr={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};class M{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(r=>parseInt(r,10)||0);if(e.push(0),e[0]===10)switch(e[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}}static getAndroidVersionName(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=M.getVersionPrecision(t),n=M.getVersionPrecision(e);let o=Math.max(i,n),c=0;const d=M.map([t,e],l=>{const u=o-M.getVersionPrecision(l),h=l+new Array(u+1).join(".0");return M.map(h.split("."),g=>new Array(20-g.length).join("0")+g).reverse()});for(r&&(c=o-Math.min(i,n)),o-=1;o>=c;){if(d[0][o]>d[1][o])return 1;if(d[0][o]===d[1][o]){if(o===c)return 0;o-=1}else if(d[0][o]<d[1][o])return-1}}static map(t,e){const r=[];let i;if(Array.prototype.map)return Array.prototype.map.call(t,e);for(i=0;i<t.length;i+=1)r.push(e(t[i]));return r}static find(t,e){let r,i;if(Array.prototype.find)return Array.prototype.find.call(t,e);for(r=0,i=t.length;r<i;r+=1){const n=t[r];if(e(n,r))return n}}static assign(t,...e){const r=t;let i,n;if(Object.assign)return Object.assign(t,...e);for(i=0,n=e.length;i<n;i+=1){const o=e[i];typeof o=="object"&&o!==null&&Object.keys(o).forEach(d=>{r[d]=o[d]})}return t}static getBrowserAlias(t){return zv[t]}static getBrowserTypeByAlias(t){return bp[t]||""}}const le=/version\/(\d+(\.?_?\d+)+)/i,Yv=[{test:[/googlebot/i],describe(s){const t={name:"Googlebot"},e=M.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,s)||M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/opera/i],describe(s){const t={name:"Opera"},e=M.getFirstMatch(le,s)||M.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/opr\/|opios/i],describe(s){const t={name:"Opera"},e=M.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,s)||M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/SamsungBrowser/i],describe(s){const t={name:"Samsung Internet for Android"},e=M.getFirstMatch(le,s)||M.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=M.getFirstMatch(le,s)||M.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/MZBrowser/i],describe(s){const t={name:"MZ Browser"},e=M.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,s)||M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/focus/i],describe(s){const t={name:"Focus"},e=M.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,s)||M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/swing/i],describe(s){const t={name:"Swing"},e=M.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,s)||M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/coast/i],describe(s){const t={name:"Opera Coast"},e=M.getFirstMatch(le,s)||M.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=M.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/yabrowser/i],describe(s){const t={name:"Yandex Browser"},e=M.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/ucbrowser/i],describe(s){const t={name:"UC Browser"},e=M.getFirstMatch(le,s)||M.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/Maxthon|mxios/i],describe(s){const t={name:"Maxthon"},e=M.getFirstMatch(le,s)||M.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/epiphany/i],describe(s){const t={name:"Epiphany"},e=M.getFirstMatch(le,s)||M.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/puffin/i],describe(s){const t={name:"Puffin"},e=M.getFirstMatch(le,s)||M.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/sleipnir/i],describe(s){const t={name:"Sleipnir"},e=M.getFirstMatch(le,s)||M.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=M.getFirstMatch(le,s)||M.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/micromessenger/i],describe(s){const t={name:"WeChat"},e=M.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(le,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=M.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/msie|trident/i],describe(s){const t={name:"Internet Explorer"},e=M.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/\sedg\//i],describe(s){const t={name:"Microsoft Edge"},e=M.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=M.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/vivaldi/i],describe(s){const t={name:"Vivaldi"},e=M.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/seamonkey/i],describe(s){const t={name:"SeaMonkey"},e=M.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/sailfish/i],describe(s){const t={name:"Sailfish"},e=M.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=M.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/phantom/i],describe(s){const t={name:"PhantomJS"},e=M.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/slimerjs/i],describe(s){const t={name:"SlimerJS"},e=M.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=M.getFirstMatch(le,s)||M.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=M.getFirstMatch(le,s)||M.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=M.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/tizen/i],describe(s){const t={name:"Tizen"},e=M.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/qupzilla/i],describe(s){const t={name:"QupZilla"},e=M.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/firefox|iceweasel|fxios/i],describe(s){const t={name:"Firefox"},e=M.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=M.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/MiuiBrowser/i],describe(s){const t={name:"Miui"},e=M.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/chromium/i],describe(s){const t={name:"Chromium"},e=M.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/chrome|crios|crmo/i],describe(s){const t={name:"Chrome"},e=M.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=M.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=M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/playstation 4/i],describe(s){const t={name:"PlayStation 4"},e=M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/safari|applewebkit/i],describe(s){const t={name:"Safari"},e=M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/.*/i],describe(s){const t=/^(.*)\/(.*) /,e=/^(.*)\/(.*)[ \t]\((.*)/,i=s.search("\\(")!==-1?e:t;return{name:M.getFirstMatch(i,s),version:M.getSecondMatch(i,s)}}}],Qv=[{test:[/Roku\/DVP/],describe(s){const t=M.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,s);return{name:yt.Roku,version:t}}},{test:[/windows phone/i],describe(s){const t=M.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,s);return{name:yt.WindowsPhone,version:t}}},{test:[/windows /i],describe(s){const t=M.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,s),e=M.getWindowsVersionName(t);return{name:yt.Windows,version:t,versionName:e}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(s){const t={name:yt.iOS},e=M.getSecondMatch(/(Version\/)(\d[\d.]+)/,s);return e&&(t.version=e),t}},{test:[/macintosh/i],describe(s){const t=M.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,s).replace(/[_\s]/g,"."),e=M.getMacOSVersionName(t),r={name:yt.MacOS,version:t};return e&&(r.versionName=e),r}},{test:[/(ipod|iphone|ipad)/i],describe(s){const t=M.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,s).replace(/[_\s]/g,".");return{name:yt.iOS,version:t}}},{test(s){const t=!s.test(/like android/i),e=s.test(/android/i);return t&&e},describe(s){const t=M.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,s),e=M.getAndroidVersionName(t),r={name:yt.Android,version:t};return e&&(r.versionName=e),r}},{test:[/(web|hpw)[o0]s/i],describe(s){const t=M.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,s),e={name:yt.WebOS};return t&&t.length&&(e.version=t),e}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(s){const t=M.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,s)||M.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,s)||M.getFirstMatch(/\bbb(\d+)/i,s);return{name:yt.BlackBerry,version:t}}},{test:[/bada/i],describe(s){const t=M.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,s);return{name:yt.Bada,version:t}}},{test:[/tizen/i],describe(s){const t=M.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,s);return{name:yt.Tizen,version:t}}},{test:[/linux/i],describe(){return{name:yt.Linux}}},{test:[/CrOS/],describe(){return{name:yt.ChromeOS}}},{test:[/PlayStation 4/],describe(s){const t=M.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,s);return{name:yt.PlayStation4,version:t}}}],Xv=[{test:[/googlebot/i],describe(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe(s){const t=M.getFirstMatch(/(can-l01)/i,s)&&"Nova",e={type:Le.mobile,vendor:"Huawei"};return t&&(e.model=t),e}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe(){return{type:Le.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe(){return{type:Le.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(){return{type:Le.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe(){return{type:Le.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe(){return{type:Le.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe(){return{type:Le.tablet}}},{test(s){const t=s.test(/ipod|iphone/i),e=s.test(/like (ipod|iphone)/i);return t&&!e},describe(s){const t=M.getFirstMatch(/(ipod|iphone)/i,s);return{type:Le.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe(){return{type:Le.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe(){return{type:Le.mobile}}},{test(s){return s.getBrowserName(!0)==="blackberry"},describe(){return{type:Le.mobile,vendor:"BlackBerry"}}},{test(s){return s.getBrowserName(!0)==="bada"},describe(){return{type:Le.mobile}}},{test(s){return s.getBrowserName()==="windows phone"},describe(){return{type:Le.mobile,vendor:"Microsoft"}}},{test(s){const t=Number(String(s.getOSVersion()).split(".")[0]);return s.getOSName(!0)==="android"&&t>=3},describe(){return{type:Le.tablet}}},{test(s){return s.getOSName(!0)==="android"},describe(){return{type:Le.mobile}}},{test(s){return s.getOSName(!0)==="macos"},describe(){return{type:Le.desktop,vendor:"Apple"}}},{test(s){return s.getOSName(!0)==="windows"},describe(){return{type:Le.desktop}}},{test(s){return s.getOSName(!0)==="linux"},describe(){return{type:Le.desktop}}},{test(s){return s.getOSName(!0)==="playstation 4"},describe(){return{type:Le.tv}}},{test(s){return s.getOSName(!0)==="roku"},describe(){return{type:Le.tv}}}],Zv=[{test(s){return s.getBrowserName(!0)==="microsoft edge"},describe(s){if(/\sedg\//i.test(s))return{name:Nr.Blink};const e=M.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,s);return{name:Nr.EdgeHTML,version:e}}},{test:[/trident/i],describe(s){const t={name:Nr.Trident},e=M.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test(s){return s.test(/presto/i)},describe(s){const t={name:Nr.Presto},e=M.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:Nr.Gecko},e=M.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:Nr.Blink}}},{test:[/(apple)?webkit/i],describe(s){const t={name:Nr.WebKit},e=M.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}}];class Pp{constructor(t,e=!1){if(t==null||t==="")throw new Error("UserAgent parameter can't be empty");this._ua=t,this.parsedResult={},e!==!0&&this.parse()}getUA(){return this._ua}test(t){return t.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const t=M.find(Yv,e=>{if(typeof e.test=="function")return e.test(this);if(e.test instanceof Array)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.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=M.find(Qv,e=>{if(typeof e.test=="function")return e.test(this);if(e.test instanceof Array)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=M.find(Xv,e=>{if(typeof e.test=="function")return e.test(this);if(e.test instanceof Array)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=M.find(Zv,e=>{if(typeof e.test=="function")return e.test(this);if(e.test instanceof Array)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 M.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=M.find(c,u=>this.isOS(u));if(d){const u=this.satisfies(e[d]);if(u!==void 0)return u}const l=M.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=M.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=M.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(M.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 NS,No,pr,gr,ns,xi,pt,as,Ne,_s,mr,wt,Fe,Jn,Kn,fr,zn,Wt,Yn,te,Ui,tt,Qn,El,ev,Vo,tp,VS,Fi,LS,bl,tv,wl,sv,Xn,Zn,Lo,xS,Yr,ea,$i,US,ta,xo,sp,Bi,Uo,FS,Fo,$S,Qr,sa,Jt,BS,os,Pl,ae,$o,js,st,Bo,rp,ra,pu,Xr,Rs,Zr,Ho,Pt,gt,Kt,ia,na,Sr,aa,ei,oa,HS,$e,Hi,cs,ca,Cs,qS,qo,da,la,ua,gu,jS,qi,ji,Ke,Ee,fe,vr,ds,jo,Ve,Gi,Go,Wi,ti,ha,ls,Be,GS,Ji,Wo,pa,Jo,_t,Ki,Ko,ga,fa,zo,Sa,va,Tr,Gs,mt,si,ri,_l,rv,zi,Yi,Yo,ip,Qo,ii,Rl,iv,Ta,ya,zt,Qi,Xc,ni,Ya,Xi,Zc,Cl,nv,yr,Xo,ai,Zi,ed,Er,kl,Zo,np,Il,av,Al,ov,WS,oi,Re,ec,ap,en,td,Ea,mu,tn,Vt,JS,us,ks,ba,KS,q,wa,Pa,Ml,Rt,Zt,Yt,Ra,Ct,Ca,We,br,Rn,ze,dt,ka,fu,He,Xe,Ia,Aa,tc,op,zS,sc,rt,rc,ic,sn,Ws,Ol,Js,mi,nc,cp,Dl,cv,Nl,dv,Is,Ma,Oa,rn,hs,ot,ci,Da,Vl,Qt,xs,di,Ll,nn,an,wr,on,La,ft,St,ac,oc,cn,xa,cc,Ua,dn,Ks,Fa,Su,dc,dp,xl,lv,lc,lp,Ul,uv,Fl,hv,$l,pv,Bl,gv,Hl,mv,uc,up,hc,hp,ql,ps,ln,li,$a,pc,zs,jl,Pr,Ba,gc,pp,Gl,fv,Wl,Sv,Jl,vv,Kl,Tv,mc,fc,Sc,Ha,qa,ja,vc,Tc,Ga,Lt,As,Ms,un,hn,_r,yc,zl,yv,Yl,Ev,Ql,bv,Xl,wv,Ec,bc,Rr,Cr,Os,wc,pn,Wa,kr,ui,Ja,Ir,Ar,Ys,eu,Pv,Pc,gp,tu,_v,su,Rv,Rc,Cc,vt,j,Ka,kt,gn,mn,fn,kc,gs,Mr,Sn,vn,It,xt,hi,Qa,ru,Cv,iu,kv,nu,Iv,Ic,mp,au,Av,ou,Mv,cu,Ov,ct,Mt,Tn,sd,du,Dv,lu,Nv,uu,Vv,yn,Ds,X,At,es,YS,Ac,Mc,Oc,Or,za,Xt,Ut,Ye,Dc,pi,Ae,Me,je,ms,it,Nc,fp,Vc,Sp,QS,Ns,Se,XS,gi,En,bn,Lc,hu,Lv,wn,Qe,Pn,ZS;"use strict";var lN=Object.defineProperty;var uN=(ke,be,Ie)=>be in ke?lN(ke,be,{enumerable:!0,configurable:!0,writable:!0,value:Ie}):ke[be]=Ie;var p=(ke,be,Ie)=>(uN(ke,typeof be!="symbol"?be+"":be,Ie),Ie),ep=(ke,be,Ie)=>{if(!be.has(ke))throw TypeError("Cannot "+Ie)};var a=(ke,be,Ie)=>(ep(ke,be,"read from private field"),Ie?Ie.call(ke):be.get(ke)),m=(ke,be,Ie)=>{if(be.has(ke))throw TypeError("Cannot add the same private member more than once");be instanceof WeakSet?be.add(ke):be.set(ke,Ie)},f=(ke,be,Ie,rd)=>(ep(ke,be,"write to private field"),rd?rd.call(ke,Ie):be.set(ke,Ie),Ie);var x=(ke,be,Ie)=>(ep(ke,be,"access private method"),Ie);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 be(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:be});var Ie,rd=new Uint8Array(16);function xv(){if(!Ie&&(Ie=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!Ie))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Ie(rd)}const Uv=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function vu(s){return typeof s=="string"&&Uv.test(s)}for(var at=[],Tu=0;Tu<256;++Tu)at.push((Tu+256).toString(16).substr(1));function Fv(s){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(at[s[t+0]]+at[s[t+1]]+at[s[t+2]]+at[s[t+3]]+"-"+at[s[t+4]]+at[s[t+5]]+"-"+at[s[t+6]]+at[s[t+7]]+"-"+at[s[t+8]]+at[s[t+9]]+"-"+at[s[t+10]]+at[s[t+11]]+at[s[t+12]]+at[s[t+13]]+at[s[t+14]]+at[s[t+15]]).toLowerCase();if(!vu(e))throw TypeError("Stringified UUID is invalid");return e}function fi(s,t,e){s=s||{};var r=s.random||(s.rng||xv)();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 Fv(r)}const $v=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")}))},Bv={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},vp={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},Le={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},Tt={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},Nr={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};class M{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(r=>parseInt(r,10)||0);if(e.push(0),e[0]===10)switch(e[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}}static getAndroidVersionName(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=M.getVersionPrecision(t),n=M.getVersionPrecision(e);let o=Math.max(i,n),c=0;const d=M.map([t,e],l=>{const u=o-M.getVersionPrecision(l),h=l+new Array(u+1).join(".0");return M.map(h.split("."),g=>new Array(20-g.length).join("0")+g).reverse()});for(r&&(c=o-Math.min(i,n)),o-=1;o>=c;){if(d[0][o]>d[1][o])return 1;if(d[0][o]===d[1][o]){if(o===c)return 0;o-=1}else if(d[0][o]<d[1][o])return-1}}static map(t,e){const r=[];let i;if(Array.prototype.map)return Array.prototype.map.call(t,e);for(i=0;i<t.length;i+=1)r.push(e(t[i]));return r}static find(t,e){let r,i;if(Array.prototype.find)return Array.prototype.find.call(t,e);for(r=0,i=t.length;r<i;r+=1){const n=t[r];if(e(n,r))return n}}static assign(t,...e){const r=t;let i,n;if(Object.assign)return Object.assign(t,...e);for(i=0,n=e.length;i<n;i+=1){const o=e[i];typeof o=="object"&&o!==null&&Object.keys(o).forEach(d=>{r[d]=o[d]})}return t}static getBrowserAlias(t){return Bv[t]}static getBrowserTypeByAlias(t){return vp[t]||""}}const le=/version\/(\d+(\.?_?\d+)+)/i,Hv=[{test:[/googlebot/i],describe(s){const t={name:"Googlebot"},e=M.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,s)||M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/opera/i],describe(s){const t={name:"Opera"},e=M.getFirstMatch(le,s)||M.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/opr\/|opios/i],describe(s){const t={name:"Opera"},e=M.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,s)||M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/SamsungBrowser/i],describe(s){const t={name:"Samsung Internet for Android"},e=M.getFirstMatch(le,s)||M.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=M.getFirstMatch(le,s)||M.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/MZBrowser/i],describe(s){const t={name:"MZ Browser"},e=M.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,s)||M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/focus/i],describe(s){const t={name:"Focus"},e=M.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,s)||M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/swing/i],describe(s){const t={name:"Swing"},e=M.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,s)||M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/coast/i],describe(s){const t={name:"Opera Coast"},e=M.getFirstMatch(le,s)||M.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=M.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/yabrowser/i],describe(s){const t={name:"Yandex Browser"},e=M.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/ucbrowser/i],describe(s){const t={name:"UC Browser"},e=M.getFirstMatch(le,s)||M.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/Maxthon|mxios/i],describe(s){const t={name:"Maxthon"},e=M.getFirstMatch(le,s)||M.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/epiphany/i],describe(s){const t={name:"Epiphany"},e=M.getFirstMatch(le,s)||M.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/puffin/i],describe(s){const t={name:"Puffin"},e=M.getFirstMatch(le,s)||M.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/sleipnir/i],describe(s){const t={name:"Sleipnir"},e=M.getFirstMatch(le,s)||M.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=M.getFirstMatch(le,s)||M.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/micromessenger/i],describe(s){const t={name:"WeChat"},e=M.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(le,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=M.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/msie|trident/i],describe(s){const t={name:"Internet Explorer"},e=M.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/\sedg\//i],describe(s){const t={name:"Microsoft Edge"},e=M.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=M.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/vivaldi/i],describe(s){const t={name:"Vivaldi"},e=M.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/seamonkey/i],describe(s){const t={name:"SeaMonkey"},e=M.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/sailfish/i],describe(s){const t={name:"Sailfish"},e=M.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=M.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/phantom/i],describe(s){const t={name:"PhantomJS"},e=M.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/slimerjs/i],describe(s){const t={name:"SlimerJS"},e=M.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=M.getFirstMatch(le,s)||M.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=M.getFirstMatch(le,s)||M.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=M.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/tizen/i],describe(s){const t={name:"Tizen"},e=M.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/qupzilla/i],describe(s){const t={name:"QupZilla"},e=M.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/firefox|iceweasel|fxios/i],describe(s){const t={name:"Firefox"},e=M.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=M.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/MiuiBrowser/i],describe(s){const t={name:"Miui"},e=M.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/chromium/i],describe(s){const t={name:"Chromium"},e=M.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/chrome|crios|crmo/i],describe(s){const t={name:"Chrome"},e=M.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=M.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=M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/playstation 4/i],describe(s){const t={name:"PlayStation 4"},e=M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/safari|applewebkit/i],describe(s){const t={name:"Safari"},e=M.getFirstMatch(le,s);return e&&(t.version=e),t}},{test:[/.*/i],describe(s){const t=/^(.*)\/(.*) /,e=/^(.*)\/(.*)[ \t]\((.*)/,i=s.search("\\(")!==-1?e:t;return{name:M.getFirstMatch(i,s),version:M.getSecondMatch(i,s)}}}],qv=[{test:[/Roku\/DVP/],describe(s){const t=M.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,s);return{name:Tt.Roku,version:t}}},{test:[/windows phone/i],describe(s){const t=M.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,s);return{name:Tt.WindowsPhone,version:t}}},{test:[/windows /i],describe(s){const t=M.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,s),e=M.getWindowsVersionName(t);return{name:Tt.Windows,version:t,versionName:e}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(s){const t={name:Tt.iOS},e=M.getSecondMatch(/(Version\/)(\d[\d.]+)/,s);return e&&(t.version=e),t}},{test:[/macintosh/i],describe(s){const t=M.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,s).replace(/[_\s]/g,"."),e=M.getMacOSVersionName(t),r={name:Tt.MacOS,version:t};return e&&(r.versionName=e),r}},{test:[/(ipod|iphone|ipad)/i],describe(s){const t=M.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,s).replace(/[_\s]/g,".");return{name:Tt.iOS,version:t}}},{test(s){const t=!s.test(/like android/i),e=s.test(/android/i);return t&&e},describe(s){const t=M.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,s),e=M.getAndroidVersionName(t),r={name:Tt.Android,version:t};return e&&(r.versionName=e),r}},{test:[/(web|hpw)[o0]s/i],describe(s){const t=M.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,s),e={name:Tt.WebOS};return t&&t.length&&(e.version=t),e}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(s){const t=M.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,s)||M.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,s)||M.getFirstMatch(/\bbb(\d+)/i,s);return{name:Tt.BlackBerry,version:t}}},{test:[/bada/i],describe(s){const t=M.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,s);return{name:Tt.Bada,version:t}}},{test:[/tizen/i],describe(s){const t=M.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,s);return{name:Tt.Tizen,version:t}}},{test:[/linux/i],describe(){return{name:Tt.Linux}}},{test:[/CrOS/],describe(){return{name:Tt.ChromeOS}}},{test:[/PlayStation 4/],describe(s){const t=M.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,s);return{name:Tt.PlayStation4,version:t}}}],jv=[{test:[/googlebot/i],describe(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe(s){const t=M.getFirstMatch(/(can-l01)/i,s)&&"Nova",e={type:Le.mobile,vendor:"Huawei"};return t&&(e.model=t),e}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe(){return{type:Le.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe(){return{type:Le.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(){return{type:Le.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe(){return{type:Le.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe(){return{type:Le.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe(){return{type:Le.tablet}}},{test(s){const t=s.test(/ipod|iphone/i),e=s.test(/like (ipod|iphone)/i);return t&&!e},describe(s){const t=M.getFirstMatch(/(ipod|iphone)/i,s);return{type:Le.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe(){return{type:Le.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe(){return{type:Le.mobile}}},{test(s){return s.getBrowserName(!0)==="blackberry"},describe(){return{type:Le.mobile,vendor:"BlackBerry"}}},{test(s){return s.getBrowserName(!0)==="bada"},describe(){return{type:Le.mobile}}},{test(s){return s.getBrowserName()==="windows phone"},describe(){return{type:Le.mobile,vendor:"Microsoft"}}},{test(s){const t=Number(String(s.getOSVersion()).split(".")[0]);return s.getOSName(!0)==="android"&&t>=3},describe(){return{type:Le.tablet}}},{test(s){return s.getOSName(!0)==="android"},describe(){return{type:Le.mobile}}},{test(s){return s.getOSName(!0)==="macos"},describe(){return{type:Le.desktop,vendor:"Apple"}}},{test(s){return s.getOSName(!0)==="windows"},describe(){return{type:Le.desktop}}},{test(s){return s.getOSName(!0)==="linux"},describe(){return{type:Le.desktop}}},{test(s){return s.getOSName(!0)==="playstation 4"},describe(){return{type:Le.tv}}},{test(s){return s.getOSName(!0)==="roku"},describe(){return{type:Le.tv}}}],Gv=[{test(s){return s.getBrowserName(!0)==="microsoft edge"},describe(s){if(/\sedg\//i.test(s))return{name:Nr.Blink};const e=M.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,s);return{name:Nr.EdgeHTML,version:e}}},{test:[/trident/i],describe(s){const t={name:Nr.Trident},e=M.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test(s){return s.test(/presto/i)},describe(s){const t={name:Nr.Presto},e=M.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:Nr.Gecko},e=M.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:Nr.Blink}}},{test:[/(apple)?webkit/i],describe(s){const t={name:Nr.WebKit},e=M.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}}];class Tp{constructor(t,e=!1){if(t==null||t==="")throw new Error("UserAgent parameter can't be empty");this._ua=t,this.parsedResult={},e!==!0&&this.parse()}getUA(){return this._ua}test(t){return t.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const t=M.find(Hv,e=>{if(typeof e.test=="function")return e.test(this);if(e.test instanceof Array)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.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=M.find(qv,e=>{if(typeof e.test=="function")return e.test(this);if(e.test instanceof Array)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=M.find(jv,e=>{if(typeof e.test=="function")return e.test(this);if(e.test instanceof Array)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=M.find(Gv,e=>{if(typeof e.test=="function")return e.test(this);if(e.test instanceof Array)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 M.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=M.find(c,u=>this.isOS(u));if(d){const u=this.satisfies(e[d]);if(u!==void 0)return u}const l=M.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=M.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=M.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(M.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/lancedikson/bowser
|
|
4
4
|
* MIT License | (c) Dustin Diaz 2012-2015
|
|
5
5
|
* MIT License | (c) Denis Demchenko 2015-2019
|
|
6
|
-
*/class _p{static getParser(t,e=!1){if(typeof t!="string")throw new Error("UserAgent should be a string");return new Pp(t,e)}static parse(t){return new Pp(t).getResult()}static get BROWSER_MAP(){return bp}static get ENGINE_MAP(){return Nr}static get OS_MAP(){return yt}static get PLATFORMS_MAP(){return Le}}const Xa="chrome",Rp="opera",Cp="firefox",kp="iexplorer",Ip="safari",Ap="nwjs",Mp="electron",Op="react-native",wu="unknown",nd={Chrome:Xa,Chromium:Xa,Opera:Rp,Firefox:Cp,"Internet Explorer":kp,Safari:Ip};function eT(){const{userAgent:s}=navigator,t={name:wu,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=Xa,t.version=e)}else t.name=Xa,t.version=s.match(/Chrome\/([\d.]+)/)[1];return t}function tT(){const{userAgent:s}=navigator;if(s.match(/Electron/)){const t=s.match(/Electron\/([\d.]+)/)[1];return{name:Mp,version:t}}return null}function sT(){const{userAgent:s}=navigator;if(s.match(/JitsiMeetNW/)){const t=s.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:Ap,version:t}}}function rT(){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:Op,version:t}}function iT(s){let t;const e=[rT,tT,sT];for(let i=0;i<e.length;i+=1)if(t=e[i](),t)return t;const r=s.getBrowserName();return r in nd?{name:nd[r],version:s.getBrowserVersion()}:(t=eT(),t||{name:wu,version:void 0})}class nT{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=_p.getParser(navigator.userAgent),typeof t=="undefined"){const i=iT(this._bowser);e=i.name,r=i.version}else t.name in nd?(e=nd[t.name],r=t.version):(e=wu,r=void 0);this._name=e,this._version=r}getName(){return this._name}isChrome(){return this._name===Xa}isOpera(){return this._name===Rp}isFirefox(){return this._name===Cp}isIExplorer(){return this._name===kp}isSafari(){return this._name===Ip}isNWJS(){return this._name===Ap}isElectron(){return this._name===Mp}isReactNative(){return this._name===Op||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 aT extends nT{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 be=new aT;var dt={},oT={get exports(){return dt},set exports(s){dt=s}},Cn=typeof Reflect=="object"?Reflect:null,Dp=Cn&&typeof Cn.apply=="function"?Cn.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},ad;Cn&&typeof Cn.ownKeys=="function"?ad=Cn.ownKeys:Object.getOwnPropertySymbols?ad=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:ad=function(t){return Object.getOwnPropertyNames(t)};function cT(s){console&&console.warn&&console.warn(s)}var Np=Number.isNaN||function(t){return t!==t};function oe(){oe.init.call(this)}oT.exports=oe,dt.once=hT,oe.EventEmitter=oe,oe.prototype._events=void 0,oe.prototype._eventsCount=0,oe.prototype._maxListeners=void 0;var Vp=10;function od(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(oe,"defaultMaxListeners",{enumerable:!0,get:function(){return Vp},set:function(s){if(typeof s!="number"||s<0||Np(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Vp=s}}),oe.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},oe.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Np(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 Lp(s){return s._maxListeners===void 0?oe.defaultMaxListeners:s._maxListeners}oe.prototype.getMaxListeners=function(){return Lp(this)},oe.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")Dp(d,this,e);else for(var l=d.length,u=Bp(d,l),r=0;r<l;++r)Dp(u[r],this,e);return!0};function xp(s,t,e,r){var i,n,o;if(od(e),n=s._events,n===void 0?(n=s._events=Object.create(null),s._eventsCount=0):(n.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),n=s._events),o=n[t]),o===void 0)o=n[t]=e,++s._eventsCount;else if(typeof o=="function"?o=n[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=Lp(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,cT(c)}return s}oe.prototype.addListener=function(t,e){return xp(this,t,e,!1)},oe.prototype.on=oe.prototype.addListener,oe.prototype.prependListener=function(t,e){return xp(this,t,e,!0)};function dT(){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 Up(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=dT.bind(r);return i.listener=e,r.wrapFn=i,i}oe.prototype.once=function(t,e){return od(e),this.on(t,Up(this,t,e)),this},oe.prototype.prependOnceListener=function(t,e){return od(e),this.prependListener(t,Up(this,t,e)),this},oe.prototype.removeListener=function(t,e){var r,i,n,o,c;if(od(e),i=this._events,i===void 0)return this;if(r=i[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete i[t],i.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(n=-1,o=r.length-1;o>=0;o--)if(r[o]===e||r[o].listener===e){c=r[o].listener,n=o;break}if(n<0)return this;n===0?r.shift():lT(r,n),r.length===1&&(i[t]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",t,c||e)}return this},oe.prototype.off=oe.prototype.removeListener,oe.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 Fp(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):Bp(i,i.length)}oe.prototype.listeners=function(t){return Fp(this,t,!0)},oe.prototype.rawListeners=function(t){return Fp(this,t,!1)},oe.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):$p.call(s,t)},oe.prototype.listenerCount=$p;function $p(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}oe.prototype.eventNames=function(){return this._eventsCount>0?ad(this._events):[]};function Bp(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function lT(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 hT(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))}Hp(s,t,n,{once:!0}),t!=="error"&&pT(s,i,{once:!0})})}function pT(s,t,e){typeof s.on=="function"&&Hp(s,"error",t,e)}function Hp(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 K;(function(s){s[s.MAJOR_EVENT=0]="MAJOR_EVENT",s[s.MINOR_EVENT=1]="MINOR_EVENT"})(K||(K={}));var N;(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"})(N||(N={}));const gT=new Map([[N.PRECALL_TEST_BEGIN,K.MINOR_EVENT],[N.PRECALL_TEST_COMPLETE,K.MINOR_EVENT],[N.CALL_JOIN_BEGIN,K.MAJOR_EVENT],[N.NET_QUALITY_TEST_BEGIN,K.MINOR_EVENT],[N.NET_QUALITY_TEST_END,K.MINOR_EVENT],[N.WEBSOCKET_CONNECTED,K.MINOR_EVENT],[N.TRANSPORT_CONNECTED,K.MAJOR_EVENT],[N.AUDIO_ON,K.MINOR_EVENT],[N.AUDIO_OFF,K.MINOR_EVENT],[N.VIDEO_ON,K.MINOR_EVENT],[N.VIDEO_OFF,K.MINOR_EVENT],[N.PARTICIPANT_ROLE,K.MINOR_EVENT],[N.PING_STAT,K.MAJOR_EVENT],[N.DISCONNECT,K.MAJOR_EVENT],[N.RECONNECT_ATTEMPT,K.MAJOR_EVENT],[N.SCREENSHARE_START_REQUESTED,K.MINOR_EVENT],[N.SCREENSHARE_STARTED,K.MINOR_EVENT],[N.SCREENSHARE_STOPPED,K.MINOR_EVENT],[N.TAB_CHANGE,K.MINOR_EVENT],[N.BROWSER_BACKGROUNDED,K.MINOR_EVENT],[N.BROWSER_FOREGROUNDED,K.MINOR_EVENT],[N.DOMINANT_SPEAKER,K.MINOR_EVENT],[N.AUDIO_DEVICES_UPDATES,K.MINOR_EVENT],[N.VIDEO_DEVICES_UPDATES,K.MINOR_EVENT],[N.SPEAKER_DEVICES_UPDATES,K.MINOR_EVENT],[N.SELECTED_MICROHPONE_UPDATE,K.MINOR_EVENT],[N.SELECTED_CAMERA_UPDATE,K.MINOR_EVENT],[N.SELECTED_SPEAKER_UPDATE,K.MINOR_EVENT],[N.MEDIA_PERMISSION,K.MINOR_EVENT],[N.LEGACY_SWITCH,K.MINOR_EVENT],[N.AUDIO_PLAY_FAILED,K.MINOR_EVENT],[N.VIDEO_PLAY_FAILED,K.MINOR_EVENT],[N.AUDIO_TRACK_MUTED,K.MINOR_EVENT],[N.VIDEO_TRACK_MUTED,K.MINOR_EVENT],[N.IVS_PLAYER_REBUFFERING,K.MAJOR_EVENT],[N.IVS_PLAYER_AUDIO_BLOCKED,K.MAJOR_EVENT],[N.IVS_PLAYER_PLAYBACK_BLOCKED,K.MAJOR_EVENT],[N.IVS_PLAYER_ERROR,K.MAJOR_EVENT],[N.IVS_PLAYER_RECOVERABLE_ERROR,K.MAJOR_EVENT],[N.IVS_PLAYER_WORKER_ERROR,K.MAJOR_EVENT],[N.IVS_PLAYER_NETWORK_UNAVAILABLE,K.MAJOR_EVENT],[N.LIVESTREAM_LATENCY,K.MAJOR_EVENT],[N.IVS_PLAYER_ANALYTICS_EVENT,K.MINOR_EVENT],[N.IVS_PLAYER_PLAYBACK_RATE_CHANGED,K.MINOR_EVENT],[N.IVS_PLAYER_QUALITY_CHANGED,K.MINOR_EVENT],[N.IVS_PLAYER_INITIALIZED,K.MINOR_EVENT],[N.EXPECTED_VIDEO_RESOLUTION,K.MINOR_EVENT],[N.EXPECTED_SCREENSHARE_RESOLUTION,K.MINOR_EVENT]]);class mT{constructor(){p(this,"events");this.events=[]}add(t){this.events.push(t)}flush(){return{entries:this.events.splice(0,25)}}}class fT extends dt{constructor({logger:e,peerId:r,apiHostnames:i}){super();p(this,"logger");p(this,"peerId");p(this,"eventStore");p(this,"apiEndpoint");this.logger=e,this.peerId=r,this.apiEndpoint=`https://${i.daCollector}/api/v1/message`,this.eventStore=new mT}async sendEventsChunkToServer(e){var i;const r={payload:e,peerId:this.peerId};try{return await fetch(this.apiEndpoint,{method:"POST",body:JSON.stringify(r)}),!0}catch(n){return this.logger.error("callStats::sendEventsChunkToServer::catch",{error:n}),(i=e.entries)==null||i.forEach(o=>{this.eventStore.add(o)}),!1}}callEvent(e){e.timestamp=new Date,this.eventStore.add(e),this.emit(e.event,e.metaData),gT.get(e.event)===K.MAJOR_EVENT&&this.flush()}async flush(){var r;const e=this.eventStore.flush();return(r=e==null?void 0:e.entries)!=null&&r.length?(await this.sendEventsChunkToServer(e),!0):!1}}var qp;(function(s){s.CHROMIUM="chromum",s.FIREFOX="firefox",s.SAFARI="safari"})(qp||(qp={}));const Za={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var ss;(function(s){s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.SPEAKER="SPEAKER",s.SCREENSHARE="SCREENSHARE"})(ss||(ss={}));var jp;(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"})(jp||(jp={}));function Vr(s){return s?s.split(".").slice(0,2).concat(["0","0"]).join("."):""}function cd({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function dd({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}const Gp=240,Wp=720,Jp=8,Kp=3,ld=10,ud=.02,hd=.03;function Qs({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 zp({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 Yp({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function Qp({packetsLost:s,packetsSent:t,jitter:e}){const i=Qs({stat:Yp({packetsLost:s,packetsSent:t}),weight:.7,rangeMin:0,rangeMax:ld,rangeRankingDirection:"UP"}),o=Qs({stat:e,weight:.3,rangeMin:ud,rangeMax:hd,rangeRankingDirection:"UP"});return i+o}function ST({frameWidth:s,isScreenShare:t}){return s<(t?Wp:Gp)}function vT({framesPerSecond:s,isScreenShare:t}){return s<(t?Kp:Jp)}function TT({framesEncoded:s}){return s===0}function Xp({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsSent:r,jitter:i,isScreenShare:n,framesEncoded:o}){const c=Qs({stat:Yp({packetsLost:e,packetsSent:r}),weight:1,rangeMin:0,rangeMax:ld,rangeRankingDirection:"UP"}),d=Qs({stat:i,weight:1,rangeMin:ud,rangeMax:hd,rangeRankingDirection:"UP"}),l=ST({frameWidth:s,isScreenShare:n}),u=vT({framesPerSecond:t,isScreenShare:n}),h=TT({framesEncoded:o,isScreenShare:n});return zp({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:h,jitterQuality:d,packetsLostQuality:c})}function Zp({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}function eg({concealmentEvents:s,packetsLost:t,packetsReceived:e,jitter:r}){const n=Qs({stat:s,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),o=.5,c=Qs({stat:Zp({packetsLost:t,packetsReceived:e}),weight:o,rangeMin:0,rangeMax:ld,rangeRankingDirection:"UP"}),l=Qs({stat:r,weight:.3,rangeMin:ud,rangeMax:hd,rangeRankingDirection:"UP"});return n+c+l}function yT({framesDecoded:s}){return s===0}function ET({framesPerSecond:s,isScreenShare:t}){return s<(t?Kp:Jp)}function wT({frameWidth:s,isScreenShare:t}){return s<(t?Wp:Gp)}function tg({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsReceived:r,jitter:i,isScreenShare:n,framesDecoded:o}){const c=Qs({stat:Zp({packetsLost:e,packetsReceived:r}),weight:1,rangeMin:0,rangeMax:ld,rangeRankingDirection:"UP"}),d=Qs({stat:i,weight:1,rangeMin:ud,rangeMax:hd,rangeRankingDirection:"UP"}),l=wT({frameWidth:s,isScreenShare:n}),u=ET({framesPerSecond:t,isScreenShare:n}),h=yT({framesDecoded:o,isScreenShare:n});return zp({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:h,jitterQuality:d,packetsLostQuality:c})}class Xs{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=Xs.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=Xs.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 yp{static getParser(t,e=!1){if(typeof t!="string")throw new Error("UserAgent should be a string");return new Tp(t,e)}static parse(t){return new Tp(t).getResult()}static get BROWSER_MAP(){return vp}static get ENGINE_MAP(){return Nr}static get OS_MAP(){return Tt}static get PLATFORMS_MAP(){return Le}}const Xa="chrome",Ep="opera",bp="firefox",wp="iexplorer",Pp="safari",_p="nwjs",Rp="electron",Cp="react-native",yu="unknown",id={Chrome:Xa,Chromium:Xa,Opera:Ep,Firefox:bp,"Internet Explorer":wp,Safari:Pp};function Wv(){const{userAgent:s}=navigator,t={name:yu,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=Xa,t.version=e)}else t.name=Xa,t.version=s.match(/Chrome\/([\d.]+)/)[1];return t}function Jv(){const{userAgent:s}=navigator;if(s.match(/Electron/)){const t=s.match(/Electron\/([\d.]+)/)[1];return{name:Rp,version:t}}return null}function Kv(){const{userAgent:s}=navigator;if(s.match(/JitsiMeetNW/)){const t=s.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:_p,version:t}}}function zv(){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:Cp,version:t}}function Yv(s){let t;const e=[zv,Jv,Kv];for(let i=0;i<e.length;i+=1)if(t=e[i](),t)return t;const r=s.getBrowserName();return r in id?{name:id[r],version:s.getBrowserVersion()}:(t=Wv(),t||{name:yu,version:void 0})}class Qv{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=yp.getParser(navigator.userAgent),typeof t=="undefined"){const i=Yv(this._bowser);e=i.name,r=i.version}else t.name in id?(e=id[t.name],r=t.version):(e=yu,r=void 0);this._name=e,this._version=r}getName(){return this._name}isChrome(){return this._name===Xa}isOpera(){return this._name===Ep}isFirefox(){return this._name===bp}isIExplorer(){return this._name===wp}isSafari(){return this._name===Pp}isNWJS(){return this._name===_p}isElectron(){return this._name===Rp}isReactNative(){return this._name===Cp||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 Xv extends Qv{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 we=new Xv;var lt={},Zv={get exports(){return lt},set exports(s){lt=s}},Cn=typeof Reflect=="object"?Reflect:null,kp=Cn&&typeof Cn.apply=="function"?Cn.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},nd;Cn&&typeof Cn.ownKeys=="function"?nd=Cn.ownKeys:Object.getOwnPropertySymbols?nd=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:nd=function(t){return Object.getOwnPropertyNames(t)};function eT(s){console&&console.warn&&console.warn(s)}var Ip=Number.isNaN||function(t){return t!==t};function oe(){oe.init.call(this)}Zv.exports=oe,lt.once=iT,oe.EventEmitter=oe,oe.prototype._events=void 0,oe.prototype._eventsCount=0,oe.prototype._maxListeners=void 0;var Ap=10;function ad(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(oe,"defaultMaxListeners",{enumerable:!0,get:function(){return Ap},set:function(s){if(typeof s!="number"||s<0||Ip(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Ap=s}}),oe.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},oe.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Ip(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 Mp(s){return s._maxListeners===void 0?oe.defaultMaxListeners:s._maxListeners}oe.prototype.getMaxListeners=function(){return Mp(this)},oe.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")kp(d,this,e);else for(var l=d.length,u=Lp(d,l),r=0;r<l;++r)kp(u[r],this,e);return!0};function Op(s,t,e,r){var i,n,o;if(ad(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=Mp(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,eT(c)}return s}oe.prototype.addListener=function(t,e){return Op(this,t,e,!1)},oe.prototype.on=oe.prototype.addListener,oe.prototype.prependListener=function(t,e){return Op(this,t,e,!0)};function tT(){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 Dp(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=tT.bind(r);return i.listener=e,r.wrapFn=i,i}oe.prototype.once=function(t,e){return ad(e),this.on(t,Dp(this,t,e)),this},oe.prototype.prependOnceListener=function(t,e){return ad(e),this.prependListener(t,Dp(this,t,e)),this},oe.prototype.removeListener=function(t,e){var r,i,n,o,c;if(ad(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():sT(r,n),r.length===1&&(i[t]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",t,c||e)}return this},oe.prototype.off=oe.prototype.removeListener,oe.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 Np(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?rT(i):Lp(i,i.length)}oe.prototype.listeners=function(t){return Np(this,t,!0)},oe.prototype.rawListeners=function(t){return Np(this,t,!1)},oe.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):Vp.call(s,t)},oe.prototype.listenerCount=Vp;function Vp(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}oe.prototype.eventNames=function(){return this._eventsCount>0?nd(this._events):[]};function Lp(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function sT(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function rT(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function iT(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))}xp(s,t,n,{once:!0}),t!=="error"&&nT(s,i,{once:!0})})}function nT(s,t,e){typeof s.on=="function"&&xp(s,"error",t,e)}function xp(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 J;(function(s){s[s.MAJOR_EVENT=0]="MAJOR_EVENT",s[s.MINOR_EVENT=1]="MINOR_EVENT"})(J||(J={}));var N;(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"})(N||(N={}));const aT=new Map([[N.PRECALL_TEST_BEGIN,J.MINOR_EVENT],[N.PRECALL_TEST_COMPLETE,J.MINOR_EVENT],[N.CALL_JOIN_BEGIN,J.MAJOR_EVENT],[N.NET_QUALITY_TEST_BEGIN,J.MINOR_EVENT],[N.NET_QUALITY_TEST_END,J.MINOR_EVENT],[N.WEBSOCKET_CONNECTED,J.MINOR_EVENT],[N.TRANSPORT_CONNECTED,J.MAJOR_EVENT],[N.AUDIO_ON,J.MINOR_EVENT],[N.AUDIO_OFF,J.MINOR_EVENT],[N.VIDEO_ON,J.MINOR_EVENT],[N.VIDEO_OFF,J.MINOR_EVENT],[N.PARTICIPANT_ROLE,J.MINOR_EVENT],[N.PING_STAT,J.MAJOR_EVENT],[N.DISCONNECT,J.MAJOR_EVENT],[N.RECONNECT_ATTEMPT,J.MAJOR_EVENT],[N.SCREENSHARE_START_REQUESTED,J.MINOR_EVENT],[N.SCREENSHARE_STARTED,J.MINOR_EVENT],[N.SCREENSHARE_STOPPED,J.MINOR_EVENT],[N.TAB_CHANGE,J.MINOR_EVENT],[N.BROWSER_BACKGROUNDED,J.MINOR_EVENT],[N.BROWSER_FOREGROUNDED,J.MINOR_EVENT],[N.DOMINANT_SPEAKER,J.MINOR_EVENT],[N.AUDIO_DEVICES_UPDATES,J.MINOR_EVENT],[N.VIDEO_DEVICES_UPDATES,J.MINOR_EVENT],[N.SPEAKER_DEVICES_UPDATES,J.MINOR_EVENT],[N.SELECTED_MICROHPONE_UPDATE,J.MINOR_EVENT],[N.SELECTED_CAMERA_UPDATE,J.MINOR_EVENT],[N.SELECTED_SPEAKER_UPDATE,J.MINOR_EVENT],[N.MEDIA_PERMISSION,J.MINOR_EVENT],[N.LEGACY_SWITCH,J.MINOR_EVENT],[N.AUDIO_PLAY_FAILED,J.MINOR_EVENT],[N.VIDEO_PLAY_FAILED,J.MINOR_EVENT],[N.AUDIO_TRACK_MUTED,J.MINOR_EVENT],[N.VIDEO_TRACK_MUTED,J.MINOR_EVENT],[N.IVS_PLAYER_REBUFFERING,J.MAJOR_EVENT],[N.IVS_PLAYER_AUDIO_BLOCKED,J.MAJOR_EVENT],[N.IVS_PLAYER_PLAYBACK_BLOCKED,J.MAJOR_EVENT],[N.IVS_PLAYER_ERROR,J.MAJOR_EVENT],[N.IVS_PLAYER_RECOVERABLE_ERROR,J.MAJOR_EVENT],[N.IVS_PLAYER_WORKER_ERROR,J.MAJOR_EVENT],[N.IVS_PLAYER_NETWORK_UNAVAILABLE,J.MAJOR_EVENT],[N.LIVESTREAM_LATENCY,J.MAJOR_EVENT],[N.IVS_PLAYER_ANALYTICS_EVENT,J.MINOR_EVENT],[N.IVS_PLAYER_PLAYBACK_RATE_CHANGED,J.MINOR_EVENT],[N.IVS_PLAYER_QUALITY_CHANGED,J.MINOR_EVENT],[N.IVS_PLAYER_INITIALIZED,J.MINOR_EVENT],[N.EXPECTED_VIDEO_RESOLUTION,J.MINOR_EVENT],[N.EXPECTED_SCREENSHARE_RESOLUTION,J.MINOR_EVENT]]);class oT{constructor(){p(this,"events");this.events=[]}add(t){this.events.push(t)}flush(){return{entries:this.events.splice(0,25)}}}class cT extends lt{constructor({logger:e,peerId:r,apiHostnames:i}){super();p(this,"logger");p(this,"peerId");p(this,"eventStore");p(this,"apiEndpoint");this.logger=e,this.peerId=r,this.apiEndpoint=`https://${i.daCollector}/api/v1/message`,this.eventStore=new oT}async sendEventsChunkToServer(e){var i;const r={payload:e,peerId:this.peerId};try{return await fetch(this.apiEndpoint,{method:"POST",body:JSON.stringify(r)}),!0}catch(n){return this.logger.error("callStats::sendEventsChunkToServer::catch",{error:n}),(i=e.entries)==null||i.forEach(o=>{this.eventStore.add(o)}),!1}}callEvent(e){e.timestamp=new Date,this.eventStore.add(e),this.emit(e.event,e.metaData),aT.get(e.event)===J.MAJOR_EVENT&&this.flush()}async flush(){var r;const e=this.eventStore.flush();return(r=e==null?void 0:e.entries)!=null&&r.length?(await this.sendEventsChunkToServer(e),!0):!1}}var Up;(function(s){s.CHROMIUM="chromum",s.FIREFOX="firefox",s.SAFARI="safari"})(Up||(Up={}));const Za={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var ts;(function(s){s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.SPEAKER="SPEAKER",s.SCREENSHARE="SCREENSHARE"})(ts||(ts={}));var Fp;(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"})(Fp||(Fp={}));function Vr(s){return s?s.split(".").slice(0,2).concat(["0","0"]).join("."):""}function od({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function cd({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}const $p=240,Bp=720,Hp=8,qp=3,dd=10,ld=.02,ud=.03;function Qs({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 jp({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 Gp({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function Wp({packetsLost:s,packetsSent:t,jitter:e}){const i=Qs({stat:Gp({packetsLost:s,packetsSent:t}),weight:.7,rangeMin:0,rangeMax:dd,rangeRankingDirection:"UP"}),o=Qs({stat:e,weight:.3,rangeMin:ld,rangeMax:ud,rangeRankingDirection:"UP"});return i+o}function dT({frameWidth:s,isScreenShare:t}){return s<(t?Bp:$p)}function lT({framesPerSecond:s,isScreenShare:t}){return s<(t?qp:Hp)}function uT({framesEncoded:s}){return s===0}function Jp({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsSent:r,jitter:i,isScreenShare:n,framesEncoded:o}){const c=Qs({stat:Gp({packetsLost:e,packetsSent:r}),weight:1,rangeMin:0,rangeMax:dd,rangeRankingDirection:"UP"}),d=Qs({stat:i,weight:1,rangeMin:ld,rangeMax:ud,rangeRankingDirection:"UP"}),l=dT({frameWidth:s,isScreenShare:n}),u=lT({framesPerSecond:t,isScreenShare:n}),h=uT({framesEncoded:o,isScreenShare:n});return jp({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:h,jitterQuality:d,packetsLostQuality:c})}function Kp({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}function zp({concealmentEvents:s,packetsLost:t,packetsReceived:e,jitter:r}){const n=Qs({stat:s,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),o=.5,c=Qs({stat:Kp({packetsLost:t,packetsReceived:e}),weight:o,rangeMin:0,rangeMax:dd,rangeRankingDirection:"UP"}),l=Qs({stat:r,weight:.3,rangeMin:ld,rangeMax:ud,rangeRankingDirection:"UP"});return n+c+l}function hT({framesDecoded:s}){return s===0}function pT({framesPerSecond:s,isScreenShare:t}){return s<(t?qp:Hp)}function gT({frameWidth:s,isScreenShare:t}){return s<(t?Bp:$p)}function Yp({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsReceived:r,jitter:i,isScreenShare:n,framesDecoded:o}){const c=Qs({stat:Kp({packetsLost:e,packetsReceived:r}),weight:1,rangeMin:0,rangeMax:dd,rangeRankingDirection:"UP"}),d=Qs({stat:i,weight:1,rangeMin:ld,rangeMax:ud,rangeRankingDirection:"UP"}),l=gT({frameWidth:s,isScreenShare:n}),u=pT({framesPerSecond:t,isScreenShare:n}),h=hT({framesDecoded:o,isScreenShare:n});return jp({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:h,jitterQuality:d,packetsLostQuality:c})}class Xs{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=Xs.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=Xs.parseCandidate(e.candidate.candidate);this.iceCandidateFilter(r)&&t.addIceCandidate(e.candidate)}}setIceCandidateFilter(t){this.iceCandidateFilter=t}constrainVideoBitrate(t){this.constrainVideoBitrateKbps=t}disableVideoFec(){this.constrainOfferToRemoveVideoFec=!0}gotOffer(t){this.constrainOfferToRemoveVideoFec&&(t.sdp=t.sdp.replace(/(m=video 1 [^\r]+)(116 117)(\r\n)/g,`$1\r
|
|
7
7
|
`),t.sdp=t.sdp.replace(/a=rtpmap:116 red\/90000\r\n/g,""),t.sdp=t.sdp.replace(/a=rtpmap:117 ulpfec\/90000\r\n/g,""),t.sdp=t.sdp.replace(/a=rtpmap:98 rtx\/90000\r\n/g,""),t.sdp=t.sdp.replace(/a=fmtp:98 apt=116\r\n/g,"")),this.pc1.setLocalDescription(t),this.pc2.setRemoteDescription(t),this.pc2.createAnswer().then(this.gotAnswer.bind(this),this.reportFatal.bind(this))}gotAnswer(t){this.constrainVideoBitrateKbps&&(t.sdp=t.sdp.replace(/a=mid:video\r\n/g,`a=mid:video\r
|
|
8
8
|
b=AS:${this.constrainVideoBitrateKbps}\r
|
|
9
|
-
`)),this.pc2.setLocalDescription(t),this.pc1.setRemoteDescription(t)}establishConnection(){this.pc1.createOffer().then(this.gotOffer.bind(this),this.reportFatal.bind(this))}reportFatal(t){console.error("Error:",t)}async getRoundTripTime(){const[t,e]=await Promise.all([this.pc1.getStats(),this.pc2.getStats()]);let r,i;if(t.forEach(n=>{n.type==="candidate-pair"&&n.nominated===!0&&n.bytesSent>0&&(r=n)}),e.forEach(n=>{n.type==="candidate-pair"&&n.nominated===!0&&n.bytesReceived>0&&(i=n)}),r&&i)try{if(r.currentRoundTripTime&&i.currentRoundTripTime)return{rtt:r.currentRoundTripTime,backendRTT:i.currentRoundTripTime};const n=(i.lastPacketReceivedTimestamp-r.lastPacketSentTimestamp)/1e3;return{rtt:n,backendRTT:n}}catch(n){return}}close(){this.pc1.close(),this.pc2.close()}}class sg extends dt{constructor(e){super();p(this,"call");p(this,"timeOut");this.call=new Xs(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 bT=8,PT=1/1e3;class _T extends sg{constructor(e){super(e);p(this,"senderChannel");p(this,"recieveChannel");p(this,"startTime");p(this,"lastBitrateMeasureTime");p(this,"sentPayloadBytes",0);p(this,"recievedPayloadBytes",0);p(this,"lastReceivedPayloadBytes",0);p(this,"stopSending",!1);p(this,"testProgress",0);p(this,"samplePacket","");p(this,"finalBitrateSum",0);p(this,"bitRateSampels",0);p(this,"maxNumberOfPacketsToSend",0);p(this,"bytesToKeepBuffered",0);p(this,"testDurationSeconds",5);this.call.setIceCandidateFilter(Xs.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)*bT/(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*PT)})}}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 bu extends sg{constructor(e,r=Xs.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 RT extends bu{constructor(t){super(t,Xs.isHost)}}class CT extends bu{constructor(t){super(t,Xs.isRelay)}}class kT extends bu{constructor(t){super(t,Xs.isReflexive)}}class IT{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=Vr(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=Vr(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 Pu=new IT,rg=[{urls:"turn:turn.dyte.in:443?transport=tcp",username:"dyte",credential:"dytein",credentialType:"password"},{urls:"turn:turn.dyte.in:3478?transport=udp",username:"dyte",credential:"dytein",credentialType:"password"}];function ig(s){const[t,e]=s.split(",");return{coords:{latitude:Number(t),longitude:Number(e)}}}class ng{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 ag extends dt{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 dt}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 w,b,C,D,F,L,B,W,ae,Tt,xs,_n,Us;const c=e,d=new ng,l=r.length?new Set(r):void 0,u=[],h=[],g=[],S=new Map,y=new Map;for(const I of c.values()){if(l){if(l.size===0)break;if(l.has(I.type))i&&l.delete(I.type);else continue}switch(I.type){case"local-candidate":{u.push(this.getIceCandidateStats(I));break}case"remote-candidate":{h.push(this.getIceCandidateStats(I));break}case"candidate-pair":{const{nominated:T}=I,{selected:P}=I,$=I,Ce={nominated:T!=null?T:P,currentRoundTripTime:$.currentRoundTripTime,totalRoundTripTime:$.totalRoundTripTime,bytesReceived:$.bytesReceived,bytesSent:$.bytesSent,availableOutgoingBitrate:$.availableOutgoingBitrate,availableIncomingBitrate:$.availableIncomingBitrate,lastPacketReceivedTimestamp:$.lastPacketReceivedTimestamp,lastPacketSentTimestamp:$.lastPacketSentTimestamp,localCandidateId:$.localCandidateId,remoteCandidateId:$.remoteCandidateId,bytesDiscardedOnSend:$.bytesDiscardedOnSend,packetsSent:$.packetsSent,packetsReceived:$.packetsReceived,packetsDiscardedOnSend:$.packetsDiscardedOnSend};g.push(Ce),(I.nominated===!0||I.selected===!0)&&(d.candidatePair=Ce);break}case"transport":{const T=I;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 P={bytesReceived:T.bytesReceived,bytesSent:T.bytesSent,packetsSent:T.packetsSent,packetsReceived:T.packetsReceived,dtlsCipher:T.dtlsCipher,dtlsState:T.dtlsState,iceRole:T.iceRole};if(d.transport=P,o){if(o.producing){const $=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,$,P)}if(o.consuming){const $=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,$,P)}}break}case"remote-inbound-rtp":{const T=I,P={jitter:T.jitter,fractionLost:T.fractionLost,roundTripTime:T.roundTripTime,roundTripTimeMeasurements:T.roundTripTimeMeasurements,totalRoundTripTime:T.totalRoundTripTime,packetsLost:T.packetsLost};d.remoteInboundRtp.set(T.localId,P);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(I.id))break;const T=I,P=n||this.outboundProducerMap.get(I.id),$=this.pausedProducerMap.get(P);if($){if($.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const Ce=this.overallProducersStatsMap[P];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.outboundProducerMap.has(I.id)){d.staleProducerStreamMap=!0;break}const qe=this.callStatsInstance.producers.get(P);if(((w=qe==null?void 0:qe.track)==null?void 0:w.readyState)==="ended")break;d.producerStreamMap.has(P)||d.producerStreamMap.set(P,{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 R=T,Je={frameHeight:R.frameHeight,frameWidth:R.frameWidth,framesEncoded:R.framesEncoded,framesDropped:R.framesDropped,framesPerSecond:R.framesPerSecond,framesSent:R.framesSent,keyFramesEncoded:R.keyFramesEncoded,firCount:R.firCount,encoderImplementation:R.encoderImplementation,hugeFramesSent:R.hugeFramesSent,pliCount:R.pliCount,qpSum:R.qpSum,qualityLimitationDurations:R.qualityLimitationDurations,qualityLimitationReason:R.qualityLimitationReason,qualityLimitationResolutionChanges:R.qualityLimitationResolutionChanges,totalEncodeTime:R.targetBitrate,totalPacketSendDelay:R.totalPacketSendDelay,retransmittedBytesSent:R.retransmittedBytesSent,retransmittedPacketsSent:R.retransmittedPacketsSent,scalabilityMode:R.scalabilityMode,powerEfficientEncoder:R.powerEfficientEncoder,...V};d.outboundVideoRtp.set(I.id,Je),d.producerStreamMap.get(P).outboundVideoRtpId.push(I.id),this.processOutboundProducerVideoStats(P,Ce,Je)}else if(T.mediaType==="audio"||T.kind==="audio"){const R=T,Je={retransmittedBytesSent:R.retransmittedBytesSent,retransmittedPacketsSent:R.retransmittedPacketsSent,...V};d.outboundAudioRtp.set(I.id,Je),d.producerStreamMap.get(P).outboundAudioRtpId.push(I.id),this.processOutboundProducerAudioStats(P,Ce,Je)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(I.id))break;const T=I,P=n||this.inboundConsumerMap.get(I.id),$=this.pausedConsumerMap.get(P);if($){if($.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(T.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const Ce=this.overallConsumersStatsMap[P];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.inboundConsumerMap.has(I.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(P)||d.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const qe={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,R={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,...qe};R.score=tg({frameWidth:R.frameWidth||0,framesDecoded:(R.framesDecoded||0)-(((b=this.videoConsumerToStatsMap.get(P))==null?void 0:b.framesDecoded)||0),framesPerSecond:R.framesPerSecond||0,packetsLost:(R.packetsLost||0)-(((C=this.videoConsumerToStatsMap.get(P))==null?void 0:C.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((D=this.videoConsumerToStatsMap.get(P))==null?void 0:D.packetsReceived)||0),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),y.set(P,{score:+(R.score*10).toFixed(),frameWidth:R.frameWidth||0,frameHeight:R.frameHeight||0,framesPerSecond:R.framesPerSecond||0,packetsLostPercentage:dd({packetsLost:(R.packetsLost||0)-(((F=this.videoConsumerToStatsMap.get(P))==null?void 0:F.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((L=this.videoConsumerToStatsMap.get(P))==null?void 0:L.packetsReceived)||0)}),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((R.bytesReceived||0)-(((B=this.videoConsumerToStatsMap.get(P))==null?void 0:B.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,R),d.inboundVideoRtp.set(I.id,R),d.consumerStreamMap.get(P).inboundVideoRtpId.push(I.id),this.processInboundConsumerVideoStats(P,Ce,R)}else if(T.mediaType==="audio"||T.kind==="audio"){const V=T,R={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,...qe};R.score=eg({concealmentEvents:(R.concealmentEvents||0)-(((W=this.audioConsumerToStatsMap.get(P))==null?void 0:W.concealmentEvents)||0),packetsLost:(R.packetsLost||0)-(((ae=this.audioConsumerToStatsMap.get(P))==null?void 0:ae.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((Tt=this.audioConsumerToStatsMap.get(P))==null?void 0:Tt.packetsReceived)||0),jitter:R.jitter||0}),y.set(P,{score:+(R.score*10).toFixed(),packetsLostPercentage:dd({packetsLost:(R.packetsLost||0)-(((xs=this.audioConsumerToStatsMap.get(P))==null?void 0:xs.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((_n=this.audioConsumerToStatsMap.get(P))==null?void 0:_n.packetsReceived)||0)}),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((R.bytesReceived||0)-(((Us=this.audioConsumerToStatsMap.get(P))==null?void 0:Us.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,R),d.inboundAudioRtp.set(I.id,R),d.consumerStreamMap.get(P).inboundAudioRtpId.push(I.id),this.processInboundConsumerAudioStats(P,Ce,R)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}}}if(d.producerStreamMap.forEach((I,T)=>{var P,$,Ce,qe,V,R,Je,Dr,Uc,Fc,$c,Bc,Hc,qc,jc,Gc,Wc,Jc,Kc,zc,Yc,Qc,Xc;if(I.outboundVideoRtpId.length>0){const he=[];I.outboundVideoRtpId.forEach(ip=>{he.push(d.outboundVideoRtp.get(ip))});const ee=this.getWorkingSimulcastVideoStats(he);ee.score=Xp({frameWidth:ee.frameWidth||0,framesPerSecond:ee.framesPerSecond||0,jitter:((P=ee.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsSent:(ee.packetsSent||0)-((($=this.videoProducerToStatsMap.get(T))==null?void 0:$.packetsSent)||0),packetsLost:(((Ce=ee.remoteData)==null?void 0:Ce.packetsLost)||0)-(((V=(qe=this.videoProducerToStatsMap.get(T))==null?void 0:qe.remoteData)==null?void 0:V.packetsLost)||0),framesEncoded:(ee.framesEncoded||0)-(((R=this.videoProducerToStatsMap.get(T))==null?void 0:R.framesEncoded)||0)}),S.set(T,{score:+(ee.score*10).toFixed(),frameWidth:ee.frameWidth||0,frameHeight:ee.frameHeight||0,framesPerSecond:ee.framesPerSecond||0,jitter:((Je=ee.remoteData)==null?void 0:Je.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsLostPercentage:cd({packetsSent:(ee.packetsSent||0)-(((Dr=this.videoProducerToStatsMap.get(T))==null?void 0:Dr.packetsSent)||0),packetsLost:(((Uc=ee.remoteData)==null?void 0:Uc.packetsLost)||0)-((($c=(Fc=this.videoProducerToStatsMap.get(T))==null?void 0:Fc.remoteData)==null?void 0:$c.packetsLost)||0)}),bitrate:((ee.bytesSent||0)-(((Bc=this.videoProducerToStatsMap.get(T))==null?void 0:Bc.bytesSent)||0))*8/7,cpuLimitations:ee.qualityLimitationReason==="cpu",bandwidthLimitations:ee.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(T,ee)}else if(I.outboundAudioRtpId.length>0){const he=d.outboundAudioRtp.get(I.outboundAudioRtpId[0]);he.score=Qp({packetsSent:(he.packetsSent||0)-(((Hc=this.audioProducerToStatsMap.get(T))==null?void 0:Hc.packetsSent)||0),packetsLost:(((qc=he.remoteData)==null?void 0:qc.packetsLost)||0)-(((Gc=(jc=this.audioProducerToStatsMap.get(T))==null?void 0:jc.remoteData)==null?void 0:Gc.packetsLost)||0),jitter:((Wc=he.remoteData)==null?void 0:Wc.jitter)||0}),S.set(T,{score:+(he.score*10).toFixed(),bitrate:((he.bytesSent||0)-(((Jc=this.audioProducerToStatsMap.get(T))==null?void 0:Jc.bytesSent)||0))*8/7,packetsLostPercentage:cd({packetsSent:(he.packetsSent||0)-(((Kc=this.audioProducerToStatsMap.get(T))==null?void 0:Kc.packetsSent)||0),packetsLost:(((zc=he.remoteData)==null?void 0:zc.packetsLost)||0)-(((Qc=(Yc=this.audioProducerToStatsMap.get(T))==null?void 0:Yc.remoteData)==null?void 0:Qc.packetsLost)||0)}),jitter:((Xc=he.remoteData)==null?void 0:Xc.jitter)||0,isScreenShare:this.screenShareProducers.has(T)}),this.audioProducerToStatsMap.set(T,he)}}),g.forEach(I=>{const T=u.find($=>$.id===I.localCandidateId?(I.localCandidateId=$.id,$):null),P=h.find($=>$.id===I.remoteCandidateId?(I.remoteCandidateId=$.id,$):null);T&&(I.localCandidateType=T.type,I.localCandidateAddress=Vr(T.address),I.localCandidatePort=T.port,I.localCandidateProtocol=T.protocol,I.localCandidateUrl=T.url,I.localCandidateNetworkType=T.networkType,I.localCandidateRelatedAddress=Vr(T.relatedAddress),I.localCandidateRelatedPort=T.relatedPort),P&&(I.remoteCandidateType=P.type,I.remoteCandidateAddress=Vr(P.address),I.remoteCandidatePort=P.port,I.remoteCandidateProtocol=P.protocol,I.remoteCandidateUrl=P.url)}),d.candidatePair&&(d.transport?(d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.availableIncomingBitrate=d.candidatePair.availableIncomingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:d.candidatePair.availableIncomingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=g),d.transport&&!d.transport.roundTripTime){let I=0,T=0;d.remoteInboundRtp.forEach((P,$)=>{P.roundTripTime&&P.roundTripTime>I&&(I=P.roundTripTime,T=P.totalRoundTripTime)}),d.transport.roundTripTime=I,d.transport.totalRoundTripTime=T}if(y.size>0)try{this.observer.emit("consumer_score",y)}catch(I){}if(S.size>0)try{this.observer.emit("producer_score",S)}catch(I){}return d}async getProducersReport(e){const r=e.map(i=>this.generateProducerStreamMap(i,!0));return r.length>0?Promise.all(r):void 0}async getConsumersReport(e){const r=e.map(i=>this.generateConsumerStreamMap(i,!0));return r.length>0?Promise.all(r):void 0}async getTransportReport(e){return e.getStats()}async getProcessedStats(e,r,i){const n=await this.getTransportReport(e),o={producing:i,consuming:r,id:e.id},c=n,d=this.parseRTCReport(c,["transport","candidate-pair","inbound-rtp","outbound-rtp","remote-inbound-rtp","local-candidate","remote-candidate"],!1,void 0,o);if(!d)return;const l={stats:d.transport,transportId:e.id,consuming:r,producing:i},u=d.staleProducerStreamMap?void 0:this.getProducerStatsFromReport(d),h=d.staleConsumerStreamMap?void 0:this.getConsumerStatsFromReport(d);return{transportReport:l,producerReport:u,consumerReport:h}}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((i,n)=>{var o,c;r.push({producerId:n,videoStats:i.outboundVideoRtpId.map(d=>e.outboundVideoRtp.get(d)),audioStats:i.outboundAudioRtpId.map(d=>e.outboundAudioRtp.get(d)),appData:((c=(o=this.callStatsInstance.producers)==null?void 0:o.get(n))==null?void 0:c.appData)||null})})}catch(i){this.callStatsInstance.logger.error("callStats::measurements::getProducerStatsFromReport",{error:{reason:i.reason,message:i.message}})}return r}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((i,n)=>{const{peerId:o,producerId:c,appData:d}=this.consumerPeerIdMap.get(n);r.push({consumerId:n,peerId:o,producerId:c,appData:d,videoStats:i.inboundVideoRtpId.map(l=>e.inboundVideoRtp.get(l)),audioStats:i.inboundAudioRtpId.map(l=>e.inboundAudioRtp.get(l))})})}catch(i){console.error("getConsumersReport: ",i,e)}return r}async getUserLocation(){return new Promise((e,r)=>{try{navigator.geolocation?navigator.geolocation.getCurrentPosition(i=>{e(i)}):r()}catch(i){r(i)}})}async getConnectivity(e){try{const r={iceServers:e||rg},i=new Promise((u,h)=>{try{const g=new RT(r);g.addListener("done",u),g.addListener("failed",()=>{u({connectivity:!1})}),g.start(2e3)}catch(g){h(g)}}),n=new Promise((u,h)=>{try{const g=new CT(r);g.addListener("done",u),g.addListener("failed",()=>{u({connectivity:!1})}),g.start(2e3)}catch(g){h(g)}}),o=new Promise((u,h)=>{try{const g=new kT(r);g.addListener("done",u),g.addListener("failed",()=>{u({connectivity:!1})}),g.start(2e3)}catch(g){h(g)}}),[c,d,l]=await Promise.all([i,n,o]);return{host:c==null?void 0:c.connectivity,relay:d==null?void 0:d.connectivity,reflexive:l==null?void 0:l.connectivity}}catch(r){return{host:!1,relay:!1,reflexive:!1}}}async getThroughput(e){try{const i=await new Promise((n,o)=>{try{const c={iceServers:e||rg},d=new _T(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 Pu.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?ig(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?ig(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 AT extends ag{}class og extends ag{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 w,b,C,D,F,L,B,W,ae,Tt,xs,_n,Us;const c=e,d=new ng,l=r.length?new Set(r):void 0,u=[],h=[],g=[],S=new Map,y=new Map;for(const I of c.values()){if(l){if(l.size===0)break;if(l.has(I.type))i&&l.delete(I.type);else continue}switch(I.type){case"local-candidate":{u.push(this.getIceCandidateStats(I));break}case"remote-candidate":{h.push(this.getIceCandidateStats(I));break}case"candidate-pair":{const{nominated:T}=I,{selected:P}=I,$=I,Ce={nominated:T!=null?T:P,currentRoundTripTime:$.currentRoundTripTime,totalRoundTripTime:$.totalRoundTripTime,bytesReceived:$.bytesReceived,bytesSent:$.bytesSent,availableOutgoingBitrate:$.availableOutgoingBitrate,availableIncomingBitrate:$.availableIncomingBitrate,lastPacketReceivedTimestamp:$.lastPacketReceivedTimestamp,lastPacketSentTimestamp:$.lastPacketSentTimestamp,localCandidateId:$.localCandidateId,remoteCandidateId:$.remoteCandidateId,bytesDiscardedOnSend:$.bytesDiscardedOnSend,packetsSent:$.packetsSent,packetsReceived:$.packetsReceived,packetsDiscardedOnSend:$.packetsDiscardedOnSend};g.push(Ce),(I.nominated===!0||I.selected===!0)&&(d.candidatePair=Ce);break}case"transport":{const T=I;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 P={bytesReceived:T.bytesReceived,bytesSent:T.bytesSent,packetsSent:T.packetsSent,packetsReceived:T.packetsReceived,dtlsCipher:T.dtlsCipher,dtlsState:T.dtlsState,iceRole:T.iceRole};if(d.transport=P,o){if(o.producing){const $=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,$,P)}if(o.consuming){const $=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,$,P)}}break}case"remote-inbound-rtp":{const T=I,P={jitter:T.jitter,fractionLost:T.fractionLost,roundTripTime:T.roundTripTime,roundTripTimeMeasurements:T.roundTripTimeMeasurements,totalRoundTripTime:T.totalRoundTripTime,packetsLost:T.packetsLost};d.remoteInboundRtp.set(T.localId,P);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(I.id))break;const T=I,P=n||this.outboundProducerMap.get(I.id),$=this.pausedProducerMap.get(P);if($){if($.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const Ce=this.overallProducersStatsMap[P];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.outboundProducerMap.has(I.id)){d.staleProducerStreamMap=!0;break}const qe=this.callStatsInstance.producers.get(P);if(((w=qe==null?void 0:qe.track)==null?void 0:w.readyState)==="ended")break;d.producerStreamMap.has(P)||d.producerStreamMap.set(P,{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 R=T,Je={frameHeight:R.frameHeight,frameWidth:R.frameWidth,framesEncoded:R.framesEncoded,framesDropped:R.framesDropped?R.framesDropped:R.droppedFrames,framesPerSecond:R.framesPerSecond?R.framesPerSecond:R.framerateMean,framesSent:R.framesSent,keyFramesEncoded:R.keyFramesEncoded,firCount:R.firCount,encoderImplementation:R.encoderImplementation,hugeFramesSent:R.hugeFramesSent,pliCount:R.pliCount,qpSum:R.qpSum,qualityLimitationReason:R.qualityLimitationReason,qualityLimitationDurations:R.qualityLimitationDurations,qualityLimitationResolutionChanges:R.qualityLimitationResolutionChanges,totalEncodeTime:R.totalEncodeTime,totalPacketSendDelay:R.totalEncodeTime,retransmittedBytesSent:R.retransmittedBytesSent,retransmittedPacketsSent:R.retransmittedPacketsSent,scalabilityMode:R.scalabilityMode,powerEfficientEncoder:R.powerEfficientEncoder,...V};d.outboundVideoRtp.set(I.id,Je),d.producerStreamMap.get(P).outboundVideoRtpId.push(I.id),this.processOutboundProducerVideoStats(P,Ce,Je)}else if(T.mediaType==="audio"||T.kind==="audio"){const R=T,Je={retransmittedBytesSent:R.retransmittedBytesSent,retransmittedPacketsSent:R.retransmittedPacketsSent,...V};d.outboundAudioRtp.set(I.id,Je),d.producerStreamMap.get(P).outboundAudioRtpId.push(I.id),this.processOutboundProducerAudioStats(P,Ce,Je)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(I.id))break;const T=I,P=n||this.inboundConsumerMap.get(I.id),$=this.pausedConsumerMap.get(P);if($){if($.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(T.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const Ce=this.overallConsumersStatsMap[P];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.inboundConsumerMap.has(I.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(P)||d.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const qe={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,R={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,...qe};R.score=tg({frameWidth:R.frameWidth||0,framesDecoded:(R.framesDecoded||0)-(((b=this.videoConsumerToStatsMap.get(P))==null?void 0:b.framesDecoded)||0),framesPerSecond:R.framesPerSecond||0,packetsLost:(R.packetsLost||0)-(((C=this.videoConsumerToStatsMap.get(P))==null?void 0:C.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((D=this.videoConsumerToStatsMap.get(P))==null?void 0:D.packetsReceived)||0),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),y.set(P,{score:+(R.score*10).toFixed(),frameWidth:R.frameWidth||0,frameHeight:R.frameHeight||0,framesPerSecond:R.framesPerSecond||0,packetsLostPercentage:dd({packetsLost:(R.packetsLost||0)-(((F=this.videoConsumerToStatsMap.get(P))==null?void 0:F.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((L=this.videoConsumerToStatsMap.get(P))==null?void 0:L.packetsReceived)||0)}),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((R.bytesReceived||0)-(((B=this.videoConsumerToStatsMap.get(P))==null?void 0:B.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,R),d.inboundVideoRtp.set(I.id,R),d.consumerStreamMap.get(P).inboundVideoRtpId.push(I.id),this.processInboundConsumerVideoStats(P,Ce,R)}else if(T.mediaType==="audio"||T.kind==="audio"){const V=T,R={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,...qe};R.score=eg({concealmentEvents:(R.concealmentEvents||0)-(((W=this.audioConsumerToStatsMap.get(P))==null?void 0:W.concealmentEvents)||0),packetsLost:(R.packetsLost||0)-(((ae=this.audioConsumerToStatsMap.get(P))==null?void 0:ae.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((Tt=this.audioConsumerToStatsMap.get(P))==null?void 0:Tt.packetsReceived)||0),jitter:R.jitter||0}),y.set(P,{score:+(R.score*10).toFixed(),packetsLostPercentage:dd({packetsLost:(R.packetsLost||0)-(((xs=this.audioConsumerToStatsMap.get(P))==null?void 0:xs.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((_n=this.audioConsumerToStatsMap.get(P))==null?void 0:_n.packetsReceived)||0)}),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((R.bytesReceived||0)-(((Us=this.audioConsumerToStatsMap.get(P))==null?void 0:Us.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,R),d.inboundAudioRtp.set(I.id,R),d.consumerStreamMap.get(P).inboundAudioRtpId.push(I.id),this.processInboundConsumerAudioStats(P,Ce,R)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}}}if(d.producerStreamMap.forEach((I,T)=>{var P,$,Ce,qe,V,R,Je,Dr,Uc,Fc,$c,Bc,Hc,qc,jc,Gc,Wc,Jc,Kc,zc,Yc,Qc,Xc;if(I.outboundVideoRtpId.length>0){const he=[];I.outboundVideoRtpId.forEach(ip=>{he.push(d.outboundVideoRtp.get(ip))});const ee=this.getWorkingSimulcastVideoStats(he);ee.score=Xp({frameWidth:ee.frameWidth||0,framesPerSecond:ee.framesPerSecond||0,jitter:((P=ee.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsSent:(ee.packetsSent||0)-((($=this.videoProducerToStatsMap.get(T))==null?void 0:$.packetsSent)||0),packetsLost:(((Ce=ee.remoteData)==null?void 0:Ce.packetsLost)||0)-(((V=(qe=this.videoProducerToStatsMap.get(T))==null?void 0:qe.remoteData)==null?void 0:V.packetsLost)||0),framesEncoded:(ee.framesEncoded||0)-(((R=this.videoProducerToStatsMap.get(T))==null?void 0:R.framesEncoded)||0)}),S.set(T,{score:+(ee.score*10).toFixed(),frameWidth:ee.frameWidth||0,frameHeight:ee.frameHeight||0,framesPerSecond:ee.framesPerSecond||0,jitter:((Je=ee.remoteData)==null?void 0:Je.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsLostPercentage:cd({packetsSent:(ee.packetsSent||0)-(((Dr=this.videoProducerToStatsMap.get(T))==null?void 0:Dr.packetsSent)||0),packetsLost:(((Uc=ee.remoteData)==null?void 0:Uc.packetsLost)||0)-((($c=(Fc=this.videoProducerToStatsMap.get(T))==null?void 0:Fc.remoteData)==null?void 0:$c.packetsLost)||0)}),bitrate:((ee.bytesSent||0)-(((Bc=this.videoProducerToStatsMap.get(T))==null?void 0:Bc.bytesSent)||0))*8/7,cpuLimitations:ee.qualityLimitationReason==="cpu",bandwidthLimitations:ee.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(T,ee)}else if(I.outboundAudioRtpId.length>0){const he=d.outboundAudioRtp.get(I.outboundAudioRtpId[0]);he.score=Qp({packetsSent:(he.packetsSent||0)-(((Hc=this.audioProducerToStatsMap.get(T))==null?void 0:Hc.packetsSent)||0),packetsLost:(((qc=he.remoteData)==null?void 0:qc.packetsLost)||0)-(((Gc=(jc=this.audioProducerToStatsMap.get(T))==null?void 0:jc.remoteData)==null?void 0:Gc.packetsLost)||0),jitter:((Wc=he.remoteData)==null?void 0:Wc.jitter)||0}),S.set(T,{score:+(he.score*10).toFixed(),bitrate:((he.bytesSent||0)-(((Jc=this.audioProducerToStatsMap.get(T))==null?void 0:Jc.bytesSent)||0))*8/7,packetsLostPercentage:cd({packetsSent:(he.packetsSent||0)-(((Kc=this.audioProducerToStatsMap.get(T))==null?void 0:Kc.packetsSent)||0),packetsLost:(((zc=he.remoteData)==null?void 0:zc.packetsLost)||0)-(((Qc=(Yc=this.audioProducerToStatsMap.get(T))==null?void 0:Yc.remoteData)==null?void 0:Qc.packetsLost)||0)}),jitter:((Xc=he.remoteData)==null?void 0:Xc.jitter)||0,isScreenShare:this.screenShareProducers.has(T)}),this.audioProducerToStatsMap.set(T,he)}}),g.forEach(I=>{const T=u.find($=>$.id===I.localCandidateId?(I.localCandidateId=$.id,$):null),P=h.find($=>$.id===I.remoteCandidateId?(I.remoteCandidateId=$.id,$):null);T&&(I.localCandidateType=T.type,I.localCandidateAddress=Vr(T.address),I.localCandidatePort=T.port,I.localCandidateProtocol=T.protocol,I.localCandidateUrl=T.url,I.localCandidateNetworkType=T.networkType,I.localCandidateRelatedAddress=Vr(T.relatedAddress),I.localCandidateRelatedPort=T.relatedPort),P&&(I.remoteCandidateType=P.type,I.remoteCandidateAddress=Vr(P.address),I.remoteCandidatePort=P.port,I.remoteCandidateProtocol=P.protocol,I.remoteCandidateUrl=P.url)}),d.candidatePair&&(d.transport?(d.transport.bytesReceived=d.candidatePair.bytesReceived,d.transport.bytesSent=d.candidatePair.bytesSent,d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.availableIncomingBitrate=d.candidatePair.availableIncomingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:d.candidatePair.availableIncomingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=g),d.transport&&!d.transport.roundTripTime){let I=0,T=0;d.remoteInboundRtp.forEach((P,$)=>{P.roundTripTime&&P.roundTripTime>I&&(I=P.roundTripTime,T=P.totalRoundTripTime)}),d.transport.roundTripTime=I,d.transport.totalRoundTripTime=T}if(y.size>0)try{this.observer.emit("consumer_score",y)}catch(I){}if(S.size>0)try{this.observer.emit("producer_score",S)}catch(I){}return d}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((i,n)=>{const o=this.producerMap.get(n),c=o.track.getSettings(),d=i.outboundVideoRtpId.map(u=>{const h=e.outboundVideoRtp.get(u);return h.frameHeight||(h.frameHeight=c.height,h.frameWidth=c.width,h.framesPerSecond=c.frameRate),h}),l={producerId:n,appData:o.appData,videoStats:d,audioStats:i.outboundAudioRtpId.map(u=>e.outboundAudioRtp.get(u))};r.push(l)})}catch(i){console.error("getProducersReport: ",i,e)}return r}getConsumerStatsFromParsedConsumerStats(e,r,i){let n;try{const{peerId:o,producerId:c,appData:d}=this.consumerPeerIdMap.get(i),l=r==null?void 0:r.inboundVideoRtpId.map(u=>{const g=this.consumerMap.get(i).track.getSettings(),S=e.inboundVideoRtp.get(u);return S.frameHeight||(S.frameHeight=g.height,S.frameWidth=g.width,S.framesPerSecond=g.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 MT extends og{}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 cg(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 Q=(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},OT=(s,t)=>(e,r,i)=>{if(i)return cg(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,cg(o,s,t))}};var z=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 Y=console;let J=class extends dt{constructor(e="https://api.testingv3.dyte.in",r="Blink",i=Za.PROD,n,o,c,d){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",{});switch(this.env=i,this.apiHostnames=d,this.logger=o,this.peerId=c,this.eventHandler=new fT({logger:o,peerId:c,apiHostnames:d}),this.logger.debug("callStats::engineName: ",{engineName:r}),r){case"Blink":this.measurements=new AT;break;case"Gecko":this.measurements=new og;break;case"WebKit":this.measurements=new MT;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 dt,this.measurements.observer.on("consumer_score",l=>{o.debug(`callStats::consumer_score ${[...l.entries()]}`),this.eventHandler.emit("consumer_score",l)}),this.measurements.observer.on("producer_score",l=>{o.debug(`callStats::producer_score ${[...l.entries()]}`),this.eventHandler.emit("producer_score",l)})}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:N.PRECALL_TEST_BEGIN,timestamp:r}),this.connectionInfoPromise&&this.connectionInfoPromise.then(i=>{this.eventHandler.callEvent({event:N.PRECALL_TEST_COMPLETE,metaData:{connectionInfo:i},timestamp:r})})}sendScreenShareToggleEvent(e,r=null,i){this.currentUserMediaStates.screen=e,this.eventHandler.callEvent({event:e?N.SCREENSHARE_STARTED:N.SCREENSHARE_STOPPED,metaData:{ssrc:r},timestamp:i})}sendScreenShareRequestedEvent(e){this.eventHandler.callEvent({event:N.SCREENSHARE_START_REQUESTED,timestamp:e})}sendActiveSpeakerEvent(e,r){this.eventHandler.callEvent({event:N.DOMINANT_SPEAKER,metaData:{peerId:e},timestamp:r})}devices(e,r,i){this.eventHandler.callEvent({event:e===ss.AUDIO&&N.AUDIO_DEVICES_UPDATES||e===ss.VIDEO&&N.VIDEO_DEVICES_UPDATES||e===ss.SPEAKER&&N.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:r},timestamp:i})}selectedDevice(e,r,i){this.eventHandler.callEvent({event:e===ss.AUDIO&&N.SELECTED_MICROHPONE_UPDATE||e===ss.VIDEO&&N.SELECTED_CAMERA_UPDATE||e===ss.SPEAKER&&N.SELECTED_SPEAKER_UPDATE,metaData:{device:r},timestamp:i})}mediaPermission(e,r,i){this.eventHandler.callEvent({event:N.MEDIA_PERMISSION,metaData:{deviceType:e,permission:r},timestamp:i})}mediaPlaybackFailed(e,r){this.eventHandler.callEvent({event:e===ss.AUDIO&&N.AUDIO_PLAY_FAILED||e===ss.VIDEO&&N.VIDEO_PLAY_FAILED,metaData:{deviceType:e},timestamp:r})}mediaTrackMuted(e,r){this.eventHandler.callEvent({event:e===ss.AUDIO&&N.AUDIO_TRACK_MUTED||e===ss.VIDEO&&N.VIDEO_TRACK_MUTED,metaData:{deviceType:e},timestamp:r})}tabChanged(e,r){this.eventHandler.callEvent({event:N.TAB_CHANGE,metaData:{isMeetingsTabActive:e},timestamp:r})}browserBackgrounded(e){this.eventHandler.callEvent({event:N.BROWSER_BACKGROUNDED,timestamp:e})}browserForegrounded(e){this.eventHandler.callEvent({event:N.BROWSER_FOREGROUNDED,timestamp:e})}legacySwitch(e,r){this.eventHandler.callEvent({event:N.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:N.CALL_JOIN_BEGIN,metaData:{peerMetaData:e},timestamp:r})}sendNetworkQualityTestBeginEvent(e,r){this.eventHandler.callEvent({event:N.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:N.NET_QUALITY_TEST_END,timestamp:r,metaData:n})})}sendWebSocketConnectedEvent(e){this.eventHandler.callEvent({event:N.WEBSOCKET_CONNECTED,timestamp:e})}sendTransportConnectedEvent(e){this.eventHandler.callEvent({event:N.TRANSPORT_CONNECTED,timestamp:e})}sendAudioToggleEvent(e,r){this.currentUserMediaStates.audio=e;let i;e?i=N.AUDIO_ON:i=N.AUDIO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendVideoToggleEvent(e,r){this.currentUserMediaStates.video=e;let i;e?i=N.VIDEO_ON:i=N.VIDEO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendParticipantRoleToggleEvent(e,r){this.eventHandler.callEvent({event:N.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:N.PING_STAT,metaData:o,timestamp:r})}sendIVSPlayerRebufferEvent(e){this.eventHandler.callEvent({event:N.IVS_PLAYER_REBUFFERING,timestamp:e})}sendIVSPlayerAudioBlockEvent(e){this.eventHandler.callEvent({event:N.IVS_PLAYER_AUDIO_BLOCKED,timestamp:e})}sendIVSPlayerPlaybackBlockedEvent(e){this.eventHandler.callEvent({event:N.IVS_PLAYER_PLAYBACK_BLOCKED,timestamp:e})}sendIVSPlayerNetworkUnavailableEvent(e){this.eventHandler.callEvent({event:N.IVS_PLAYER_NETWORK_UNAVAILABLE,timestamp:e})}sendIVSPlayerInitializedEvent(e){this.eventHandler.callEvent({event:N.IVS_PLAYER_INITIALIZED,timestamp:e})}sendIVSPlayerWorkerErrorEvent(e){this.eventHandler.callEvent({event:N.IVS_PLAYER_WORKER_ERROR,timestamp:e})}sendIVSPlayerErrorEvent(e,r){this.eventHandler.callEvent({event:N.IVS_PLAYER_ERROR,timestamp:r,metaData:e})}sendIVSPlayerRecoverableErrorEvent(e,r){this.eventHandler.callEvent({event:N.IVS_PLAYER_RECOVERABLE_ERROR,timestamp:r,metaData:e})}sendIVSPlayerAnalyticsEvent(e,r){this.eventHandler.callEvent({event:N.IVS_PLAYER_ANALYTICS_EVENT,timestamp:r,metaData:e})}sendIVSPlayerPlaybackRateChangedEvent(e,r){this.eventHandler.callEvent({event:N.IVS_PLAYER_PLAYBACK_RATE_CHANGED,timestamp:r,metaData:{updatedPlaybackRate:e}})}sendIVSPlayerQualityChanged(e,r){this.eventHandler.callEvent({event:N.IVS_PLAYER_QUALITY_CHANGED,timestamp:r,metaData:e})}sendPlayerLiveLatency(e,r){this.eventHandler.callEvent({event:N.LIVESTREAM_LATENCY,timestamp:r,metaData:{latency:e}})}sendDisconnectEvent(e){this.eventHandler.callEvent({event:N.DISCONNECT,timestamp:e})}sendReconnectEvent(e){this.eventHandler.callEvent({event:N.RECONNECT_ATTEMPT,timestamp:e})}expectedVideoResolution(e,r,i){this.eventHandler.callEvent({event:N.EXPECTED_VIDEO_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}expectedScreenshareResolution(e,r,i){this.eventHandler.callEvent({event:N.EXPECTED_SCREENSHARE_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}};z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"registerIceServers",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"registerConsumer",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"registerProducer",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendConsumerSharedMediaStateEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"registerProducingTransport",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"registerConsumingTransport",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"deRegisterConsumer",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"deRegisterProducer",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"disconnectConsumingTransport",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"disconnectProducingTransport",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendPreCallTestBeginEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendScreenShareToggleEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendScreenShareRequestedEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendActiveSpeakerEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"devices",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"selectedDevice",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"mediaPermission",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"mediaPlaybackFailed",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"mediaTrackMuted",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"tabChanged",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"browserBackgrounded",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"browserForegrounded",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"legacySwitch",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"getPreCallTestResults",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendCallJoinBeginEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendNetworkQualityTestBeginEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendWebSocketConnectedEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendTransportConnectedEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendAudioToggleEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendVideoToggleEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendParticipantRoleToggleEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"startPingStats",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"stopPingStats",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendPingStatsEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendIVSPlayerRebufferEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendIVSPlayerAudioBlockEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendIVSPlayerPlaybackBlockedEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendIVSPlayerNetworkUnavailableEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendIVSPlayerInitializedEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendIVSPlayerWorkerErrorEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendIVSPlayerErrorEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendIVSPlayerRecoverableErrorEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendIVSPlayerAnalyticsEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendIVSPlayerQualityChanged",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendPlayerLiveLatency",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendDisconnectEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"sendReconnectEvent",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"expectedVideoResolution",null),z([Q(TypeError,(s,t)=>Y.error(t,s))],J.prototype,"expectedScreenshareResolution",null),J=z([OT(TypeError,(s,t)=>Y.error(t,s))],J);const DT=J;class dg extends dt{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=Za.PROD,iceServers:n,apiBase:o="https://api.cluster.dyte.in",flags:c,logger:d=console,apiHostnames:l,skipConnectivityChecks:u=!1}){var h,g,S;try{this.peerId=e,this.logger=d,this.ipInformation=await Pu.getIPDetails({peerId:e,apiHostnames:l,logger:d}),this.backend=new DT(o,r,i,c,d,e,l),this.iceServers=n,(h=this.backend)==null||h.registerIceServers(this.iceServers),this.initialized=!0,(S=(g=this.backend)==null?void 0:g.eventHandler)==null||S.emit("initialized",this.ipInformation),this.emit("initialized",this.ipInformation),this.startPreCallTest(u)}catch(y){this.logger.error("callStats::CallStatsIntegration: ",{error:y}),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,g,S,y,w;switch(e){case"PlayerRebuffering":(n=this.backend)==null||n.sendIVSPlayerRebufferEvent(i);break;case"PlayerAudioBlocked":(o=this.backend)==null||o.sendIVSPlayerAudioBlockEvent(i);break;case"PlayerPlaybackBlocked":(c=this.backend)==null||c.sendIVSPlayerPlaybackBlockedEvent(i);break;case"PlayerNetworkUnavailable":(d=this.backend)==null||d.sendIVSPlayerNetworkUnavailableEvent(i);break;case"PlayerInitialized":(l=this.backend)==null||l.sendIVSPlayerInitializedEvent(i);break;case"PlayerWorkerError":(u=this.backend)==null||u.sendIVSPlayerWorkerErrorEvent(i);break;case"PlayerError":(h=this.backend)==null||h.sendIVSPlayerErrorEvent(r,i);break;case"PlayerRecoverableError":(g=this.backend)==null||g.sendIVSPlayerRecoverableErrorEvent(r,i);break;case"PlayerAnalyticsEvent":(S=this.backend)==null||S.sendIVSPlayerAnalyticsEvent(r,i);break;case"PlayerPlaybackRateChanged":(y=this.backend)==null||y.sendIVSPlayerPlaybackRateChangedEvent(r,i);break;case"PlayerQualityChanged":(w=this.backend)==null||w.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 dg().setMaxListeners(30);function NT(){this.__data__=[],this.size=0}function eo(s,t){return s===t||s!==s&&t!==t}function gd(s,t){for(var e=s.length;e--;)if(eo(s[e][0],t))return e;return-1}var VT=Array.prototype,LT=VT.splice;function xT(s){var t=this.__data__,e=gd(t,s);if(e<0)return!1;var r=t.length-1;return e==r?t.pop():LT.call(t,e,1),--this.size,!0}function UT(s){var t=this.__data__,e=gd(t,s);return e<0?void 0:t[e][1]}function FT(s){return gd(this.__data__,s)>-1}function $T(s,t){var e=this.__data__,r=gd(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=NT,Zs.prototype.delete=xT,Zs.prototype.get=UT,Zs.prototype.has=FT,Zs.prototype.set=$T;function BT(){this.__data__=new Zs,this.size=0}function HT(s){var t=this.__data__,e=t.delete(s);return this.size=t.size,e}function qT(s){return this.__data__.get(s)}function jT(s){return this.__data__.has(s)}var GT=typeof global=="object"&&global&&global.Object===Object&&global;const lg=GT;var WT=typeof self=="object"&&self&&self.Object===Object&&self,JT=lg||WT||Function("return this")();const vs=JT;var KT=vs.Symbol;const $s=KT;var ug=Object.prototype,zT=ug.hasOwnProperty,YT=ug.toString,to=$s?$s.toStringTag:void 0;function QT(s){var t=zT.call(s,to),e=s[to];try{s[to]=void 0;var r=!0}catch(n){}var i=YT.call(s);return r&&(t?s[to]=e:delete s[to]),i}var XT=Object.prototype,ZT=XT.toString;function ey(s){return ZT.call(s)}var ty="[object Null]",sy="[object Undefined]",hg=$s?$s.toStringTag:void 0;function Si(s){return s==null?s===void 0?sy:ty:hg&&hg in Object(s)?QT(s):ey(s)}function rs(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var ry="[object AsyncFunction]",iy="[object Function]",ny="[object GeneratorFunction]",ay="[object Proxy]";function _u(s){if(!rs(s))return!1;var t=Si(s);return t==iy||t==ny||t==ry||t==ay}var oy=vs["__core-js_shared__"];const Ru=oy;var pg=function(){var s=/[^.]+$/.exec(Ru&&Ru.keys&&Ru.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function cy(s){return!!pg&&pg in s}var dy=Function.prototype,ly=dy.toString;function vi(s){if(s!=null){try{return ly.call(s)}catch(t){}try{return s+""}catch(t){}}return""}var uy=/[\\^$.*+?()[\]{}|]/g,hy=/^\[object .+?Constructor\]$/,py=Function.prototype,gy=Object.prototype,my=py.toString,fy=gy.hasOwnProperty,Sy=RegExp("^"+my.call(fy).replace(uy,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function vy(s){if(!rs(s)||cy(s))return!1;var t=_u(s)?Sy:hy;return t.test(vi(s))}function Ty(s,t){return s==null?void 0:s[t]}function Ti(s,t){var e=Ty(s,t);return vy(e)?e:void 0}var yy=Ti(vs,"Map");const so=yy;var Ey=Ti(Object,"create");const ro=Ey;function wy(){this.__data__=ro?ro(null):{},this.size=0}function by(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var Py="__lodash_hash_undefined__",_y=Object.prototype,Ry=_y.hasOwnProperty;function Cy(s){var t=this.__data__;if(ro){var e=t[s];return e===Py?void 0:e}return Ry.call(t,s)?t[s]:void 0}var ky=Object.prototype,Iy=ky.hasOwnProperty;function Ay(s){var t=this.__data__;return ro?t[s]!==void 0:Iy.call(t,s)}var My="__lodash_hash_undefined__";function Oy(s,t){var e=this.__data__;return this.size+=this.has(s)?0:1,e[s]=ro&&t===void 0?My:t,this}function yi(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])}}yi.prototype.clear=wy,yi.prototype.delete=by,yi.prototype.get=Cy,yi.prototype.has=Ay,yi.prototype.set=Oy;function Dy(){this.size=0,this.__data__={hash:new yi,map:new(so||Zs),string:new yi}}function Ny(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 Ny(t)?e[typeof t=="string"?"string":"hash"]:e.map}function Vy(s){var t=md(this,s).delete(s);return this.size-=t?1:0,t}function Ly(s){return md(this,s).get(s)}function xy(s){return md(this,s).has(s)}function Uy(s,t){var e=md(this,s),r=e.size;return e.set(s,t),this.size+=e.size==r?0:1,this}function er(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])}}er.prototype.clear=Dy,er.prototype.delete=Vy,er.prototype.get=Ly,er.prototype.has=xy,er.prototype.set=Uy;var Fy=200;function $y(s,t){var e=this.__data__;if(e instanceof Zs){var r=e.__data__;if(!so||r.length<Fy-1)return r.push([s,t]),this.size=++e.size,this;e=this.__data__=new er(r)}return e.set(s,t),this.size=e.size,this}function Ts(s){var t=this.__data__=new Zs(s);this.size=t.size}Ts.prototype.clear=BT,Ts.prototype.delete=HT,Ts.prototype.get=qT,Ts.prototype.has=jT,Ts.prototype.set=$y;function By(s,t){for(var e=-1,r=s==null?0:s.length;++e<r&&t(s[e],e,s)!==!1;);return s}var Hy=function(){try{var s=Ti(Object,"defineProperty");return s({},"",{}),s}catch(t){}}();const fd=Hy;function Cu(s,t,e){t=="__proto__"&&fd?fd(s,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):s[t]=e}var qy=Object.prototype,jy=qy.hasOwnProperty;function gg(s,t,e){var r=s[t];(!(jy.call(s,t)&&eo(r,e))||e===void 0&&!(t in s))&&Cu(s,t,e)}function io(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?Cu(e,c,d):gg(e,c,d)}return e}function Gy(s,t){for(var e=-1,r=Array(s);++e<s;)r[e]=t(e);return r}function Bs(s){return s!=null&&typeof s=="object"}var Wy="[object Arguments]";function mg(s){return Bs(s)&&Si(s)==Wy}var fg=Object.prototype,Jy=fg.hasOwnProperty,Ky=fg.propertyIsEnumerable,zy=mg(function(){return arguments}())?mg:function(s){return Bs(s)&&Jy.call(s,"callee")&&!Ky.call(s,"callee")};const no=zy;var Yy=Array.isArray;const Ft=Yy;function Qy(){return!1}var Sg=typeof exports=="object"&&exports&&!exports.nodeType&&exports,vg=Sg&&typeof module=="object"&&module&&!module.nodeType&&module,Xy=vg&&vg.exports===Sg,Tg=Xy?vs.Buffer:void 0,Zy=Tg?Tg.isBuffer:void 0,eE=Zy||Qy;const kn=eE;var tE=9007199254740991,sE=/^(?:0|[1-9]\d*)$/;function ku(s,t){var e=typeof s;return t=t==null?tE:t,!!t&&(e=="number"||e!="symbol"&&sE.test(s))&&s>-1&&s%1==0&&s<t}var rE=9007199254740991;function Iu(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=rE}var iE="[object Arguments]",nE="[object Array]",aE="[object Boolean]",oE="[object Date]",cE="[object Error]",dE="[object Function]",lE="[object Map]",uE="[object Number]",hE="[object Object]",pE="[object RegExp]",gE="[object Set]",mE="[object String]",fE="[object WeakMap]",SE="[object ArrayBuffer]",vE="[object DataView]",TE="[object Float32Array]",yE="[object Float64Array]",EE="[object Int8Array]",wE="[object Int16Array]",bE="[object Int32Array]",PE="[object Uint8Array]",_E="[object Uint8ClampedArray]",RE="[object Uint16Array]",CE="[object Uint32Array]",ve={};ve[TE]=ve[yE]=ve[EE]=ve[wE]=ve[bE]=ve[PE]=ve[_E]=ve[RE]=ve[CE]=!0,ve[iE]=ve[nE]=ve[SE]=ve[aE]=ve[vE]=ve[oE]=ve[cE]=ve[dE]=ve[lE]=ve[uE]=ve[hE]=ve[pE]=ve[gE]=ve[mE]=ve[fE]=!1;function kE(s){return Bs(s)&&Iu(s.length)&&!!ve[Si(s)]}function Au(s){return function(t){return s(t)}}var yg=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ao=yg&&typeof module=="object"&&module&&!module.nodeType&&module,IE=ao&&ao.exports===yg,Mu=IE&&lg.process,AE=function(){try{var s=ao&&ao.require&&ao.require("util").types;return s||Mu&&Mu.binding&&Mu.binding("util")}catch(t){}}();const In=AE;var Eg=In&&In.isTypedArray,ME=Eg?Au(Eg):kE;const Sd=ME;var OE=Object.prototype,DE=OE.hasOwnProperty;function wg(s,t){var e=Ft(s),r=!e&&no(s),i=!e&&!r&&kn(s),n=!e&&!r&&!i&&Sd(s),o=e||r||i||n,c=o?Gy(s.length,String):[],d=c.length;for(var l in s)(t||DE.call(s,l))&&!(o&&(l=="length"||i&&(l=="offset"||l=="parent")||n&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||ku(l,d)))&&c.push(l);return c}var NE=Object.prototype;function vd(s){var t=s&&s.constructor,e=typeof t=="function"&&t.prototype||NE;return s===e}function bg(s,t){return function(e){return s(t(e))}}var VE=bg(Object.keys,Object);const LE=VE;var xE=Object.prototype,UE=xE.hasOwnProperty;function Pg(s){if(!vd(s))return LE(s);var t=[];for(var e in Object(s))UE.call(s,e)&&e!="constructor"&&t.push(e);return t}function oo(s){return s!=null&&Iu(s.length)&&!_u(s)}function Td(s){return oo(s)?wg(s):Pg(s)}function FE(s,t){return s&&io(t,Td(t),s)}function $E(s){var t=[];if(s!=null)for(var e in Object(s))t.push(e);return t}var BE=Object.prototype,HE=BE.hasOwnProperty;function qE(s){if(!rs(s))return $E(s);var t=vd(s),e=[];for(var r in s)r=="constructor"&&(t||!HE.call(s,r))||e.push(r);return e}function co(s){return oo(s)?wg(s,!0):qE(s)}function jE(s,t){return s&&io(t,co(t),s)}var _g=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Rg=_g&&typeof module=="object"&&module&&!module.nodeType&&module,GE=Rg&&Rg.exports===_g,Cg=GE?vs.Buffer:void 0,kg=Cg?Cg.allocUnsafe:void 0;function Ig(s,t){if(t)return s.slice();var e=s.length,r=kg?kg(e):new s.constructor(e);return s.copy(r),r}function Ag(s,t){var e=-1,r=s.length;for(t||(t=Array(r));++e<r;)t[e]=s[e];return t}function WE(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 Mg(){return[]}var JE=Object.prototype,KE=JE.propertyIsEnumerable,Og=Object.getOwnPropertySymbols,zE=Og?function(s){return s==null?[]:(s=Object(s),WE(Og(s),function(t){return KE.call(s,t)}))}:Mg;const Ou=zE;function YE(s,t){return io(s,Ou(s),t)}function Dg(s,t){for(var e=-1,r=t.length,i=s.length;++e<r;)s[i+e]=t[e];return s}var QE=bg(Object.getPrototypeOf,Object);const Du=QE;var XE=Object.getOwnPropertySymbols,ZE=XE?function(s){for(var t=[];s;)Dg(t,Ou(s)),s=Du(s);return t}:Mg;const Ng=ZE;function ew(s,t){return io(s,Ng(s),t)}function Vg(s,t,e){var r=t(s);return Ft(s)?r:Dg(r,e(s))}function Nu(s){return Vg(s,Td,Ou)}function tw(s){return Vg(s,co,Ng)}var sw=Ti(vs,"DataView");const Vu=sw;var rw=Ti(vs,"Promise");const Lu=rw;var iw=Ti(vs,"Set");const An=iw;var nw=Ti(vs,"WeakMap");const xu=nw;var Lg="[object Map]",aw="[object Object]",xg="[object Promise]",Ug="[object Set]",Fg="[object WeakMap]",$g="[object DataView]",ow=vi(Vu),cw=vi(so),dw=vi(Lu),lw=vi(An),uw=vi(xu),Ei=Si;(Vu&&Ei(new Vu(new ArrayBuffer(1)))!=$g||so&&Ei(new so)!=Lg||Lu&&Ei(Lu.resolve())!=xg||An&&Ei(new An)!=Ug||xu&&Ei(new xu)!=Fg)&&(Ei=function(s){var t=Si(s),e=t==aw?s.constructor:void 0,r=e?vi(e):"";if(r)switch(r){case ow:return $g;case cw:return Lg;case dw:return xg;case lw:return Ug;case uw:return Fg}return t});const Mn=Ei;var hw=Object.prototype,pw=hw.hasOwnProperty;function gw(s){var t=s.length,e=new s.constructor(t);return t&&typeof s[0]=="string"&&pw.call(s,"index")&&(e.index=s.index,e.input=s.input),e}var mw=vs.Uint8Array;const yd=mw;function Uu(s){var t=new s.constructor(s.byteLength);return new yd(t).set(new yd(s)),t}function fw(s,t){var e=t?Uu(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.byteLength)}var Sw=/\w*$/;function vw(s){var t=new s.constructor(s.source,Sw.exec(s));return t.lastIndex=s.lastIndex,t}var Bg=$s?$s.prototype:void 0,Hg=Bg?Bg.valueOf:void 0;function Tw(s){return Hg?Object(Hg.call(s)):{}}function qg(s,t){var e=t?Uu(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.length)}var yw="[object Boolean]",Ew="[object Date]",ww="[object Map]",bw="[object Number]",Pw="[object RegExp]",_w="[object Set]",Rw="[object String]",Cw="[object Symbol]",kw="[object ArrayBuffer]",Iw="[object DataView]",Aw="[object Float32Array]",Mw="[object Float64Array]",Ow="[object Int8Array]",Dw="[object Int16Array]",Nw="[object Int32Array]",Vw="[object Uint8Array]",Lw="[object Uint8ClampedArray]",xw="[object Uint16Array]",Uw="[object Uint32Array]";function Fw(s,t,e){var r=s.constructor;switch(t){case kw:return Uu(s);case yw:case Ew:return new r(+s);case Iw:return fw(s,e);case Aw:case Mw:case Ow:case Dw:case Nw:case Vw:case Lw:case xw:case Uw:return qg(s,e);case ww:return new r;case bw:case Rw:return new r(s);case Pw:return vw(s);case _w:return new r;case Cw:return Tw(s)}}var jg=Object.create,$w=function(){function s(){}return function(t){if(!rs(t))return{};if(jg)return jg(t);s.prototype=t;var e=new s;return s.prototype=void 0,e}}();const Bw=$w;function Gg(s){return typeof s.constructor=="function"&&!vd(s)?Bw(Du(s)):{}}var Hw="[object Map]";function qw(s){return Bs(s)&&Mn(s)==Hw}var Wg=In&&In.isMap,jw=Wg?Au(Wg):qw;const Gw=jw;var Ww="[object Set]";function Jw(s){return Bs(s)&&Mn(s)==Ww}var Jg=In&&In.isSet,Kw=Jg?Au(Jg):Jw;const zw=Kw;var Yw=1,Qw=2,Xw=4,Kg="[object Arguments]",Zw="[object Array]",eb="[object Boolean]",tb="[object Date]",sb="[object Error]",zg="[object Function]",rb="[object GeneratorFunction]",ib="[object Map]",nb="[object Number]",Yg="[object Object]",ab="[object RegExp]",ob="[object Set]",cb="[object String]",db="[object Symbol]",lb="[object WeakMap]",ub="[object ArrayBuffer]",hb="[object DataView]",pb="[object Float32Array]",gb="[object Float64Array]",mb="[object Int8Array]",fb="[object Int16Array]",Sb="[object Int32Array]",vb="[object Uint8Array]",Tb="[object Uint8ClampedArray]",yb="[object Uint16Array]",Eb="[object Uint32Array]",pe={};pe[Kg]=pe[Zw]=pe[ub]=pe[hb]=pe[eb]=pe[tb]=pe[pb]=pe[gb]=pe[mb]=pe[fb]=pe[Sb]=pe[ib]=pe[nb]=pe[Yg]=pe[ab]=pe[ob]=pe[cb]=pe[db]=pe[vb]=pe[Tb]=pe[yb]=pe[Eb]=!0,pe[sb]=pe[zg]=pe[lb]=!1;function lo(s,t,e,r,i,n){var o,c=t&Yw,d=t&Qw,l=t&Xw;if(e&&(o=i?e(s,r,i,n):e(s)),o!==void 0)return o;if(!rs(s))return s;var u=Ft(s);if(u){if(o=gw(s),!c)return Ag(s,o)}else{var h=Mn(s),g=h==zg||h==rb;if(kn(s))return Ig(s,c);if(h==Yg||h==Kg||g&&!i){if(o=d||g?{}:Gg(s),!c)return d?ew(s,jE(o,s)):YE(s,FE(o,s))}else{if(!pe[h])return i?s:{};o=Fw(s,h,c)}}n||(n=new Ts);var S=n.get(s);if(S)return S;n.set(s,o),zw(s)?s.forEach(function(b){o.add(lo(b,t,e,b,s,n))}):Gw(s)&&s.forEach(function(b,C){o.set(C,lo(b,t,e,C,s,n))});var y=l?d?tw:Nu:d?co:Td,w=u?void 0:y(s);return By(w||s,function(b,C){w&&(C=b,b=s[C]),gg(o,C,lo(b,t,e,C,s,n))}),o}var wb=1,bb=4;function Fu(s){return lo(s,wb|bb)}var Pb="[object Symbol]";function Ed(s){return typeof s=="symbol"||Bs(s)&&Si(s)==Pb}var _b=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Rb=/^\w*$/;function $u(s,t){if(Ft(s))return!1;var e=typeof s;return e=="number"||e=="symbol"||e=="boolean"||s==null||Ed(s)?!0:Rb.test(s)||!_b.test(s)||t!=null&&s in Object(t)}var Cb="Expected a function";function Bu(s,t){if(typeof s!="function"||t!=null&&typeof t!="function")throw new TypeError(Cb);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(Bu.Cache||er),e}Bu.Cache=er;var kb=500;function Ib(s){var t=Bu(s,function(r){return e.size===kb&&e.clear(),r}),e=t.cache;return t}var Ab=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Mb=/\\(\\)?/g,Ob=Ib(function(s){var t=[];return s.charCodeAt(0)===46&&t.push(""),s.replace(Ab,function(e,r,i,n){t.push(i?n.replace(Mb,"$1"):r||e)}),t});const Db=Ob;function Nb(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 Vb=1/0,Qg=$s?$s.prototype:void 0,Xg=Qg?Qg.toString:void 0;function Zg(s){if(typeof s=="string")return s;if(Ft(s))return Nb(s,Zg)+"";if(Ed(s))return Xg?Xg.call(s):"";var t=s+"";return t=="0"&&1/s==-Vb?"-0":t}function Lb(s){return s==null?"":Zg(s)}function em(s,t){return Ft(s)?s:$u(s,t)?[s]:Db(Lb(s))}var xb=1/0;function wd(s){if(typeof s=="string"||Ed(s))return s;var t=s+"";return t=="0"&&1/s==-xb?"-0":t}function tm(s,t){t=em(t,s);for(var e=0,r=t.length;s!=null&&e<r;)s=s[wd(t[e++])];return e&&e==r?s:void 0}function Ub(s,t,e){var r=s==null?void 0:tm(s,t);return r===void 0?e:r}function Fb(s,t,e){t=em(t,s);for(var r=-1,i=t.length,n=!1;++r<i;){var o=wd(t[r]);if(!(n=s!=null&&e(s,o)))break;s=s[o]}return n||++r!=i?n:(i=s==null?0:s.length,!!i&&Iu(i)&&ku(o,i)&&(Ft(s)||no(s)))}var tr=(s=>(s.GroupCall="GROUP_CALL",s.Webinar="WEBINAR",s.AudioRoom="AUDIO_ROOM",s.Livestream="LIVESTREAM",s.Chat="CHAT",s))(tr||{}),H=(s=>(s.Allowed="ALLOWED",s.NotAllowed="NOT_ALLOWED",s.CanRequest="CAN_REQUEST",s))(H||{}),sm="hXgU8Wc8pwuGNq9ms5q9Hh";typeof process!="undefined"&&(BS=process==null?void 0:process.env)!=null&&BS.FLAGSMITH_ENVIRONMENT_KEY&&(sm=process.env.FLAGSMITH_ENVIRONMENT_KEY);function $b(s=[]){const t={};return s.forEach(e=>{t[e.feature.name]={enabled:e.enabled,value:e.feature_state_value}}),t}var rm=class{constructor(s=sm){p(this,"flags",{});p(this,"environmentKey",null);this.environmentKey=s}async identifyAndFetchFlagsWithRetry({primaryEndpoint:s,secondaryEndpoint:t,forceEvaluate:e,timeout:r,uniqueIdentifier:i,traitsObj:n,logger:o}){const c=JSON.parse(JSON.stringify(n)),d=Object.entries(c).map(u=>({trait_key:u[0],trait_value:u[1]})),l=[s,t,t];for(const u of l)try{const h=new AbortController,g=setTimeout(()=>h.abort(),r),S=`_${(Math.random()+1).toString(36).substring(2)}`,y=await fetch(`https://${u}/api/v1/identities/`,{method:"POST",headers:{"Content-Type":"application/json","X-Environment-Key":this.environmentKey},body:JSON.stringify({identifier:i+(e?S:""),traits:d}),signal:h.signal});if(clearTimeout(g),!y.ok)throw new Error(`Request failed with status ${y.status}`);const w=await y.json();return $b(w.flags||[])}catch(h){o.error("Flagsmith identify failed!!",{error:h,url:u})}return{}}async identify(s,t={},e=!1,r=5e3,i="edge.api.flagsmith.com",n=console){return this.flags=await this.identifyAndFetchFlagsWithRetry({traitsObj:t,uniqueIdentifier:s,forceEvaluate:e,timeout:r,primaryEndpoint:i,secondaryEndpoint:"edge.api.flagsmith.com",logger:n}),this.flags}getValue(s){return this.flags&&this.flags[s]&&this.flags[s].value}hasFeature(s){return this.flags&&this.flags[s]&&this.flags[s].enabled}getAllFlags(){return this.flags}},Bb=new rm;function Hb(s){return new rm(s)}var im=[-2,-1,0,1,2],qb=[0,1,2,3,4];function jb(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 Gb=(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)]},Wb=(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]},Jb=(s,t,e)=>{const r=i=>i.toString(16).padStart(2,"0");return`#${r(s)}${r(t)}${r(e)}`},nm=(s,t=im,e=.4)=>{const r=[],[i,n,o]=jb(s),[c,d,l]=Wb(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(b=>b===0);if(h===-1)throw new Error("Invalid reducer provided, it must contain atleast one zero");const g=5-h,S=h+1,y=(100-u)/g,w=u/S;for(const b of t){let C;b<0?C=u+b*w*e:b>0?C=u+b*y*e:C=u;const[D,F,L]=Gb(c,d,C/100);r.push(Jb(D,F,L))}return r},am={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"}},Kb=s=>{const[t,e,r,i,n]=nm(s,im);return{300:t,400:e,500:r,600:i,700:n}},zb=s=>{if(s==="#FFFFFF")return am.light.background;if(s==="#000000")return am.dark.background;const[t,e,r,i,n]=nm(s,qb);return{1e3:t,900:e,800:r,700:i,600:n}},Yb={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:Kb("#2160FD"),background:zb("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function om(){return Fu(Yb)}var Qb={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:om(),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 Xb(){return Fu(Qb)}var Zb={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:om(),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 Hu(){return Fu(Zb)}class cm{constructor(){m(this,No,void 0)}get telemetry(){var t;return(t=a(this,No))==null?void 0:t.getValue("telemetry")}init(t){f(this,No,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)}}No=new WeakMap;class eP extends dt.EventEmitter{constructor(e){super();m(this,pr,void 0);m(this,gr,void 0);p(this,"asyncPromiseTimeout");p(this,"logger");this.logger=e,f(this,pr,new Map),f(this,gr,new Map),this.asyncPromiseTimeout=8e3}async emitAsync(e,...r){a(this,pr).set(e,[]);const i=a(this,gr).get(e).map(()=>new Promise(n=>{a(this,pr).get(e).push(n)}));super.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,pr).delete(e)}onAsync(e,r){const i=a(this,pr),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,gr).get(e)||a(this,gr).set(e,[]),a(this,gr).get(e).push(n),super.on(e,n)}reset(){f(this,pr,new Map),f(this,gr,new Map),super.removeAllListeners()}}pr=new WeakMap,gr=new WeakMap;var tP=/\s/;function sP(s){for(var t=s.length;t--&&tP.test(s.charAt(t)););return t}var rP=/^\s+/;function iP(s){return s&&s.slice(0,sP(s)+1).replace(rP,"")}var dm=0/0,nP=/^[-+]0x[0-9a-f]+$/i,aP=/^0b[01]+$/i,oP=/^0o[0-7]+$/i,cP=parseInt;function lm(s){if(typeof s=="number")return s;if(Ed(s))return dm;if(rs(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=rs(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=iP(s);var e=aP.test(s);return e||oP.test(s)?cP(s.slice(2),e?2:8):nP.test(s)?dm:+s}function qu(s){return s}function dP(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 lP(){}var uP=800,hP=16,pP=Date.now;function gP(s){var t=0,e=0;return function(){var r=pP(),i=hP-(r-e);if(e=r,i>0){if(++t>=uP)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}function mP(s){return function(){return s}}var fP=fd?function(s,t){return fd(s,"toString",{configurable:!0,enumerable:!1,value:mP(t),writable:!0})}:qu,SP=gP(fP);const vP=SP;function TP(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 yP(s){return s!==s}function EP(s,t,e){for(var r=e-1,i=s.length;++r<i;)if(s[r]===t)return r;return-1}function wP(s,t,e){return t===t?EP(s,t,e):TP(s,yP,e)}function bP(s,t){var e=s==null?0:s.length;return!!e&&wP(s,t,0)>-1}var um=Math.max;function PP(s,t,e){return t=um(t===void 0?s.length-1:t,0),function(){for(var r=arguments,i=-1,n=um(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),dP(s,this,c)}}function _P(s,t){return vP(PP(s,t,qu),s+"")}function RP(s,t,e){if(!rs(e))return!1;var r=typeof t;return(r=="number"?oo(e)&&ku(t,e.length):r=="string"&&t in e)?eo(e[t],s):!1}function CP(s){return _P(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&&RP(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 kP="[object Object]",IP=Function.prototype,AP=Object.prototype,hm=IP.toString,MP=AP.hasOwnProperty,OP=hm.call(Object);function DP(s){if(!Bs(s)||Si(s)!=kP)return!1;var t=Du(s);if(t===null)return!0;var e=MP.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&hm.call(e)==OP}var NP=4;function VP(s){return lo(s,NP)}var LP="__lodash_hash_undefined__";function xP(s){return this.__data__.set(s,LP),this}function UP(s){return this.__data__.has(s)}function uo(s){var t=-1,e=s==null?0:s.length;for(this.__data__=new er;++t<e;)this.add(s[t])}uo.prototype.add=uo.prototype.push=xP,uo.prototype.has=UP;function FP(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 pm(s,t){return s.has(t)}var $P=1,BP=2;function gm(s,t,e,r,i,n){var o=e&$P,c=s.length,d=t.length;if(c!=d&&!(o&&d>c))return!1;var l=n.get(s),u=n.get(t);if(l&&u)return l==t&&u==s;var h=-1,g=!0,S=e&BP?new uo:void 0;for(n.set(s,t),n.set(t,s);++h<c;){var y=s[h],w=t[h];if(r)var b=o?r(w,y,h,t,s,n):r(y,w,h,s,t,n);if(b!==void 0){if(b)continue;g=!1;break}if(S){if(!FP(t,function(C,D){if(!pm(S,D)&&(y===C||i(y,C,e,r,n)))return S.push(D)})){g=!1;break}}else if(!(y===w||i(y,w,e,r,n))){g=!1;break}}return n.delete(s),n.delete(t),g}function HP(s){var t=-1,e=Array(s.size);return s.forEach(function(r,i){e[++t]=[i,r]}),e}function ju(s){var t=-1,e=Array(s.size);return s.forEach(function(r){e[++t]=r}),e}var qP=1,jP=2,GP="[object Boolean]",WP="[object Date]",JP="[object Error]",KP="[object Map]",zP="[object Number]",YP="[object RegExp]",QP="[object Set]",XP="[object String]",ZP="[object Symbol]",e_="[object ArrayBuffer]",t_="[object DataView]",mm=$s?$s.prototype:void 0,Gu=mm?mm.valueOf:void 0;function s_(s,t,e,r,i,n,o){switch(e){case t_:if(s.byteLength!=t.byteLength||s.byteOffset!=t.byteOffset)return!1;s=s.buffer,t=t.buffer;case e_:return!(s.byteLength!=t.byteLength||!n(new yd(s),new yd(t)));case GP:case WP:case zP:return eo(+s,+t);case JP:return s.name==t.name&&s.message==t.message;case YP:case XP:return s==t+"";case KP:var c=HP;case QP:var d=r&qP;if(c||(c=ju),s.size!=t.size&&!d)return!1;var l=o.get(s);if(l)return l==t;r|=jP,o.set(s,t);var u=gm(c(s),c(t),r,i,n,o);return o.delete(s),u;case ZP:if(Gu)return Gu.call(s)==Gu.call(t)}return!1}var r_=1,i_=Object.prototype,n_=i_.hasOwnProperty;function a_(s,t,e,r,i,n){var o=e&r_,c=Nu(s),d=c.length,l=Nu(t),u=l.length;if(d!=u&&!o)return!1;for(var h=d;h--;){var g=c[h];if(!(o?g in t:n_.call(t,g)))return!1}var S=n.get(s),y=n.get(t);if(S&&y)return S==t&&y==s;var w=!0;n.set(s,t),n.set(t,s);for(var b=o;++h<d;){g=c[h];var C=s[g],D=t[g];if(r)var F=o?r(D,C,g,t,s,n):r(C,D,g,s,t,n);if(!(F===void 0?C===D||i(C,D,e,r,n):F)){w=!1;break}b||(b=g=="constructor")}if(w&&!b){var L=s.constructor,B=t.constructor;L!=B&&"constructor"in s&&"constructor"in t&&!(typeof L=="function"&&L instanceof L&&typeof B=="function"&&B instanceof B)&&(w=!1)}return n.delete(s),n.delete(t),w}var o_=1,fm="[object Arguments]",Sm="[object Array]",bd="[object Object]",c_=Object.prototype,vm=c_.hasOwnProperty;function d_(s,t,e,r,i,n){var o=Ft(s),c=Ft(t),d=o?Sm:Mn(s),l=c?Sm:Mn(t);d=d==fm?bd:d,l=l==fm?bd:l;var u=d==bd,h=l==bd,g=d==l;if(g&&kn(s)){if(!kn(t))return!1;o=!0,u=!1}if(g&&!u)return n||(n=new Ts),o||Sd(s)?gm(s,t,e,r,i,n):s_(s,t,d,e,r,i,n);if(!(e&o_)){var S=u&&vm.call(s,"__wrapped__"),y=h&&vm.call(t,"__wrapped__");if(S||y){var w=S?s.value():s,b=y?t.value():t;return n||(n=new Ts),i(w,b,e,r,n)}}return g?(n||(n=new Ts),a_(s,t,e,r,i,n)):!1}function Pd(s,t,e,r,i){return s===t?!0:s==null||t==null||!Bs(s)&&!Bs(t)?s!==s&&t!==t:d_(s,t,e,r,Pd,i)}var l_=1,u_=2;function h_(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 Ts;if(r)var g=r(l,u,d,s,t,h);if(!(g===void 0?Pd(u,l,l_|u_,r,h):g))return!1}}return!0}function Tm(s){return s===s&&!rs(s)}function p_(s){for(var t=Td(s),e=t.length;e--;){var r=t[e],i=s[r];t[e]=[r,i,Tm(i)]}return t}function ym(s,t){return function(e){return e==null?!1:e[s]===t&&(t!==void 0||s in Object(e))}}function g_(s){var t=p_(s);return t.length==1&&t[0][2]?ym(t[0][0],t[0][1]):function(e){return e===s||h_(e,s,t)}}function m_(s,t){return s!=null&&t in Object(s)}function f_(s,t){return s!=null&&Fb(s,t,m_)}var S_=1,v_=2;function T_(s,t){return $u(s)&&Tm(t)?ym(wd(s),t):function(e){var r=Ub(e,s);return r===void 0&&r===t?f_(e,s):Pd(t,r,S_|v_)}}function y_(s){return function(t){return t==null?void 0:t[s]}}function E_(s){return function(t){return tm(t,s)}}function w_(s){return $u(s)?y_(wd(s)):E_(s)}function b_(s){return typeof s=="function"?s:s==null?qu:typeof s=="object"?Ft(s)?T_(s[0],s[1]):g_(s):w_(s)}function P_(s){return function(t,e,r){for(var i=-1,n=Object(t),o=r(t),c=o.length;c--;){var d=o[s?c:++i];if(e(n[d],d,n)===!1)break}return t}}var __=P_();const R_=__;var C_=function(){return vs.Date.now()};const Wu=C_;var k_="Expected a function",I_=Math.max,A_=Math.min;function Ju(s,t,e){var r,i,n,o,c,d,l=0,u=!1,h=!1,g=!0;if(typeof s!="function")throw new TypeError(k_);t=lm(t)||0,rs(e)&&(u=!!e.leading,h="maxWait"in e,n=h?I_(lm(e.maxWait)||0,t):n,g="trailing"in e?!!e.trailing:g);function S(W){var ae=r,Tt=i;return r=i=void 0,l=W,o=s.apply(Tt,ae),o}function y(W){return l=W,c=setTimeout(C,t),u?S(W):o}function w(W){var ae=W-d,Tt=W-l,xs=t-ae;return h?A_(xs,n-Tt):xs}function b(W){var ae=W-d,Tt=W-l;return d===void 0||ae>=t||ae<0||h&&Tt>=n}function C(){var W=Wu();if(b(W))return D(W);c=setTimeout(C,w(W))}function D(W){return c=void 0,g&&r?S(W):(r=i=void 0,o)}function F(){c!==void 0&&clearTimeout(c),l=0,r=d=i=c=void 0}function L(){return c===void 0?o:D(Wu())}function B(){var W=Wu(),ae=b(W);if(r=arguments,i=this,d=W,ae){if(c===void 0)return y(d);if(h)return clearTimeout(c),c=setTimeout(C,t),S(d)}return c===void 0&&(c=setTimeout(C,t)),o}return B.cancel=F,B.flush=L,B}function Ku(s,t,e){(e!==void 0&&!eo(s[t],e)||e===void 0&&!(t in s))&&Cu(s,t,e)}function M_(s){return Bs(s)&&oo(s)}function zu(s,t){if(!(t==="constructor"&&typeof s[t]=="function")&&t!="__proto__")return s[t]}function O_(s){return io(s,co(s))}function D_(s,t,e,r,i,n,o){var c=zu(s,e),d=zu(t,e),l=o.get(d);if(l){Ku(s,e,l);return}var u=n?n(c,d,e+"",s,t,o):void 0,h=u===void 0;if(h){var g=Ft(d),S=!g&&kn(d),y=!g&&!S&&Sd(d);u=d,g||S||y?Ft(c)?u=c:M_(c)?u=Ag(c):S?(h=!1,u=Ig(d,!0)):y?(h=!1,u=qg(d,!0)):u=[]:DP(d)||no(d)?(u=c,no(c)?u=O_(c):(!rs(c)||_u(c))&&(u=Gg(d))):h=!1}h&&(o.set(d,u),i(u,d,r,n,o),o.delete(d)),Ku(s,e,u)}function Em(s,t,e,r,i){s!==t&&R_(t,function(n,o){if(i||(i=new Ts),rs(n))D_(s,t,o,e,Em,r,i);else{var c=r?r(zu(s,o),n,o+"",s,t,i):void 0;c===void 0&&(c=n),Ku(s,o,c)}},co)}function N_(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 V_="[object Map]",L_="[object Set]",x_=Object.prototype,U_=x_.hasOwnProperty;function F_(s){if(s==null)return!0;if(oo(s)&&(Ft(s)||typeof s=="string"||typeof s.splice=="function"||kn(s)||Sd(s)||no(s)))return!s.length;var t=Mn(s);if(t==V_||t==L_)return!s.size;if(vd(s))return!Pg(s).length;for(var e in s)if(U_.call(s,e))return!1;return!0}function $_(s,t){return Pd(s,t)}var B_=CP(function(s,t,e){Em(s,t,e)});const Lr=B_;var H_=1/0,q_=An&&1/ju(new An([,-0]))[1]==H_?function(s){return new An(s)}:lP;const j_=q_;var G_=200;function wm(s,t,e){var r=-1,i=bP,n=s.length,o=!0,c=[],d=c;if(e)o=!1,i=N_;else if(n>=G_){var l=t?null:j_(s);if(l)return ju(l);o=!1,i=pm,d=new uo}else d=t?[]:c;e:for(;++r<n;){var u=s[r],h=t?t(u):u;if(u=e||u!==0?u:0,o&&h===h){for(var g=d.length;g--;)if(d[g]===h)continue e;t&&d.push(h),c.push(u)}else i(d,h,e)||(d!==c&&d.push(h),c.push(u))}return c}function W_(s){return s&&s.length?wm(s):[]}function J_(s,t){return s&&s.length?wm(s,b_(t)):[]}var Yu=(s=>(s.PARTICIPANT="PARTICIPANT",s.PEER="PEER",s.CLIENT="CLIENT",s))(Yu||{});const Z={PROPAGATE_KICK_ALL:"propagate_kick_across_rooms",REFRESH_ID_ON_DISCONNECTION:"refresh_id_on_disconnection",SKIP_OTEL_TRACES:"skip_otel_traces",CF_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED:"cf_transport_force_relay_on_ice_failed",LOG_LEVEL:"log_level",V1_PLUGINS:"v1_plugins",LIVESTREAM:"feat_livestream",VAL_MIN_FRAMERATE:"val_min_framerate",SCREEENSHARE_ERR_HACK:"screenshare_err_hack",SCREEENSHARE_CONSTRAINTS_RETRY:"screenshare_constraints_retry",SCREENSHARE_CONSTRAINTS:"screenshare_constraints",OBS_QUALITY:"obs_quality",ALLOW_SAFARI_MEDIA_MIDDLEWARES:"allow_safari_media_middlewares",EXP_RESHARE:"exp_reshare",SKIP_SETTING_IN_USE_DEVICE:"skip_setting_in_use_device",PRECALL_BANDWIDTH_TEST:"precall_bandwidth_test",DEBUG_SOCKET_JOIN:"debug_socket_join",FORCE_RELAY:"force_relay",FORCE_VIDEO_CODEC:"force_video_codec",TRACK_HINT:"track_hint",PRECREATE_PRODUCERS:"precreate_producers",DISABLE_OPUS_DTX_CF:"disable_opus_dtx_cf",ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS:"enable_audio_activity_debug_logs",DISABLE_LAYER_SWITCH:"disable_layer_switch"};function _d(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 K_={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},ho={baseURL:"http://localhost:5000",createdAt:"2021-08-05T10:49:56.602Z",description:"Develop plugins locally",id:"09259e3b-7be8-46f6-9801-106bf1866e1c",name:"Localhost Dev",organizationId:"4ad15a19-80e2-4105-bf43-48039fd2963e",picture:"https://dyte-uploads.s3.ap-south-1.amazonaws.com/dyte.png",private:!1,published:!0,staggered:!1,tags:["#localhost","#dev"],type:"self_hosted",updatedAt:"2021-08-05T10:50:07.681Z"},z_={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 On(s,t){const e=s.getValue("overrides");return e&&e[t]?e[t]:!1}function Y_({baseURI:s}){return s.includes("preprod.dyte")||s.includes("preprod.realtime")?Za.PREPROD:s.includes("devel.dyte")||s.includes("devel.realtime")?Za.DEVEL:Za.PROD}function wi({servicePrefix:s,baseURI:t}){return`${s}.${t}`}function bm(s){const t=s.getValue("baseURI");return{location:wi({servicePrefix:"location",baseURI:t}),locationLegacy:wi({servicePrefix:"location-legacy",baseURI:t}),daCollector:wi({servicePrefix:"da-collector",baseURI:t})}}const Q_='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="m16.242 2.932 4.826 4.826a2.75 2.75 0 0 1-.715 4.404l-4.87 2.435a.75.75 0 0 0-.374.426l-1.44 4.166a1.25 1.25 0 0 1-2.065.476L8.5 16.561 4.06 21H3v-1.06l4.44-4.44-3.105-3.104a1.25 1.25 0 0 1 .476-2.066l4.166-1.44a.75.75 0 0 0 .426-.373l2.435-4.87a2.75 2.75 0 0 1 4.405-.715Zm3.766 5.886-4.826-4.826a1.25 1.25 0 0 0-2.002.325l-2.435 4.871a2.25 2.25 0 0 1-1.278 1.12l-3.789 1.31 6.705 6.704 1.308-3.789a2.25 2.25 0 0 1 1.12-1.277l4.872-2.436a1.25 1.25 0 0 0 .325-2.002Z" fill="currentColor"/></svg>',X_='<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>',Rd=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})},bi={logs:"https://api-silos.dyte.io/otel/logs",mock:{url:"https://mock.dyte.io",domain:"mock.dyte.io",app:"https://app.dyte.io/v2/meeting",stagingApp:"https://app.devel.dyte.io/v2/meeting"},apiBase:{prod:"https://api.dyte.io",staging:"https://api.devel.dyte.io",prodAlternate:"https://api.cluster.dyte.in"},baseURI:{prod:"dyte.io",staging:"devel.dyte.io"}};function Z_(s){var r,i,n;const t=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((r=window.location.host)==null?void 0:r.includes(bi.baseURI.staging)),e=!!((n=(i=s==null?void 0:s.getValue("modules"))==null?void 0:i.devTools)!=null&&n.logs);return t||e}function eR(s,t){var e;if(s!=null&&s.getValue("flagsmith").hasFeature(Z.LOG_LEVEL)){let r=((e=s.getValue("flagsmith").getValue(Z.LOG_LEVEL))==null?void 0:e.toString())||"all";if(r=r.toLowerCase().trim(),r==="off")return!1;if(r!=="all"){const i=["debug","log","info","warn","error"],n=i.indexOf(t),o=i.indexOf(r);if(n<o)return!1}}return!0}function Pm(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"?Pm(s[r],i,e):["number","string","boolean"].includes(typeof s[r])&&(e[i]=s[r])}),e}function _m(s,t,e={},r=""){const i={};try{const n=JSON.stringify(e),o=JSON.parse(n),c=Pm(o,r),d=JSON.stringify(c);return JSON.parse(d)}catch(n){const o=_d(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}const tp=class{constructor(){p(this,"logsCache",[]);p(this,"logsProcessorTimer");p(this,"tracingEnabled",!0);p(this,"initialized",!1);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",{})}get logsEndpoint(){const t=sr.getContext(this.meetingMetadata.peerId);return`https://${wi({servicePrefix:"api-silos",baseURI:t.getValue("baseURI")})}/otel/logs`}resetPeerId(t){this.meetingMetadata.peerId=t}init(t,e,r){this.tracingEnabled=!0,this.initialized=!1,this.logsCache=[];const i=t.getValue("peerId");this.meetingMetadata=e,this.tracingEnabled=r,this.meetingMetadata.peerId=i,this.meetingMetadata.sdkVersion=t.getValue("sdkVersion");const{RNDeviceInfoImpl:n}=navigator;this.meetingMetadata.deviceInfo=navigator.isReactNative?n==null?void 0:n.getDeviceInfo():be.getDeviceInfo(),this.meetingMetadata.visitedUrl=!navigator.isReactNative&&typeof window!="undefined"&&window.location.href,this.logsProcessorTimer=setInterval(this.processCachedLogs.bind(this),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){var g;const l=this==null?void 0:this.telemetry;if(!l||!l.initialized||navigator.isReactNative||!l.tracingEnabled||(g=sr.getContext(l.meetingMetadata.peerId))!=null&&g.getValue("flagsmith").hasFeature(Z.SKIP_OTEL_TRACES))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 S=performance.now();S-u>10&&l.addLogInCurrentSpan("info",`${t}_timing`,{execTime:S-u,country:tp.location.country})}).catch(()=>{const S=performance.now();l.addLogInCurrentSpan("info",`${t}_timing`,{execTime:S-u})}),h},n}}injectContext(t){var i;const e=fi().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:_d(r.error)});const n=sr.getContext(this.meetingMetadata.peerId);if(Z_(n)&&(F_(r)?console[t]("InternalLogs:: ",t,e):console[t]("InternalLogs:: ",t,e,r)),!!eR(n,t))try{const c=_m(n,e,r,"metadata"),d=new Date,l={message:e,level:t,...c,loggedAt:d.toISOString(),loggedAtTzOffset:d.getTimezoneOffset()};i?this.sendOtelLogsToNewRelic([l]):this.logsCache.push(l)}catch(c){this.addLogInCurrentSpan("error","opentelemetry::addLogInCurrentSpan_failed",{error:_d(c)})}}sendOtelLogsToNewRelic(t){const e=sr.getContext(this.meetingMetadata.peerId);fetch(this.logsEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({meetingMetadata:_m(e,"sendOtelLogsToNewRelic",this.meetingMetadata,"meetingMetadata"),serviceName:e.getValue("sdkName"),logs:t})}).catch(r=>{this.addLogInCurrentSpan("error","opentelemetry::sendOtelLogToNewRelic_failed",{error:_d(r)}),this.logsCache.push(...t)})}processCachedLogs(){const t=this.logsCache.splice(0,25);t!=null&&t.length&&this.sendOtelLogsToNewRelic(t)}destruct(){clearInterval(this.logsProcessorTimer),this.processCachedLogs()}};let E=tp;p(E,"location",{country:void 0});function tR(s){const t={...s},e=new Map,r=(l,u)=>(e.has(l)||e.set(l,new Set),e.get(l).add(u),()=>{var h;return(h=e.get(l))==null?void 0:h.delete(u)}),i=(l,u)=>{var h;(h=e.get(l))==null||h.delete(u)},n=l=>{var u;(u=e.get(l))==null||u.forEach(h=>{try{h(t[l])}catch(g){}})};return{subscribe:r,unsubscribe:i,notify:n,setValue:(l,u,h=!0)=>{t[l]=u,h&&n(l)},getValue:l=>t[l],getAllValues:()=>t}}class sR{constructor(){p(this,"contexts",new Map);p(this,"mostRecentPeerId",null)}createContext(t,e){if(this.contexts.has(t))return this.contexts.get(t);const r=new E,i=new cm;this.contexts.set(t,tR(e)),this.contexts.get(t).setValue("peerSessionStore",new eP(i));const n=new dg;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.contexts.get(t).setValue("flagsmith",Hb()),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 sr=new sR,rR={"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"},Cd={"0000":"Internal exception.","0001":"Failed to initialize.","0002":"Failed to join room.","0003":"Failed to leave room.","0004":"Invalid auth token","0010":"Browser not supported","0011":"HTTP Network Error","0012":"Websocket Network Error","0013":"Rate Limited","0100":"Internal exception","0101":"Permission denied","0102":"Prerequisite module missing","0200":"Internal exception.","0300":"Internal exception","0400":"Internal exception","0404":"Missing prerequisites to establish a websocket connection","0500":"Internal exception","0501":"Permission denied.","0502":"Invalid message body.","0503":"Text Message is too large","0504":"Message not found by the given id","0505":"Action not permitted without joining room","0506":"Message search is disabled","0600":"Internal exception","0601":"Permission denied.","0602":"Auth token not set for plugin","0603":"Iframe was not provided","0700":"Internal exception","0705":"Action not permitted without joining room","0800":"Internal exception","0801":"Permission denied","0900":"Internal exception","0904":"Could not load preset",1e3:"Internal exception",1001:"Permission denied",1004:"Could not find specified recording",1005:"Action not permitted in given recording state",1100:"Internal exception",1101:"Permission denied",1102:"Unsupported",1103:"Name cannot be empty",1104:"No device selected while calling meeting.self.setDevice",1105:"Action not permitted without joining room",1106:"Can't set currently used device",1200:"Internal exception",1201:"Permission denied",1202:"Invalid page number was requested",1203:"Invalid participant count per page was requested",1204:"No participants exists with the given UserIds",1205:"Action not permitted without joining room",1206:"Manual Subscription Mode was not ACTIVATED",1207:"Invalid view mode",1208:"Manual Subscription not enabled for organization",1209:"Broadcast message type must be a non-empty string",1300:"Internal exception",1400:"Internal exception",1402:"No existing remote requests",1403:"No peer exists with given id",1500:"Internal exception",1600:"Internal exception",1601:"Failed to get audio track",1602:"Failed to get video track",1603:"Incorrect device",1604:"Failed to change device",1605:"Failed to get audio & video track",1606:"No audio input devices are available",1607:"No video input devices are available",1608:"No audio output devices (speakers) are available",1609:"Failed to fetch list of media devices",1610:"No media track exists",1611:"Failed to unmute track",1612:"Failed to get screenshare tracks",1701:"Crypto error",1800:"Internal exception",1801:"Can't fetch transcript file",1900:"Internal exception",1901:"Permission denied.",1902:"Livestream that has not yet started, can't be stopped",2e3:"Internal exception",2001:"Permission denied",2002:"Unsupported",2003:"Stage is disabled",2004:"Method not implemented",2005:"Action not permitted without joining room",2006:"Action not permitted in current stage status",9900:"Internal exception"};Object.keys(Cd).forEach(s=>{Cd[s]=`{${rR[s.slice(0,2)]}} ${Cd[s]}`});class k 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?Cd[this.code]:"";this.message=`${o}: ${c}
|
|
10
|
-
${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=sr.getContext(sr.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 kd(s,t,e,r){if(r instanceof k)throw r;if(r instanceof t){const i=new k(r.message,e);throw i.stack=r.stack,i}else throw r}function Rm(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){kd(this,t,e,o)}}),n&&(s.set=function(o){try{return n.apply(this,[o])}catch(c){kd(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=>{kd(this,t,e,o)}):n}catch(n){kd(this,t,e,n)}},s}function iR(s,t){return(e,r,i)=>{if(i)return Rm(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,Rm(o,s,t))}}}const lt=s=>iR(Error,s);function nR(s){let t=0,e,r;if(!s)return t;for(e=0;e<s.length;e+=1)r=s.charCodeAt(e),t=(t<<5)-t+r,t|=0;return Math.abs(t)%100+1}function aR(){be.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.PRODUCER_CLOSED="websocket/producer-closed",s.NEW_CONSUMER="websocket/new-consumer",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.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))(_||{});class Dn extends dt.EventEmitter{constructor(e){super();p(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}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 $t extends dt.EventEmitter{constructor(e){super();p(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}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)}}function oR(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 Cm=1080,km=1920,cR=(s,t,e,r,i,n)=>{let o=.5,c=.5;const d=i,l=n,u=Math.min(e/d,r/l);let h=d*u,g=l*u,S,y,w,b,C=1;return h<e&&(C=e/h),Math.abs(C-1)<1e-14&&g<r&&(C=r/g),h*=C,g*=C,w=d/(h/e),b=l/(g/r),S=(d-w)*o,y=(l-b)*c,S<0&&(S=0),y<0&&(y=0),w>d&&(w=d),b>l&&(b=l),[S,y,w,b,s,t,e,r]},sp=class extends $t{constructor(e,r,i,n){const o=e.getValue("logger");super(o);m(this,os,void 0);m(this,xi,void 0);m(this,pt,void 0);m(this,cs,void 0);m(this,Ne,{height:Cm,width:km});m(this,Cs,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"});m(this,mr,void 0);m(this,bt,{});m(this,Fe,void 0);m(this,Jn,void 0);m(this,Kn,void 0);m(this,fr,void 0);m(this,zn,!1);p(this,"cleanupEventListeners",()=>{a(this,xi).unsubscribe("stageStatus",this.handlePipMediaControls),a(this,Fe).removeListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,Fe).removeListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,Fe).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,Fe).videoEnabled?a(this,Fe).disableVideo():a(this,Fe).enableVideo(),this.emit("cameraToggled")),e==="MIC"&&(a(this,Fe).audioEnabled?a(this,Fe).disableAudio():a(this,Fe).enableAudio(),this.emit("micToggled")),e==="END"&&(a(this,xi).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,fr)==="active"){this.disable(!0);return}a(this,bt)!==void 0&&this.paintCanvas(),a(this,mr)!==void 0&&f(this,mr,requestAnimationFrame(()=>this.animate()))});p(this,"disable",(e=!1)=>{f(this,fr,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(a(this,mr)),e!==!0&&document.body.removeChild(a(this,pt)),f(this,mr,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()});f(this,xi,e),f(this,fr,"idle"),f(this,Fe,r),f(this,Cs,{brand:r.config.designTokens.colors.brand[500],background:r.config.designTokens.colors.background[1e3],text:r.config.designTokens.colors.text,videoBackground:r.config.designTokens.colors.videoBg,textOnBrand:r.config.designTokens.colors.textOnBrand}),i&&this.setupIcon("pin",i),n&&this.setupIcon("handRaise",n)}static async _init(e,r){let i,n;try{i=await Rd(Q_),n=await Rd(X_)}catch(o){}return new sp(e,r,i,n)}async setupIcon(e,r){switch(e){case"handRaise":f(this,Kn,r);break;case"pin":f(this,Jn,r);break}}async overrideIcon(e,r){switch(e){case"handRaise":f(this,Kn,await Rd(r));break;case"pin":f(this,Jn,await Rd(r));break}}constructImage(e){const r=new Image,i=new Blob([e],{type:"image/svg+xml"}),n=window.URL.createObjectURL(i);return new Promise(o=>{r.onload=()=>{o(r),window.URL.revokeObjectURL(n)},r.src=n})}createVideoContainer(){f(this,pt,document.createElement("div")),a(this,pt).style.width="0.1px",a(this,pt).style.height="0.1px",a(this,pt).style.overflow="hidden",a(this,pt).style.position="absolute",a(this,pt).style.bottom="0",a(this,pt).style.right="0",a(this,pt).style.opacity="0",a(this,pt).appendChild(a(this,cs))}setupEventListeners(){a(this,xi).subscribe("stageStatus",this.handlePipMediaControls),a(this,Fe).addListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,Fe).addListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,Fe).addListener("roomLeft",()=>this.disable())}createCanvas(){const e=document.createElement("canvas");e.height=a(this,Ne).height,e.width=a(this,Ne).width,f(this,os,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,Fe).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||a(this,Fe).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const r=Object.values(a(this,bt)).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,os)===void 0)return;const o=a(this,os).getContext("2d"),c=a(this,os).width,d=0,l=0,u=r-d*2,h=i-d*2,g=Math.floor(c/u),S=Math.floor(e/g),w=e%g*(u+d)+d,b=S*(h+d)+d,{displayText:C,image:D}=n!=null?n:{};o.fillStyle=C||D?a(this,Cs).videoBackground:a(this,Cs).background,o.strokeStyle=a(this,Cs).brand,o.beginPath(),o.moveTo(w+l,b),o.arcTo(w+u,b,w+u,b+l,l),o.arcTo(w+u,b+h,w+u-l,b+h,l),o.arcTo(w,b+h,w,b+h-l,l),o.arcTo(w,b,w+l,b,l),o.closePath(),o.fill(),o.stroke();const F=u/6,L=u/2+w,B=h/2+b;o.save(),(C||D)&&(o.beginPath(),o.arc(L,B,F,0,Math.PI*2),o.fillStyle=a(this,Cs).brand,o.fill(),D?(o.clip(),o.drawImage(D,L-F,B-F,F*2,F*2),o.restore()):C&&(o.fillStyle=a(this,Cs).textOnBrand,o.font=`${F/2}px sans-serif`,o.textAlign="center",o.textBaseline="middle",o.fillText(C,L,B)),this.drawIcons(n,w,b,Math.max(u,h)))}drawIcons(e,r,i,n){const o=Math.min(Math.max(n*.15,100),200),c=o*.2,d=o*.2;let l=r+c;const u=i+c,h=g=>{const S=a(this,os).getContext("2d");S.save(),S.fillStyle=a(this,Cs).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 g=="string"?(S.font=`${o/1.5}px sans-serif`,S.fillStyle=a(this,Cs).text,S.textAlign="center",S.textBaseline="top",S.fillText(g,o/2+l,u+c)):S.drawImage(g,l+c,u+c,o-c*2,o-c*2),l+=o+c,S.restore()};e.pinned&&h(a(this,Jn)),e.handRaised&&h(a(this,Kn)),e.reaction&&h(e.reaction)}drawTile(e,r,i){var l,u;if(a(this,os)===void 0)return;const n=a(this,os).getContext("2d"),o=this.getSources();let c=0,d=0;for(;c<a(this,Ne).height-5;){let h=0;for(;h<a(this,Ne).width-5&&d<i;){if((l=o[d])!=null&&l.enabled){const g=o[d].element,[S,y,w,b,C,D,F,L]=cR(h,c,e,r,g.videoWidth,g.videoHeight);((u=g==null?void 0:g.classList)==null?void 0:u.contains("mirror"))?(n.save(),n.scale(-1,1),n.drawImage(g,S,y,w,b,-1*C,D,-1*F,L),n.restore()):n.drawImage(g,S,y,w,b,C,D,F,L),this.drawIcons(o[d],C,D,Math.max(F,L))}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,Ne).width,a(this,Ne).height];case 2:return[Math.floor(a(this,Ne).width/2),a(this,Ne).height];case 3:case 4:return[Math.floor(a(this,Ne).width/2),Math.floor(a(this,Ne).height/2)];case 5:case 6:return[Math.floor(a(this,Ne).width/3),Math.floor(a(this,Ne).height/2)];case 7:case 8:case 9:return[Math.floor(a(this,Ne).width/3),Math.floor(a(this,Ne).height/3)];default:return[Math.floor(a(this,Ne).width/3),Math.floor(a(this,Ne).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,Fe).config)==null?void 0:e.viewType)!=="LIVESTREAM"}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(f(this,zn,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),a(this,pt))try{document.body.removeChild(a(this,pt))}catch(e){}this.removeAllSources(),f(this,os,void 0),f(this,cs,void 0),f(this,mr,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,zn))return;f(this,zn,!0),this.createCanvas(),this.setupMediaSessionEvents();const i=document.createElement("video");f(this,Ne,{height:e!=null?e:Cm,width:r!=null?r:km}),i.height=a(this,Ne).height,i.width=a(this,Ne).width,i.autoplay=!0,i.muted=!0,i.srcObject=a(this,os).captureStream(24),f(this,cs,i),a(this,cs).onloadedmetadata=()=>{try{this.emit("pipStarted"),a(this,cs).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,bt)[e]!==void 0&&(a(this,bt)[e].enabled=!0)}disableSource(e){a(this,bt)[e]!==void 0&&(a(this,bt)[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,bt)[e]={id:e,element:r,enabled:i,pinned:n,displayText:o?oR(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,bt)[e];i&&(a(this,bt)[e]={...i,...r})}removeSource(e){delete a(this,bt)[e]}removePinnedSource(){Object.values(a(this,bt)).forEach(r=>{r.pinned&&this.removeSource(r.id)})}removeAllSources(){f(this,bt,{})}enable(){f(this,fr,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",a(this,Fe).videoEnabled),this.updateMediaSession("MIC",a(this,Fe).audioEnabled),document.body.appendChild(a(this,pt)),f(this,mr,requestAnimationFrame(()=>this.animate())),a(this,cs).onloadedmetadata=()=>{a(this,cs).requestPictureInPicture().then(()=>{f(this,fr,"active")})},a(this,cs).readyState===4&&a(this,cs).requestPictureInPicture().then(()=>{f(this,fr,"active")})}};let Qu=sp;os=new WeakMap,xi=new WeakMap,pt=new WeakMap,cs=new WeakMap,Ne=new WeakMap,Cs=new WeakMap,mr=new WeakMap,bt=new WeakMap,Fe=new WeakMap,Jn=new WeakMap,Kn=new WeakMap,fr=new WeakMap,zn=new WeakMap;function Xu(s){let t=typeof s;if(t=="object"){if(Array.isArray(s))return"array";if(s===null)return"null"}return t}function dR(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}let rr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Id=[];for(let s=0;s<rr.length;s++)Id[rr[s].charCodeAt(0)]=s;Id["-".charCodeAt(0)]=rr.indexOf("+"),Id["_".charCodeAt(0)]=rr.indexOf("/");function lR(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=Id[s.charCodeAt(c)],n===void 0)switch(s[c]){case"=":i=0;case`
|
|
11
|
-
`: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 uR(s){let t="",e=0,r,i=0;for(let n=0;n<s.length;n++)switch(r=s[n],e){case 0:t+=rr[r>>2],i=(r&3)<<4,e=1;break;case 1:t+=rr[i|r>>4],i=(r&15)<<2,e=2;break;case 2:t+=rr[i|r>>6],t+=rr[r&63],e=0;break}return e&&(t+=rr[i],t+="=",e==1&&(t+="=")),t}var Ad;(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])})(Ad||(Ad={}));var xe;(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"})(xe||(xe={}));function hR(){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 Zu(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 Md=(1<<16)*(1<<16);function Im(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>=Md&&(i=i+(r/Md|0),r=r%Md)}return n(-24,-18),n(-18,-12),n(-12,-6),n(-6),[t,r,i]}function eh(s,t){if(t>>>0<=2097151)return""+(Md*t+(s>>>0));let e=s&16777215,r=(s>>>24|t<<8)>>>0&16777215,i=t>>16&65535,n=e+r*6777216+i*6710656,o=r+i*8147497,c=i*2,d=1e7;n>=d&&(o+=Math.floor(n/d),n%=d),o>=d&&(c+=Math.floor(o/d),o%=d);function l(u,h){let g=u?String(u):"";return h?"0000000".slice(g.length)+g:g}return l(c,0)+l(o,c)+l(n,1)}function Am(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 pR(){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 ue;function gR(){const s=new DataView(new ArrayBuffer(8));ue=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}gR();function Mm(s){if(!s)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const Om=/^-?[0-9]+$/,Od=4294967296,Dd=2147483648;class Dm{constructor(t,e){this.lo=t|0,this.hi=e|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let t=this.hi*Od+(this.lo>>>0);if(!Number.isSafeInteger(t))throw new Error("cannot convert to safe number");return t}}class ut extends Dm{static from(t){if(ue)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=ue.C(t);case"number":if(t===0)return this.ZERO;t=ue.C(t);case"bigint":if(!t)return this.ZERO;if(t<ue.UMIN)throw new Error("signed value for ulong");if(t>ue.UMAX)throw new Error("ulong too large");return ue.V.setBigUint64(0,t,!0),new ut(ue.V.getInt32(0,!0),ue.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!Om.test(t))throw new Error("string is no integer");let[e,r,i]=Im(t);if(e)throw new Error("signed value for ulong");return new ut(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 ut(t,t/Od)}throw new Error("unknown value "+typeof t)}toString(){return ue?this.toBigInt().toString():eh(this.lo,this.hi)}toBigInt(){return Mm(ue),ue.V.setInt32(0,this.lo,!0),ue.V.setInt32(4,this.hi,!0),ue.V.getBigUint64(0,!0)}}ut.ZERO=new ut(0,0);class ge extends Dm{static from(t){if(ue)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=ue.C(t);case"number":if(t===0)return this.ZERO;t=ue.C(t);case"bigint":if(!t)return this.ZERO;if(t<ue.MIN)throw new Error("signed long too small");if(t>ue.MAX)throw new Error("signed long too large");return ue.V.setBigInt64(0,t,!0),new ge(ue.V.getInt32(0,!0),ue.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!Om.test(t))throw new Error("string is no integer");let[e,r,i]=Im(t);if(e){if(i>Dd||i==Dd&&r!=0)throw new Error("signed long too small")}else if(i>=Dd)throw new Error("signed long too large");let n=new ge(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 ge(t,t/Od):new ge(-t,-t/Od).negate()}throw new Error("unknown value "+typeof t)}isNegative(){return(this.hi&Dd)!==0}negate(){let t=~this.hi,e=this.lo;return e?e=~e+1:t+=1,new ge(e,t)}toString(){if(ue)return this.toBigInt().toString();if(this.isNegative()){let t=this.negate();return"-"+eh(t.lo,t.hi)}return eh(this.lo,this.hi)}toBigInt(){return Mm(ue),ue.V.setInt32(0,this.lo,!0),ue.V.setInt32(4,this.hi,!0),ue.V.getBigInt64(0,!0)}}ge.ZERO=new ge(0,0);const Nm={readUnknownField:!0,readerFactory:s=>new fR(s)};function mR(s){return s?Object.assign(Object.assign({},Nm),s):Nm}class fR{constructor(t,e){this.varint64=hR,this.uint32=pR,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 xe.Varint:for(;this.buf[this.pos++]&128;);break;case xe.Bit64:this.pos+=4;case xe.Bit32:this.pos+=4;break;case xe.LengthDelimited:let r=this.uint32();this.pos+=r;break;case xe.StartGroup:let i;for(;(i=this.tag()[1])!==xe.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 ge(...this.varint64())}uint64(){return new ut(...this.varint64())}sint64(){let[t,e]=this.varint64(),r=-(t&1);return t=(t>>>1|(e&1)<<31)^r,e=e>>>1^r,new ge(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 ut(this.sfixed32(),this.sfixed32())}sfixed64(){return new ge(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 se(s,t){if(!s)throw new Error(t)}const SR=34028234663852886e22,vR=-34028234663852886e22,TR=4294967295,yR=2147483647,ER=-2147483648;function po(s){if(typeof s!="number")throw new Error("invalid int 32: "+typeof s);if(!Number.isInteger(s)||s>yR||s<ER)throw new Error("invalid int 32: "+s)}function Nd(s){if(typeof s!="number")throw new Error("invalid uint 32: "+typeof s);if(!Number.isInteger(s)||s>TR||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>SR||s<vR))throw new Error("invalid float 32: "+s)}const Vm={writeUnknownFields:!0,writerFactory:()=>new bR};function wR(s){return s?Object.assign(Object.assign({},Vm),s):Vm}class bR{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(Nd(t);t>127;)this.buf.push(t&127|128),t=t>>>7;return this.buf.push(t),this}int32(t){return po(t),Am(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){Nd(t);let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),this.raw(e)}sfixed32(t){po(t);let e=new Uint8Array(4);return new DataView(e.buffer).setInt32(0,t,!0),this.raw(e)}sint32(t){return po(t),t=(t<<1^t>>31)>>>0,Am(t,this.buf),this}sfixed64(t){let e=new Uint8Array(8),r=new DataView(e.buffer),i=ge.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=ut.from(t);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(e)}int64(t){let e=ge.from(t);return Zu(e.lo,e.hi,this.buf),this}sint64(t){let e=ge.from(t),r=e.hi>>31,i=e.lo<<1^r,n=(e.hi<<1|e.lo>>>31)^r;return Zu(i,n,this.buf),this}uint64(t){let e=ut.from(t);return Zu(e.lo,e.hi,this.buf),this}}const Lm={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},xm={ignoreUnknownFields:!1};function PR(s){return s?Object.assign(Object.assign({},xm),s):xm}function _R(s){return s?Object.assign(Object.assign({},Lm),s):Lm}const Um=Symbol.for("protobuf-ts/message-type");function Fm(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 A;(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"})(A||(A={}));var Hs;(function(s){s[s.BIGINT=0]="BIGINT",s[s.STRING=1]="STRING",s[s.NUMBER=2]="NUMBER"})(Hs||(Hs={}));var Vd;(function(s){s[s.NO=0]="NO",s[s.PACKED=1]="PACKED",s[s.UNPACKED=2]="UNPACKED"})(Vd||(Vd={}));function RR(s){var t,e,r,i;return s.localName=(t=s.localName)!==null&&t!==void 0?t:Fm(s.name),s.jsonName=(e=s.jsonName)!==null&&e!==void 0?e:Fm(s.name),s.repeat=(r=s.repeat)!==null&&r!==void 0?r:Vd.NO,s.opt=(i=s.opt)!==null&&i!==void 0?i:s.repeat||s.oneof?!1:s.kind=="message",s}function CR(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 kR{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(!CR(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,A.INT32,i):this.scalar(t,A.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),A.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 A.UINT64:case A.FIXED64:case A.INT64:case A.SFIXED64:case A.SINT64:switch(r){case Hs.BIGINT:return i=="bigint";case Hs.NUMBER:return i=="number"&&!isNaN(t);default:return i=="string"}case A.BOOL:return i=="boolean";case A.STRING:return i=="string";case A.BYTES:return t instanceof Uint8Array;case A.DOUBLE:case A.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 A.INT32:case A.FIXED32:case A.SFIXED32:case A.SINT32:case A.UINT32:return this.scalars(i.slice(0,r).map(n=>parseInt(n)),e,r);case A.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,Hs.STRING)}}}function ys(s,t){switch(t){case Hs.BIGINT:return s.toBigInt();case Hs.NUMBER:return s.toNumber();default:return s.toString()}}class IR{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=Xu(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(dR(o),c.name,o);const u=l[d];for(const[h,g]of Object.entries(o)){this.assert(g!==null,c.name+" map value",null);let S;switch(c.V.kind){case"message":S=c.V.T().internalJsonRead(g,r);break;case"enum":if(S=this.enum(c.V.T(),g,c.name,r.ignoreUnknownFields),S===!1)continue;break;case"scalar":S=this.scalar(g,c.V.T,c.V.L,c.name);break}this.assert(S!==void 0,c.name+" map value",g);let y=h;c.K==A.BOOL&&(y=y=="true"?!0:y=="false"?!1:y),y=this.scalar(y,c.K,Hs.STRING,c.name).toString(),u[y]=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 g;switch(c.kind){case"message":g=c.T().internalJsonRead(h,r);break;case"enum":if(g=this.enum(c.T(),h,c.name,r.ignoreUnknownFields),g===!1)continue;break;case"scalar":g=this.scalar(h,c.T,c.L,c.name);break}this.assert(g!==void 0,c.name,o),u.push(g)}}else switch(c.kind){case"message":if(o===null&&c.T().typeName!="google.protobuf.Value"){this.assert(c.oneof===void 0,c.name+" (oneof member)",null);continue}l[d]=c.T().internalJsonRead(o,r,l[d]);break;case"enum":if(o===null)continue;let u=this.enum(c.T(),o,c.name,r.ignoreUnknownFields);if(u===!1)continue;l[d]=u;break;case"scalar":if(o===null)continue;l[d]=this.scalar(o,c.T,c.L,c.name);break}}}enum(t,e,r,i){if(t[0]=="google.protobuf.NullValue"&&se(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 se(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:(se(typeof o=="number",`Unable to parse field ${this.info.typeName}#${r}, enum ${t[0]} has no value for "${e}".`),o)}se(!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 A.DOUBLE:case A.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==A.FLOAT&&th(o),o;case A.INT32:case A.FIXED32:case A.SFIXED32:case A.SINT32:case A.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==A.UINT32?Nd(c):po(c),c;case A.INT64:case A.SFIXED64:case A.SINT64:if(t===null)return ys(ge.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return ys(ge.from(t),r);case A.FIXED64:case A.UINT64:if(t===null)return ys(ut.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return ys(ut.from(t),r);case A.BOOL:if(t===null)return!1;if(typeof t!="boolean")break;return t;case A.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 A.BYTES:if(t===null||t==="")return new Uint8Array(0);if(typeof t!="string")break;return lR(t)}}catch(o){n=o.message}this.assert(!1,i+(n?" - "+n:""),t)}}class AR{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);se(d!==void 0),r[e.useProtoFieldName?n.name:n.jsonName]=d}return r}field(t,e,r){let i;if(t.kind=="map"){se(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);se(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);se(u!==void 0),n[d.toString()]=u}break;case"enum":const c=t.V.T();for(const[d,l]of Object.entries(e)){se(l===void 0||typeof l=="number");const u=this.enum(c,l,t.name,!1,!0,r.enumAsInteger);se(u!==void 0),n[d.toString()]=u}break}(r.emitDefaultValues||Object.keys(n).length>0)&&(i=n)}else if(t.repeat){se(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);se(l!==void 0),n.push(l)}break;case"enum":const o=t.T();for(let d=0;d<e.length;d++){se(e[d]===void 0||typeof e[d]=="number");const l=this.enum(o,e[d],t.name,t.opt,!0,r.enumAsInteger);se(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);se(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){se(i);return}if(!(e===0&&!n&&!i))return se(typeof e=="number"),se(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){se(i);return}const o=n||i;switch(t){case A.INT32:case A.SFIXED32:case A.SINT32:return e===0?o?0:void 0:(po(e),e);case A.FIXED32:case A.UINT32:return e===0?o?0:void 0:(Nd(e),e);case A.FLOAT:th(e);case A.DOUBLE:return e===0?o?0:void 0:(se(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e);case A.STRING:return e===""?o?"":void 0:(se(typeof e=="string"),e);case A.BOOL:return e===!1?o?!1:void 0:(se(typeof e=="boolean"),e);case A.UINT64:case A.FIXED64:se(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let c=ut.from(e);return c.isZero()&&!o?void 0:c.toString();case A.INT64:case A.SFIXED64:case A.SINT64:se(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let d=ge.from(e);return d.isZero()&&!o?void 0:d.toString();case A.BYTES:return se(e instanceof Uint8Array),e.byteLength?uR(e):o?"":void 0}}}function sh(s,t=Hs.STRING){switch(s){case A.BOOL:return!1;case A.UINT64:case A.FIXED64:return ys(ut.ZERO,t);case A.INT64:case A.SFIXED64:case A.SINT64:return ys(ge.ZERO,t);case A.DOUBLE:case A.FLOAT:return 0;case A.BYTES:return new Uint8Array(0);case A.STRING:return"";default:return 0}}class MR{constructor(t){this.info=t}prepare(){var t;if(!this.fieldNoToField){const e=(t=this.info.fields)!==null&&t!==void 0?t:[];this.fieldNoToField=new Map(e.map(r=>[r.no,r]))}}read(t,e,r,i){this.prepare();const n=i===void 0?t.len:t.pos+i;for(;t.pos<n;){const[o,c]=t.tag(),d=this.fieldNoToField.get(o);if(!d){let g=r.readUnknownField;if(g=="throw")throw new Error(`Unknown field ${o} (wire type ${c}) for ${this.info.typeName}`);let S=t.skip(c);g!==!1&&(g===!0?Ad.onRead:g)(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 g=d.kind=="enum"?A.INT32:d.T,S=d.kind=="scalar"?d.L:void 0;if(u){let b=l[h];if(c==xe.LengthDelimited&&g!=A.STRING&&g!=A.BYTES){let C=t.uint32()+t.pos;for(;t.pos<C;)b.push(this.scalar(t,g,S))}else b.push(this.scalar(t,g,S))}else l[h]=this.scalar(t,g,S);break;case"message":if(u){let b=l[h],C=d.T().internalBinaryRead(t,t.uint32(),r);b.push(C)}else l[h]=d.T().internalBinaryRead(t,t.uint32(),r,l[h]);break;case"map":let[y,w]=this.mapEntry(d,t,r);l[h][y]=w;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==A.BOOL?o=e.bool().toString():o=this.scalar(e,t.K,Hs.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=sh(t.K);o=t.K==A.BOOL?d.toString():d}if(c===void 0)switch(t.V.kind){case"scalar":c=sh(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 A.INT32:return t.int32();case A.STRING:return t.string();case A.BOOL:return t.bool();case A.DOUBLE:return t.double();case A.FLOAT:return t.float();case A.INT64:return ys(t.int64(),r);case A.UINT64:return ys(t.uint64(),r);case A.FIXED64:return ys(t.fixed64(),r);case A.FIXED32:return t.fixed32();case A.BYTES:return t.bytes();case A.UINT32:return t.uint32();case A.SFIXED32:return t.sfixed32();case A.SFIXED64:return ys(t.sfixed64(),r);case A.SINT32:return t.sint32();case A.SINT64:return ys(t.sint64(),r)}}}class OR{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"?A.INT32:n.T;if(d)if(se(Array.isArray(o)),d==Vd.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?se(n.opt):this.scalar(e,u,n.no,o,c||n.opt);break;case"message":if(d){se(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":se(typeof o=="object"&&o!==null);for(const[h,g]of Object.entries(o))this.mapEntry(e,r,n,h,g);break}}let i=r.writeUnknownFields;i!==!1&&(i===!0?Ad.onWrite:i)(this.info.typeName,t,e)}mapEntry(t,e,r,i,n){t.tag(r.no,xe.LengthDelimited),t.fork();let o=i;switch(r.K){case A.INT32:case A.FIXED32:case A.UINT32:case A.SFIXED32:case A.SINT32:o=Number.parseInt(i);break;case A.BOOL:se(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,A.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,xe.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;se(e!==A.BYTES&&e!==A.STRING),t.tag(r,xe.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=xe.Varint,i,n=e===void 0,o=e===0;switch(t){case A.INT32:i="int32";break;case A.STRING:o=n||!e.length,r=xe.LengthDelimited,i="string";break;case A.BOOL:o=e===!1,i="bool";break;case A.UINT32:i="uint32";break;case A.DOUBLE:r=xe.Bit64,i="double";break;case A.FLOAT:r=xe.Bit32,i="float";break;case A.INT64:o=n||ge.from(e).isZero(),i="int64";break;case A.UINT64:o=n||ut.from(e).isZero(),i="uint64";break;case A.FIXED64:o=n||ut.from(e).isZero(),r=xe.Bit64,i="fixed64";break;case A.BYTES:o=n||!e.byteLength,r=xe.LengthDelimited,i="bytes";break;case A.FIXED32:r=xe.Bit32,i="fixed32";break;case A.SFIXED32:r=xe.Bit32,i="sfixed32";break;case A.SFIXED64:o=n||ge.from(e).isZero(),r=xe.Bit64,i="sfixed64";break;case A.SINT32:i="sint32";break;case A.SINT64:o=n||ge.from(e).isZero(),i="sint64";break}return[r,i,n||o]}}function DR(s){const t=s.messagePrototype?Object.create(s.messagePrototype):Object.defineProperty({},Um,{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]=sh(e.T,e.L);break;case"enum":t[r]=0;break;case"map":t[r]={};break}}return t}function rh(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 NR(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"?A.INT32:r.T;if(!(r.repeat?Bm(c,n,o):$m(c,n,o)))return!1;break;case"map":if(!(r.V.kind=="message"?Hm(r.V.T(),Ld(n),Ld(o)):Bm(r.V.kind=="enum"?A.INT32:r.V.T,Ld(n),Ld(o))))return!1;break;case"message":let d=r.T();if(!(r.repeat?Hm(d,n,o):d.equals(n,o)))return!1;break}}return!0}const Ld=Object.values;function $m(s,t,e){if(t===e)return!0;if(s!==A.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 Bm(s,t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(!$m(s,t[r],e[r]))return!1;return!0}function Hm(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 VR=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({}));class v{constructor(t,e,r){this.defaultCheckDepth=16,this.typeName=t,this.fields=e.map(RR),this.options=r!=null?r:{},this.messagePrototype=Object.create(null,Object.assign(Object.assign({},VR),{[Um]:{value:this}})),this.refTypeCheck=new kR(this),this.refJsonReader=new IR(this),this.refJsonWriter=new AR(this),this.refBinReader=new MR(this),this.refBinWriter=new OR(this)}create(t){let e=DR(this);return t!==void 0&&rh(this,e,t),e}clone(t){let e=this.create();return rh(this,e,t),e}equals(t,e){return NR(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){rh(this,t,e)}fromBinary(t,e){let r=mR(e);return this.internalBinaryRead(r.readerFactory(t),t.byteLength,r)}fromJson(t,e){return this.internalJsonRead(t,PR(e))}fromJsonString(t,e){let r=JSON.parse(t);return this.fromJson(r,e)}toJson(t,e){return this.internalJsonWrite(t,_R(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=wR(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 ${Xu(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 ir;(function(s){s[s.PUBLISHER=0]="PUBLISHER",s[s.SUBSCRIBER=1]="SUBSCRIBER"})(ir||(ir={}));var qs;(function(s){s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO"})(qs||(qs={}));class LR 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 qm=new LR;class xR 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 UR=new xR;class FR extends v{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new FR;class $R extends v{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",ir]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const Es=new $R;class BR 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 HR=new BR;class qR 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:()=>Es},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8},{no:5,name:"producers",kind:"message",repeat:1,T:()=>HR}])}}const jR=new qR;class GR 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 WR=new GR;class JR extends v{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Es},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:4,name:"producer_ids",kind:"scalar",repeat:2,T:9}])}}const jm=new JR;class KR extends v{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Es}])}}const zR=new KR;class YR extends v{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Es}])}}new YR;class QR 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 XR=new QR;class ZR 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 eC=new ZR;class tC 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 tC;class sC 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 sC;class rC extends v{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",qs]},{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:()=>qm}])}}const go=new rC;class iC extends v{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>go},{no:3,name:"producer_track",kind:"message",T:()=>eC},{no:4,name:"error_code",kind:"scalar",opt:!0,T:9}])}}const nC=new iC;class aC extends v{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>nC}}])}}const Gm=new aC;class oC extends v{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>Km},{no:2,name:"receiver",kind:"message",T:()=>Km}])}}const Wm=new oC;class cC extends v{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>qm},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>UR}])}}const Jm=new cC;class dC extends v{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>Jm},{no:2,name:"video",kind:"message",T:()=>Jm}])}}const Km=new dC;class lC 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 uC=new lC;class hC 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 zm=new hC;class pC 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 gC=new pC;class mC 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:()=>gC},{no:9,name:"capabilities",kind:"message",T:()=>Wm}])}}const fC=new mC;class SC extends v{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const vC=new SC;class TC extends v{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const yC=new TC;class EC 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 EC;class wC 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:()=>uC},{no:5,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:6,name:"simulcast",kind:"message",T:()=>zm}])}}const bC=new wC;class PC extends v{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>bC},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const _C=new PC;class RC extends v{constructor(){super("media.edge.UpdateConsumerSimulcastConfigRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"simulcast",kind:"message",T:()=>zm},{no:3,name:"producing_transport_id",kind:"scalar",T:9},{no:4,name:"mid",kind:"scalar",T:9}])}}const CC=new RC;class kC extends v{constructor(){super("media.edge.UpdateConsumersSimulcastConfigRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>CC},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const IC=new kC;class AC 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:()=>Es},{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 MC=new AC;class OC extends v{constructor(){super("media.edge.SelectedPeersRequest",[])}}new OC;class DC extends v{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const NC=new DC;class VC 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 xd=new VC;class LC 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 LC;class xC extends v{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Es},{no:3,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const UC=new xC;class FC 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:()=>Es},{no:3,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const $C=new FC;class BC extends v{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new BC;class HC extends v{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const Ym=new HC;class qC 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 jC=new qC;class GC 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 WC=new GC;class JC 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 KC=new JC;class zC 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 YC=new zC;class QC 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 XC=new QC;class ZC extends v{constructor(){super("media.edge.EmptyResponse",[])}}new ZC;class ek 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:()=>go},{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:()=>Wm}])}}const Qm=new ek;class tk 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 ih=new tk;class sk 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 rk=new sk;class ik extends v{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>rk}])}}const Xm=new ik;class nk extends v{constructor(){super("media.edge.PeerJoinResponse",[])}}new nk;class ak extends v{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>YC},{no:2,name:"participants",kind:"message",repeat:1,T:()=>Qm},{no:3,name:"selected_peers",kind:"message",T:()=>ih},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const nh=new ak;class ok extends v{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const ck=new ok;class dk extends v{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Gm}])}}new dk;class lk extends v{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Gm},{no:3,name:"description",kind:"message",T:()=>Es}])}}const uk=new lk;class hk 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:()=>Es}])}}const pk=new hk;class gk extends v{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>XR}])}}new gk;class mk 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 mk;class fk extends v{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new fk;class Sk extends v{constructor(){super("media.edge.ProducerToggleResponse",[])}}new Sk;class vk extends v{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new vk;class Tk extends v{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>Es}])}}const yk=new Tk;class Ek extends v{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>Es}])}}const wk=new Ek;class bk extends v{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new bk;class Pk extends v{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new Pk;class _k extends v{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new _k;class Rk extends v{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Ck=new Rk;class kk extends v{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Ik=new kk;class Ak extends v{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Mk=new Ak;class Ok extends v{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>Qm}])}}const Zm=new Ok;class Dk extends v{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const ef=new Dk;class Nk extends v{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>ef},{no:3,name:"screenshare",kind:"message",T:()=>ef}])}}const Vk=new Nk;class Lk extends v{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>jm},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>Vk}])}}new Lk;class xk extends v{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>go}])}}const Uk=new xk;class Fk extends v{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>go},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const tf=new Fk;class $k extends v{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>go}])}}const Bk=new $k;class Hk extends v{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const ah=new Hk;class qk extends v{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const sf=new qk;class jk extends v{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new jk;class Gk extends v{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new Gk;class Wk extends v{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new Wk;class Jk 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 Jk;class Kk extends v{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new Kk;class zk extends v{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new zk;class Yk 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 oh=new Yk;class Qk 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 Qk;class Xk 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 Zk=new Xk;var Pi;(function(s){s[s.BROWSER=0]="BROWSER",s[s.TRACK=1]="TRACK",s[s.COMPOSITE=2]="COMPOSITE"})(Pi||(Pi={}));var nr;(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"})(nr||(nr={}));var ch;(function(s){s[s.NONE=0]="NONE",s[s.RECORDER=1]="RECORDER",s[s.LIVESTREAMER=2]="LIVESTREAMER"})(ch||(ch={}));var dh;(function(s){s[s.PEERS=0]="PEERS",s[s.ROOMS=1]="ROOMS"})(dh||(dh={}));var Ud;(function(s){s[s.HIVE=0]="HIVE",s[s.CHAT=1]="CHAT",s[s.PING=2]="PING"})(Ud||(Ud={}));class eI 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 tI=new eI;class sI 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",nr,"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:()=>tI}])}}const Fd=new sI;class rI extends v{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>Fd}])}}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",nr,"STAGE_TYPE_"]}])}}const rf=new iI;class nI 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 aI=new nI;class oI extends v{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>Fd}])}}const lh=new oI;class cI extends v{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const nf=new cI;class dI 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:()=>uI},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const af=new dI;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",Pi]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const uI=new lI;class hI extends v{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>af}])}}const of=new hI;class pI extends v{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const cf=new pI;class gI 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 gI;class mI extends v{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Fd},{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",Ud,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const fI=new mI;class SI extends v{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Fd},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const vI=new SI;class TI extends v{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>af}])}}new TI;class yI extends v{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new yI;class EI 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 uh=new EI;class wI 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 bI=new wI;class PI 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:()=>bI}])}}const df=new PI;class _I extends v{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>df},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>df}])}}const RI=new _I;class CI extends v{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const kI=new CI;class II extends v{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>kI}])}}const AI=new II;class MI 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:()=>uh}])}}const OI=new MI;class DI extends v{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>OI}])}}const lf=new DI;class NI 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 VI=new NI;class LI extends v{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>VI}])}}new LI;class xI extends v{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const UI=new xI;class FI extends v{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>UI}])}}const $I=new FI;class BI extends v{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>jI}])}}const HI=new BI;class qI 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:()=>uh}])}}const jI=new qI;class GI 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 WI=new GI;class JI 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:()=>WI}])}}const KI=new JI;class zI 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:()=>uh}])}}const uf=new zI;class YI extends v{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>uf}])}}new YI;class QI 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 XI=new QI;class ZI extends v{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>sA}])}}const eA=new ZI;class tA 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 sA=new tA;class rA extends v{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const hf=new rA;class iA 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",dh,"BROADCAST_TYPE_"]}])}}const mo=new iA;class nA extends v{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const aA=new nA;class oA extends v{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const cA=new oA;class dA 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 lA=new dA;class uA extends v{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>lA}])}}const pf=new uA;class hA 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 hA;var hh;(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"})(hh||(hh={}));var xr;(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"})(xr||(xr={}));class pA 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 gA=new pA;class mA 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 fA=new mA;class SA 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 vA=new SA;class TA 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 yA=new TA;class EA extends v{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>vA},{no:2,name:"private",kind:"message",T:()=>yA}])}}const wA=new EA;class bA 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 PA=new bA;class _A extends v{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",xr,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",xr,"STREAM_PERMISSION_TYPE_"]}])}}const ph=new _A;class RA extends v{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>ph},{no:2,name:"audio",kind:"message",T:()=>ph},{no:3,name:"screenshare",kind:"message",T:()=>ph}])}}const CA=new RA;class kA extends v{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>gA},{no:2,name:"plugins",kind:"message",T:()=>fA},{no:3,name:"chat",kind:"message",T:()=>wA},{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",hh,"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",ch,"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:()=>PA},{no:23,name:"media",kind:"message",T:()=>CA}])}}const gh=new kA;class IA extends v{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const AA=new IA;class MA 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 OA=new MA;class DA extends v{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>OA}])}}const NA=new DA;class VA extends v{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>gh}])}}const mf=new VA;class LA extends v{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>mf}])}}const xA=new LA;class UA extends v{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>mf}])}}const ff=new UA;class FA 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 $A=new FA;class BA extends v{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>$A},{no:2,name:"patch",kind:"message",T:()=>gh}])}}new BA;class HA extends v{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>gh}])}}new HA;class qA 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 Ur=new qA;class jA 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 GA=new jA;class WA 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:()=>GA}])}}const JA=new WA;class KA extends v{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Ur},{no:2,name:"next",kind:"scalar",T:8}])}}const zA=new KA;class YA extends v{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Ur}])}}const Sf=new YA;class QA 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 XA=new QA;class ZA extends v{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>Ur}])}}const mh=new ZA;class e0 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 t0=new e0;class s0 extends v{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>Ur}])}}const fh=new s0;class r0 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 r0;class i0 extends v{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>Ur}])}}new i0;class n0 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 a0=new n0;class o0 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 c0=new o0;class d0 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:()=>Ur}])}}const $d=new d0;class l0 extends v{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>Ur}])}}const Bd=new l0;class u0 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 h0=new u0;class p0 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 Hd=new p0;class g0 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 m0=new g0;class f0 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 f0;class S0 extends v{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}new S0;class v0 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 v0;class T0 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 T0;class y0 extends v{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new y0;class E0 extends v{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new E0;class w0 extends v{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>Ur},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const b0=new w0;class P0 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:()=>b0},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const _0=new P0;class R0 extends v{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>_0}])}}new R0;class C0 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 k0=new C0;class I0 extends v{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>k0}])}}new I0;class A0 extends v{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const M0=new A0;class O0 extends v{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const D0=new O0;class N0 extends v{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const V0=new N0;class L0 extends v{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const x0=new L0;class U0 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}])}}const F0=new U0;class $0 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}])}}const B0=new $0;class H0 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}])}}const q0=new H0;class j0 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}])}}const G0=new j0;class W0 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 Sh=new W0;class J0 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:()=>Sh}])}}const vf=new J0;class K0 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:()=>Sh}])}}const z0=new K0;class Y0 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:()=>Sh}])}}const Q0=new Y0;class X0 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}])}}const Z0=new X0;class eM 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 vh=new eM;class tM extends v{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>vh}])}}const sM=new tM;class rM 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}])}}const Tf=new rM;class iM 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 nM=new iM;class aM 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:()=>nM}])}}const yf=new aM;class oM 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}])}}const Ef=new oM;class cM 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 wf=new cM;class dM extends v{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const bf=new dM;class lM 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 uM=new lM;class hM extends v{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>uM}])}}const Th=new hM;class pM extends v{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const gM=new pM;class mM extends v{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const fM=new mM;class SM extends v{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const Pf=new SM;class vM 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:()=>yM},{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 _f=new vM;class TM 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:()=>wM}])}}const yM=new TM;class EM 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 wM=new EM;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 PM=new bM;class _M 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 RM=new _M;class CM extends v{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>_f}])}}const yh=new CM;class kM extends v{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>_f}])}}const IM=new kM;class AM 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",Pi]}])}}const Rf=new AM;class MM 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=ge.from(Math.floor(e/1e3)).toBigInt(),t.nanos=e%1e3*1e6,t}toDate(t){return new Date(ge.from(t.seconds).toNumber()*1e3+Math.ceil(t.nanos/1e6))}fromDate(t){const e=this.create(),r=t.getTime();return e.seconds=ge.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}internalJsonWrite(t,e){let r=ge.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 "+Xu(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=ge.from(n/1e3).toBigInt(),r.nanos=0,i[7]&&(r.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),r}}new MM;class OM 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 Eh=new OM;class DM extends v{constructor(){super("common.BulkedHubMessage",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Eh}])}}new DM;class NM extends v{constructor(){super("common.CFWorkersResponse",[{no:1,name:"responses",kind:"message",repeat:1,T:()=>Eh},{no:2,name:"broadcast_responses",kind:"message",repeat:1,T:()=>Eh}])}}new NM;const VM=0,LM=1,xM=2,UM=3,FM=5,$M={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},BM={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,searchChannelMessages:7,pinMessage:10},HM={getPlugins:0,addPlugin:1,enablePluginForRoom:2,disablePluginForPeers:3,enablePluginForPeers:4,disablePluginForRoom:5,removePlugin:6,customPluginEventToRoom:7,customPluginEventToPeers:8,storeInsertKeys:9,storeGetKeys:10,storeDeleteKeys:11,storeDelete:12},qM={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},Cf={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},jM={getUserPresets:0,updateUserPreset:1};function fo(s,t){return Object.keys(t).reduce((e,r)=>(e[r]=(s<<16)+t[r],e),{})}function kf(s,t){return Object.keys(s).reduce((e,r)=>(e[r]=t|s[r],e),{})}const U=fo(VM,$M),Ge=fo(LM,BM),G=fo(xM,HM),ar=fo(UM,qM),Fr=kf(Cf,16777216),ws=kf(Cf,50331648),qd=fo(FM,jM);var GM=Object.defineProperty,WM=Object.getOwnPropertyDescriptor,$r=(s,t,e,r)=>{for(var i=r>1?void 0:r?WM(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&&GM(t,e,i),i},is=(s=>(s[s.TEXT=0]="TEXT",s[s.IMAGE=1]="IMAGE",s[s.FILE=2]="FILE",s[s.CUSTOM=3]="CUSTOM",s))(is||{});class or{constructor(t,e){m(this,Jt,void 0);m(this,Yn,void 0);f(this,Jt,e),f(this,Yn,t)}get telemetry(){return a(this,Yn).getValue("telemetry")}get logger(){return a(this,Yn).getValue("logger")}getChatMessages(){return a(this,Jt).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,Jt).sendMessagePromise(Ge.getPaginatedMessages,JA.toBinary(n));return o.payload?zA.fromBinary(o.payload):{messages:[],next:!1}}sendMessageToRoom(t,e){const r={payloadType:e,payload:t};a(this,Jt).sendMessage(Ge.sendMessageToRoom,XA.toBinary(r))}sendMessageToPeers(t,e,r){const i={payloadType:e,peerIds:r,payload:t};a(this,Jt).sendMessage(Ge.sendMessageToPeers,t0.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,Jt).sendMessagePromise(Ge.editMessage,a0.toBinary(n));return Bd.fromBinary(o.payload).message}async deleteMessage(t){const e={chatId:t},r=await a(this,Jt).sendMessagePromise(Ge.deleteMessage,h0.toBinary(e));return{id:Hd.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,Jt).sendMessagePromise(Ge.searchChannelMessages,m0.toBinary(r));return Sf.fromBinary(d.payload).messages}catch(d){return[]}}async setPinState(t,e){const r={chatId:t,pinned:e},i=await a(this,Jt).sendMessagePromise(Ge.pinMessage,c0.toBinary(r));return $d.fromBinary(i.payload)}on(t,e){let r,i;switch(t){case Ge.sendMessageToRoom:{r=mh.fromBinary.bind(mh),i=mh.create();break}case Ge.sendMessageToPeers:{r=fh.fromBinary.bind(fh),i=fh.create();break}case Ge.editMessage:{r=Bd.fromBinary.bind(Bd),i=Bd.create();break}case Ge.pinMessage:{r=$d.fromBinary.bind($d),i=$d.create();break}case Ge.deleteMessage:{r=Hd.fromBinary.bind(Hd),i=Hd.create();break}}if(!r){this.logger.warn(`ChatSocketHandler::Event ${t} is not recognized`);return}a(this,Jt).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)})}}Jt=new WeakMap,Yn=new WeakMap,$r([E.trace("SocketService.getChatMessages")],or.prototype,"getChatMessages",1),$r([E.trace("SocketService.getChatMessagesPaginated")],or.prototype,"getChatMessagesPaginated",1),$r([E.trace("SocketService.sendMessageToRoom")],or.prototype,"sendMessageToRoom",1),$r([E.trace("SocketService.sendMessageToPeers")],or.prototype,"sendMessageToPeers",1),$r([E.trace("SocketService.sendMessage")],or.prototype,"sendMessage",1),$r([E.trace("SocketService.editMessage")],or.prototype,"editMessage",1),$r([E.trace("SocketService.deleteMessage")],or.prototype,"deleteMessage",1),$r([E.trace("SocketService.searchMessages")],or.prototype,"searchMessages",1);function JM(s){return s.replace(/([-_]\w)/g,t=>t[1].toUpperCase())}function bs(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>bs(e));const t={};return Object.keys(s).forEach(e=>{const r=yu(e)?e:JM(e);t[r]=bs(s[e])}),t}function KM(s){return s.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function If(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>If(e));const t={};return Object.keys(s).forEach(e=>{const r=yu(e)?e:KM(e);t[r]=s[e]}),t}function jd(s,t={}){return s==null?{}:(Object.getOwnPropertyNames(s).forEach(e=>{if(typeof s[e]!="function"){if(typeof s[e]=="object"){jd(s[e],t[e]={});return}t[e]=s[e]}}),t)}class Af{constructor(t){p(this,"defaults");this.defaults={baseURL:t.baseURL,headers:{common:{}},timeout:t.timeout,retry:t.retry,retryDelay:t.retryDelay}}buildURL(t,e){const{baseURL:r}=this.defaults,i=t.startsWith("http")?t:`${r}${t.startsWith("/")?t:`/${t}`}`;if(e){const n=new URLSearchParams;return Object.entries(e).forEach(([o,c])=>{n.append(o,c)}),`${i}${i.includes("?")?"&":"?"}${n.toString()}`}return i}async request(t){var h;const e=((h=t.method)==null?void 0:h.toUpperCase())||"GET",r=this.buildURL(t.url||"",t.params),i={...this.defaults.headers.common,...t.headers};e!=="GET"&&e!=="HEAD"&&t.data&&!i["Content-Type"]&&(i["Content-Type"]="application/json");const o=i["Content-Type"]==="application/json"?JSON.stringify(t.data):t.data,c={method:e,headers:i,body:e!=="GET"&&e!=="HEAD"&&t.data?o:void 0},d=t.timeout||this.defaults.timeout,l=t.retry!==void 0?t.retry:this.defaults.retry,u=t.retryDelay||this.defaults.retryDelay;try{const g=new AbortController,S=setTimeout(()=>g.abort(),d);c.signal=g.signal;const y=await fetch(r,c);clearTimeout(S);let w=null;const b=y.headers.get("content-type");b&&b.includes("application/json")?w=await y.json():w=await y.text();const C={};y.headers.forEach((F,L)=>{C[L]=F});const D={data:w,status:y.status,statusText:y.statusText,headers:C,config:t};if(!y.ok)throw D;return D}catch(g){if(g instanceof Error&&l>0)return await new Promise(S=>setTimeout(S,u)),this.defaults.baseURL===bi.apiBase.prod?this.defaults.baseURL=bi.apiBase.prodAlternate:this.defaults.baseURL===bi.apiBase.prodAlternate&&(this.defaults.baseURL=bi.apiBase.prod),this.request({...t,retry:l-1});throw g}}async get(t,e={}){return this.request({...e,method:"GET",url:t})}async post(t,e,r={}){return this.request({...r,method:"POST",url:t,data:e})}async put(t,e,r={}){return this.request({...r,method:"PUT",url:t,data:e})}}const zM=3,YM=30,QM=8e3;class XM{constructor(t,e){p(this,"ipInfo");p(this,"fetchClient");p(this,"requests");p(this,"roomName");p(this,"roomUUID");p(this,"authToken");p(this,"organizationId");p(this,"iceServers");p(this,"pluginInformation");p(this,"userDetails");p(this,"roomDetails");p(this,"context");this.context=t;const{timeout:r=QM,retry:i=zM,retryDelay:n=YM,baseURL:o=bi.apiBase.prod,authToken:c,cachedUserDetails:d}=e||{};this.iceServers=d==null?void 0:d.iceServers,this.pluginInformation=d==null?void 0:d.pluginInformation,this.userDetails=d==null?void 0:d.userDetails,this.roomDetails=d==null?void 0:d.roomDetails,this.requests=new Af({baseURL:o,timeout:r,retry:i,retryDelay:n,responseType:"json"}),this.fetchClient=new Af({baseURL:"",timeout:r,retry:i,retryDelay:n,responseType:"json"}),this.setAuthToken(c,{bearer:!0});const l=this.requests.request.bind(this.requests);this.requests.request=async u=>{var g,S,y,w,b;const h=t.getValue("telemetry");try{h.injectContext(this.requests.defaults.headers.common);const C=await l(u);return u.url!==h.logsEndpoint&&this.logger.debug("xhr::fetch",{networkCall:{status:C.status,statusText:C.statusText,baseURL:u.baseURL||this.requests.defaults.baseURL,url:u.url,method:u.method}}),C}catch(C){throw C?(((g=C.config)==null?void 0:g.url)!==h.logsEndpoint&&this.logger.error("xhr::fetch",{error:C,networkCall:{status:C.status,statusText:C.statusText,baseURL:((S=C.config)==null?void 0:S.baseURL)||this.requests.defaults.baseURL,url:(y=C.config)==null?void 0:y.url,retries:(w=C.config)==null?void 0:w.retry,method:(b=C.config)==null?void 0:b.method,isOnline:navigator.onLine?"online":"offline"}}),new k(C.message||"Network request failed","0011")):new k("Unknown network error occurred","0011")}}}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 ZM=Object.defineProperty,eO=Object.getOwnPropertyDescriptor,ns=(s,t,e,r)=>{for(var i=r>1?void 0:r?eO(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&&ZM(t,e,i),i};class Bt extends XM{constructor(e,r){super(e,r);p(this,"telemetry");this.telemetry=e.getValue("telemetry"),this.setHeader("x-realtimekit-version",e.getValue("sdkVersion"))}async getIPDetails(){var r;const{peerId:e}=this;try{const i=await Pu.getIPDetails({peerId:e,apiHostnames:bm(this.context),logger:cm});if(this.logger.log("ipInfo",{ipInfo:i}),((r=i==null?void 0:i.loc)==null?void 0:r.length)>5)return i;throw Error("Insufficient data")}catch(i){this.logger.warn("APIClient.getIPDetails Failed to get ip details",{error:{name:i.name,message:i.message}});return}}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 getPlugins(){var n,o,c,d,l,u,h;if(this.pluginInformation)return this.pluginInformation;const{plugins:e}=(await this.requests.get("/v2/plugins/user")).data.data,r=((o=(n=this.context.getValue("flagsmith").getValue(Z.V1_PLUGINS))==null?void 0:n.toString())==null?void 0:o.split(","))||[],i=e.reduce((g,S)=>(g[r.includes(S.id)?"v1":"v2"].push({...S,name:S.name.replace("v2","")}),g),{v1:[],v2:[]});return(l=(d=(c=this.context.getValue("modules"))==null?void 0:c.devTools)==null?void 0:d.plugins)!=null&&l.length&&((h=(u=this.context.getValue("modules"))==null?void 0:u.devTools)==null||h.plugins.forEach(g=>{var y,w,b;const S={...ho,tags:[...ho.tags],baseUrl:`http://localhost:${g.port}`,name:g.name,picture:(y=g.picture)!=null?y:ho.picture,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),id:g.id,organizationId:this.organizationId,description:(w=g.description)!=null?w:ho.description,staggered:(b=g.staggered)!=null?b:ho.staggered};i.v2.push(S)})),i.v2}async getPluginDetails(e){const{plugin:r}=(await this.requests.get(`/v2/plugins/view/${e}`)).data.data;return r}async getPluginConfig(e){return(await this.fetchClient.get(`${e}/dyte-config.json`)).data}async authorizePlugin(e){const r={peerId:this.peerId},{token:i}=(await this.requests.post(`/v2/plugins/authorize/${e}`,r)).data.data;return i}async getPresignedUrls(e){const r=On(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=bs(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=bs((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 bs(e)}async startRecording(e,r){return(await this.requests.post("/v2/recordings",{...If(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 k("Cant fetch transcript s3 url","1801")}}async getRoomNodeData(){const e=await this.getIPDetails();if(this.ipInfo=e,this.roomDetails)return this.roomDetails;const{title:r}=bs((await this.requests.post("v2/internals/rooms",{ip_information:e})).data.data);return{meetingTitle:r}}}ns([E.trace("APIClient.getIPDetails")],Bt.prototype,"getIPDetails",1),ns([E.trace("APIClient.getICEServers")],Bt.prototype,"getICEServers",1),ns([E.trace("APIClient.getPlugins")],Bt.prototype,"getPlugins",1),ns([E.trace("APIClient.startLivestreaming")],Bt.prototype,"startLivestreaming",1),ns([E.trace("APIClient.stopLivestreaming")],Bt.prototype,"stopLivestreaming",1),ns([E.trace("APIClient.getActiveLivestream")],Bt.prototype,"getActiveLivestream",1),ns([E.trace("APIClient.getUserDetails")],Bt.prototype,"getUserDetails",1),ns([E.trace("APIClient.startRecording")],Bt.prototype,"startRecording",1),ns([E.trace("APIClient.stopRecording")],Bt.prototype,"updateRecording",1),ns([E.trace("APIClient.getActiveRecording")],Bt.prototype,"getActiveRecording",1),ns([E.trace("APIClient.getActiveTranscript")],Bt.prototype,"getActiveTranscript",1),ns([E.trace("APIClient.getRoomNodeData")],Bt.prototype,"getRoomNodeData",1);let wh;function tO(s,t){return wh=new Bt(s,t),wh}function ht(){return wh}const Vn={maxInvocations:5,period:1};function Ot(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 k(`Method rate limit ${u.maxInvocations} invocations/${u.period}sec exceeded`,"0013");return o+=1,n.apply(this,d)},i}}var sO=Object.defineProperty,rO=Object.getOwnPropertyDescriptor,Ps=(s,t,e,r)=>{for(var i=r>1?void 0:r?rO(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};const iO=["text","image","file","custom","poll"],Gd={maxInvocations:180,period:60};let Ht=(HS=class extends $t{constructor(t,e,r,i){const n=t.getValue("logger");super(n);m(this,wl);m(this,Vo);p(this,"messages");m(this,te,void 0);m(this,Ui,void 0);m(this,tt,void 0);m(this,Qn,void 0);p(this,"maxTextLimit",2e3);f(this,Qn,t),f(this,tt,e),f(this,te,r),f(this,Ui,i),this.messages=[]}get telemetry(){return a(this,Qn).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 k("Max character limit breached","0503");if(e&&e.length>0){if(!((i=a(this,te).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,te).permissions)!=null&&n.chatPrivate.text))throw this.logger.error("sendTextMessage::private_chat_permission_denied"),new k("Could not send message to private chat.","0501")}else if(!((c=(o=a(this,te).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,te).permissions)==null?void 0:d.chatPublic)!=null&&l.text))throw this.logger.error("sendTextMessage::public_chat_permission_denied"),new k("Could not send message to public chat.","0501");if(!t)throw this.logger.error("sendTextMessage::message_can_not_be_empty"),new k("Message can not be empty.","0502");let r=[];e&&e.length>0&&(e.push(a(this,te).id),r=a(this,Ui).joined.toArray().filter(u=>e.includes(u.id)).map(u=>u.userId),r.push(a(this,te).userId)),a(this,tt).sendMessage(t,is.TEXT,e)}async sendImageMessageInternal(t,e){var i,n,o,c,d,l;if(e&&e.length>0){if(!((i=a(this,te).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,te).permissions)!=null&&n.chatPrivate.files)){this.logger.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((c=(o=a(this,te).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,te).permissions)==null?void 0:d.chatPublic)!=null&&l.files)){this.logger.error("sendImageMessage::permission_denied");return}if(!t){this.logger.error("sendImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(t.type)){this.logger.error("sendImageMessage::image_type_not_supported",{chat:{imageType:t.type}});return}try{const u=ht(),{getLocation:h,putLocation:g}=await u.getPresignedUrls(t.name);await u.uploadFile(t,g);let S=[];e&&e.length>0&&(e.push(a(this,te).id),S=a(this,Ui).joined.toArray().filter(y=>e.includes(y.id)).map(y=>y.userId),S.push(a(this,te).userId)),a(this,tt).sendMessage(h,is.IMAGE,e)}catch(u){throw new k("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,te).permissions)!=null&&r.chatPrivate.canSend)||!((i=a(this,te).permissions)!=null&&i.chatPrivate.files)){this.logger.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((o=(n=a(this,te).permissions)==null?void 0:n.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,te).permissions)==null?void 0:c.chatPublic)!=null&&d.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!t){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const l=ht(),{getLocation:u,putLocation:h}=await l.getPresignedUrls(t.name);await l.uploadFile(t,h);let g=[];e&&e.length>0&&(e.push(a(this,te).id),g=a(this,Ui).joined.toArray().filter(y=>e.includes(y.id)).map(y=>y.userId),g.push(a(this,te).userId));const S=JSON.stringify({link:u,name:t.name,size:"size"in t?t.size:0});a(this,tt).sendMessage(S,is.FILE,e)}catch(l){throw new k("Error sending file message.","0500",this.logger)}}get rateLimits(){return Gd}updateRateLimits(t,e){Gd.maxInvocations=t,Gd.period=e}async sendTextMessage(t,e){return this.sendTextMessageInternal(t,e)}async sendCustomMessage(t,e){var n,o,c,d,l,u,h,g,S,y,w,b,C,D,F;if(e&&e.length>0){if(!((n=a(this,te).permissions)!=null&&n.chatPrivate.canSend)||!((o=a(this,te).permissions)!=null&&o.chatPrivate.files)||!((c=a(this,te).permissions)!=null&&c.chatPrivate.text)){this.logger.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((l=(d=a(this,te).permissions)==null?void 0:d.chatPublic)!=null&&l.canSend)||!((h=(u=a(this,te).permissions)==null?void 0:u.chatPublic)!=null&&h.files)||!((S=(g=a(this,te).permissions)==null?void 0:g.chatPublic)!=null&&S.text)){this.logger.error("sendCustomMessage::permission_denied");return}const r=async L=>{try{if(typeof L=="string")return{link:L};const B=ht(),{getLocation:W,putLocation:ae}=await B.getPresignedUrls(L.name);return await B.uploadFile(L,ae),{link:W,type:L.type,name:L.name,size:L.size}}catch(B){throw new k("Error sending image message.","0500",this.logger)}},i={...t,files:await Promise.all((w=(y=t.files)!=null?y:[])==null?void 0:w.map(async L=>r(L))),images:await Promise.all((C=(b=t.images)!=null?b:[])==null?void 0:C.map(async L=>r(L))),videos:await Promise.all((F=(D=t.videos)!=null?D:[])==null?void 0:F.map(async L=>r(L)))};a(this,tt).sendMessage(JSON.stringify(i),is.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,te).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(n=a(this,te).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,tt).editMessage(t,e,is.TEXT)}async editImageMessage(t,e){var i,n,o,c;if(!((n=(i=a(this,te).permissions)==null?void 0:i.chatPublic)!=null&&n.canSend)||!((c=(o=a(this,te).permissions)==null?void 0:o.chatPublic)!=null&&c.files)){this.logger.error("editImageMessage::permission_denied");return}if(!e){this.logger.error("editImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(e.type)){this.logger.error("sendImageMessage::image_type_not_supported",{chat:{imageType:e.type}});return}try{const d=ht(),{getLocation:l,putLocation:u}=await d.getPresignedUrls(e.name);await d.uploadFile(e,u),a(this,tt).editMessage(t,l,is.IMAGE)}catch(d){throw new k("Error editing image message.","0500",this.logger)}}async editFileMessage(t,e){var r,i,n,o;if(!((i=(r=a(this,te).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(n=a(this,te).permissions)==null?void 0:n.chatPublic)!=null&&o.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!e){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const c=ht(),{getLocation:d,putLocation:l}=await c.getPresignedUrls(e.name);await c.uploadFile(e,l),a(this,tt).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),is.FILE)}catch(c){throw new k("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,tt).deleteMessage(t)}getMessagesByUser(t){return this.messages.filter(e=>e.userId===t)}getMessagesByType(t){return this.messages.filter(e=>e.type===t)}async pin(t){if(!a(this,Vo,ap))throw new k("Can`t pin message without joining room","0505");try{await a(this,tt).setPinState(t,!0)}catch(e){throw new k(`No message found with id: ${t}`,"0504")}}async unpin(t){if(!a(this,Vo,ap))throw new k("Can`t unpin message without joining room","0505");try{await a(this,tt).setPinState(t,!1)}catch(e){throw new k(`No message found with id: ${t}`,"0504")}}async fetchPublicMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await a(this,tt).getChatMessagesPaginated(t,e,r==="before")).messages.map(o=>as.formatSocketPeerMessage(o))}async fetchPrivateMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after",userId:i}){return(await a(this,tt).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"userId",userId:i})).messages.map(c=>as.formatSocketPeerMessage(c))}async fetchPinnedMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await a(this,tt).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"pinned",pinned:!0})).messages.map(o=>as.formatSocketPeerMessage(o))}async getMessages(t,e,r,i=0){const n=await a(this,tt).getChatMessagesPaginated(t,e,r);return{messages:n.messages.map(o=>as.formatSocketPeerMessage(o)),next:n.next}}async searchMessages(t,e){throw new k("searchMessages is disabled! Please use `fetchPublicMessages` method instead.","0506")}get pinned(){return this.messages.filter(t=>t.pinned)}},te=new WeakMap,Ui=new WeakMap,tt=new WeakMap,Qn=new WeakMap,wl=new WeakSet,ov=function(){return a(this,Qn).getValue("connectionHandler")},Vo=new WeakSet,ap=function(){return a(this,wl,ov).socketJoined===!0},HS);Ps([E.trace("Chat.sendTextMessage"),Ot(Gd)],Ht.prototype,"sendTextMessage",1),Ps([E.trace("Chat.sendImageMessage"),Ot({maxInvocations:20,period:60})],Ht.prototype,"sendImageMessage",1),Ps([E.trace("Chat.sendFileMessage"),Ot({maxInvocations:20,period:60})],Ht.prototype,"sendFileMessage",1),Ps([E.trace("Chat.sendMessage"),Ot({maxInvocations:180,period:60})],Ht.prototype,"sendMessage",1),Ps([E.trace("Chat.editTextMessage")],Ht.prototype,"editTextMessage",1),Ps([E.trace("Chat.editImageMessage")],Ht.prototype,"editImageMessage",1),Ps([E.trace("Chat.editFileMessage")],Ht.prototype,"editFileMessage",1),Ps([E.trace("Chat.editMessage")],Ht.prototype,"editMessage",1),Ps([E.trace("Chat.deleteMessage")],Ht.prototype,"deleteMessage",1),Ps([E.trace("Chat.searchMessages")],Ht.prototype,"searchMessages",1),Ht=Ps([lt("0500")],Ht);var nO=Object.defineProperty,aO=Object.getOwnPropertyDescriptor,oO=(s,t,e,r)=>{for(var i=r>1?void 0:r?aO(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};const Br=(qS=class{constructor(s,t,e,r){p(this,"chat");p(this,"chatSocketHandler");p(this,"self");m(this,Fi,void 0);f(this,Fi,s),this.chatSocketHandler=t,this.chat=new Ht(s,t,e,r),this.self=e,this.setupEvents()}get telemetry(){return a(this,Fi).getValue("telemetry")}get logger(){return a(this,Fi).getValue("logger")}static async init(s,t,e,r){return new Br(s,t,e,r)}static formatMessage(s){return{...s,time:new Date(s.time),type:iO[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 is.TEXT:{e.message=s.payload;break}case is.IMAGE:{e.link=s.payload;break}case is.FILE:{const{link:r,name:i,size:n}=JSON.parse(s.payload);e.link=r,e.name=i,e.size=n;break}case is.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 Br.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=Sf.fromBinary(s.payload).messages;this.chat.messages=t.map(e=>Br.formatSocketPeerMessage(e))}setupEvents(){a(this,Fi).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,async()=>{this.getChatMessages()}),this.chatSocketHandler.on(Ge.sendMessageToRoom,s=>{if(!s.message)return;const t=Br.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=Br.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=Br.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=Br.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})})}},Fi=new WeakMap,qS);let as=Br;oO([E.trace("ChatController.setupEvents")],as.prototype,"setupEvents",1);var cO=Object.defineProperty,dO=Object.getOwnPropertyDescriptor,lO=(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};let bh=(jS=class extends $t{constructor(t,e,r){const i=t.getValue("logger");super(i);m(this,bl);m(this,Pl);p(this,"items");m(this,Xn,void 0);m(this,Zn,void 0);m(this,Lo,void 0);f(this,Lo,t),f(this,Xn,e),f(this,Zn,r),this.items=[]}async create(t,e,r=!1,i=!1){if(!a(this,Pl,dv))throw new k("Can't create polls without joining room","0705");if(!a(this,Xn).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,Zn).createPoll(t,e,r,i)}async vote(t,e){if(!a(this,Xn).permissions.polls.canVote){this.logger.error("Polls::vote::permission_denied");return}await a(this,Zn).votePoll(t,e)}},bl=new WeakSet,cv=function(){return a(this,Lo).getValue("connectionHandler")},Pl=new WeakSet,dv=function(){var t;return((t=a(this,bl,cv))==null?void 0:t.socketJoined)===!0},Xn=new WeakMap,Zn=new WeakMap,Lo=new WeakMap,jS);bh=lO([lt("0700")],bh);var uO=Object.defineProperty,hO=Object.getOwnPropertyDescriptor,pO=(s,t,e,r)=>{for(var i=r>1?void 0:r?hO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&uO(t,e,i),i};const Ln=(GS=class{constructor(s,t,e){p(this,"polls");m(this,Yr,void 0);m(this,ea,void 0);m(this,$i,void 0);this.polls=new bh(s,t,e),f(this,ea,t),f(this,Yr,s),f(this,$i,e),this.setupEvents()}get telemetry(){return a(this,Yr).getValue("telemetry")}get logger(){return a(this,Yr).getValue("logger")}static async init(s,t,e){return new Ln(s,t,e)}canViewPolls(){return a(this,ea).permissions.polls.canView}setupEvents(){const s={[ar.createPoll]:r=>{r.poll&&this.updatePoll(Ln.formatSocketServicePoll(r.poll))},[ar.updatePoll]:r=>{r.poll&&this.updatePoll(Ln.formatSocketServicePoll(r.poll))},[ar.votePoll]:r=>{r.poll&&this.updatePoll(Ln.formatSocketServicePoll(r.poll))}},t=()=>{a(this,Yr).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,Yr).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,$i).removeListeners(r)})};a(this,ea).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}=IM.fromBinary(s.payload);this.polls.items=t.map(e=>Ln.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}}},Yr=new WeakMap,ea=new WeakMap,$i=new WeakMap,GS);let Mf=Ln;pO([E.trace("PollController.setupEvents")],Mf.prototype,"setupEvents",1);var gO=Object.defineProperty,mO=Object.getOwnPropertyDescriptor,fO=(s,t,e,r)=>{for(var i=r>1?void 0:r?mO(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&&gO(t,e,i),i},Of=(s=>(s[s.User=0]="User",s[s.Meeting=1]="Meeting",s))(Of||{});let Ph=(WS=class extends $t{constructor(t,e,r,i,n){const o=t.getValue("logger");super(o);m(this,xo);p(this,"selfActiveTab");p(this,"broadcastTabChanges");m(this,ta,void 0);m(this,Bi,void 0);m(this,Uo,void 0);p(this,"viewType");p(this,"meetingStartedTimestamp");p(this,"meetingTitle");p(this,"sessionId");f(this,ta,t),f(this,Bi,e),this.viewType=r,f(this,Uo,i),this.meetingTitle=n,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return a(this,xo,op).socketState}get mediaState(){return a(this,xo,op).mediaState}get meetingId(){return a(this,ta).getValue("meetingId")}setBroadcastTabChanges(t){if(!a(this,Bi).permissions.canSpotlight)throw this.logger.error("Spotlight::setSpotlighted::permission_denied"),new k("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,Uo).broadcastMessage("spotlight",{userId:a(this,Bi).userId,currentTab:this.selfActiveTab})}},ta=new WeakMap,xo=new WeakSet,op=function(){return a(this,ta).getValue("connectionHandler")},Bi=new WeakMap,Uo=new WeakMap,WS);Ph=fO([lt("0800")],Ph);function SO(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===`
|
|
12
|
-
`&&o?(t==="\r"&&(e[i]=e[i].slice(0,-1)),e=r[++n]=[c=""],i=0):e[i]+=c,t=c;return r}var
|
|
13
|
-
`).map(e=>Hr.parseTranscript(e,!1)).filter(Boolean):[]}async getActiveTranscript(){try{const t=ht(),{transcript:e}=await t.getActiveTranscript();this.transcripts=Hr.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)}},Fo=new WeakMap,JS);Df([E.trace("Ai.getActiveTranscript")],Hr.prototype,"getActiveTranscript",1),Hr=Df([lt("0000")],Hr);var yO=Object.defineProperty,EO=Object.getOwnPropertyDescriptor,wO=(s,t,e,r)=>{for(var i=r>1?void 0:r?EO(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&&yO(t,e,i),i};const Nf=(KS=class{constructor(s,t,e,r,i,n){p(this,"meta");p(this,"ai");m(this,Qr,void 0);m(this,sa,void 0);p(this,"aiSocketHandler");m(this,Kt,void 0);f(this,Kt,s),this.meta=new Ph(s,t,t.config.viewType,e,n),this.ai=r,f(this,Qr,t),f(this,sa,e),this.aiSocketHandler=i,this.setupEvents()}get telemetry(){return a(this,Kt).getValue("telemetry")}get logger(){return a(this,Kt).getValue("logger")}static async init(s,t,e,r,i){const n=await Hr.init(s,t.permissions.transcriptionEnabled);return new Nf(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,Of.Meeting),this.meta.emit("activeTabUpdate",s.currentTab))}setupEvents(){a(this,Kt).getValue("peerSessionStore").on(_.TRANSPORT_STATE_UPDATE,s=>{this.meta.emit("mediaConnectionUpdate",s)}),a(this,Kt).getValue("peerSessionStore").on(_.SOCKET_STATE_UPDATE,s=>{this.meta.emit("socketConnectionUpdate",s)}),a(this,Kt).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,Kt).getValue("peerSessionStore").on(_.PRODUCER_SCORE_UPDATE,({score:s})=>{s<5&&this.meta.emit("poorConnection",{score:s})}),a(this,Qr).permissions.canSpotlight&&(this.logger.info("MetaController::Asserting Spotlight"),this.meta.selfActiveTab&&a(this,sa).broadcastMessage("spotlight",{userId:a(this,Qr).userId,currentTab:this.meta.selfActiveTab})),a(this,Kt).getValue("peerSessionStore").on(_.PEER_JOINED_INTERNAL,async s=>{a(this,Qr).permissions.canSpotlight&&this.meta.selfActiveTab&&a(this,sa).broadcastToPeers("spotlight",[s.id],{userId:a(this,Qr).userId,currentTab:this.meta.selfActiveTab})}),a(this,Kt).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,Kt).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(U.transcript,s=>{const{meetingId:t,transcript:e,isPartial:r}=s;let i;try{i=Hr.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),this.meta.emit("transcript",i);const{peerId:n,name:o,transcript:c}=i;this.logger.debug(`${t} Received transcript for peer ${n} - ${o}: ${c}`)})}},Qr=new WeakMap,sa=new WeakMap,Kt=new WeakMap,KS);let Vf=Nf;wO([E.trace("MetaController.setupEvents")],Vf.prototype,"setupEvents",1);const So={},cr={executeWithLock({methodName:s,lockName:t,timeout:e}){return(r,i,n)=>{const o=n.value;return n.value=function(...d){var y,w;const l=(w=(this==null?void 0:this.peerId)||((y=d[0])==null?void 0:y.authToken))!=null?w:"",u=`${t}-${l}`,h=this==null?void 0:this.logger;if(So[u]){const b=new Error(`Unsupported concurrent calls on method: ${s}.`);throw b.name="UnsupportedConcurrentMethodExecution",h==null||h.error("Locker::UnsupportedConcurrentMethodExecution",{error:{stack:b.stack},locker:{methodName:s,lockName:u}}),b}So[u]=!0;const g=setTimeout(()=>delete So[u],e),S=o.apply(this,d);return Promise.resolve(S).then(()=>{delete So[u],clearTimeout(g)}).catch(()=>{delete So[u],clearTimeout(g)}),S},n}}};var bO=Object.defineProperty,PO=Object.getOwnPropertyDescriptor,_i=(s,t,e,r)=>{for(var i=r>1?void 0:r?PO(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 qr extends $t{constructor(e,r,i,n,o){const c=e.getValue("logger");super(c);m(this,Bo);m(this,ra);m(this,ds,void 0);m(this,_l,void 0);m(this,ne,void 0);m(this,$o,void 0);m(this,js,void 0);m(this,st,void 0);f(this,st,e),f(this,ds,n),f(this,_l,o),f(this,ne,r),f(this,$o,i),f(this,js,[]),this.setupEvents()}get telemetry(){return a(this,st).getValue("telemetry")}get status(){return a(this,st).getValue("stageStatus")}setupEvents(){const e={[_.GET_STAGE_REQUESTS]:async n=>{f(this,js,n)},[_.UPDATE_STAGE_REQUESTS]:async({add:n})=>{const o=a(this,js).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,st).getValue("peerSessionStore").onAsync(n,o)})},i=()=>{Object.entries(e).forEach(([n,o])=>{a(this,st).getValue("peerSessionStore").removeListener(n,o)})};a(this,ne).permissions.on("permissionsUpdate",n=>{const{canAcceptProductionRequests:o}=n;o!==void 0&&(a(this,ne).permissions.acceptStageRequests?(r(),a(this,ds).getStageRequests()):(i(),f(this,js,[]),this.emit("stageAccessRequestUpdate",a(this,js))))}),a(this,ne).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!a(this,ne).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new k("Stage is disabled","2003");if(!a(this,ne).permissions.acceptStageRequests)throw this.logger.error("Stage::get_access_request::permission_denied"),new k("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 f(this,js,e),{stageRequests:a(this,js)}}async requestAccess(){if(!a(this,ne).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new k("Stage is disabled","2003");if(this.status!=="OFF_STAGE")throw new k(`Unable to request access you are currently ${this.status}`,"2006");if(a(this,ne).permissions.stageAccess===H.Allowed){x(this,ra,mu).call(this,"ACCEPTED_TO_JOIN_STAGE");return}a(this,ds).requestAccess(),x(this,ra,mu).call(this,"REQUESTED_TO_JOIN_STAGE")}async cancelRequestAccess(){if(!a(this,ne).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new k("Stage is disabled","2003");a(this,ds).cancelRequestAccess(),x(this,ra,mu).call(this,"OFF_STAGE")}grantAccess(e){if(!a(this,ne).roomJoined)throw new k("Can`t grant for participant without joining room");if(!a(this,ne).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new k("Stage is disabled","2003");if(!a(this,ne).permissions.acceptStageRequests)throw this.logger.error("Stage::grant_access::permission_denied"),new k("You do not have permission to perform this action","2001");return a(this,ds).grantAccess(e)}denyAccess(e){if(!a(this,ne).roomJoined)throw new k("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!a(this,ne).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new k("Stage is disabled","2003");if(!a(this,ne).permissions.acceptStageRequests)throw this.logger.error("Stage::deny_access::permission_denied"),new k("You do not have permission to perform this action","2001");return a(this,ds).denyAccess(e)}get peerId(){return a(this,st).getValue("peerId")}async join(){const e=a(this,st).getValue("viewType");if(this.status==="ON_STAGE")throw new k("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||a(this,ne).permissions.stageAccess===H.NotAllowed)throw new k(`Unable to join stage you are currently ${this.status}`,"2006");if(a(this,st).setValue("stageStatus","ON_STAGE",!1),await a(this,ds).joinStage(),e===tr.Livestream){await a(this,st).getValue("selfController").joinRoom();return}a(this,st).notify("stageStatus"),a(this,ne).audioEnabled&&a(this,Bo,cp).shareMic(a(this,ne).audioTrack),a(this,ne).videoEnabled&&a(this,Bo,cp).shareWebcam(a(this,ne).videoTrack)}async leave(){if(!a(this,ne).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new k("Stage is disabled","2003");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new k(`Unable to leave stage you are currently ${this.status}`,"2006");a(this,ne).setIsPinned(!1),a(this,st).setValue("stageStatus","OFF_STAGE",!1),await a(this,ds).leaveStage(a(this,ne).userId);try{await a(this,st).getValue("peerSessionStore").emitAsync(_.LEAVE_MEDIA_ROOM,"stageLeft")}catch(e){this.logger.error("Stage::leave::emitAsync::failed",{error:e})}a(this,st).notify("stageStatus")}async kick(e){if(!a(this,ne).roomJoined)throw new k("Can`t kick participant without joining room","2005");if(!a(this,ne).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new k("Stage is disabled","2003");if(!a(this,ne).permissions.acceptStageRequests)throw this.logger.error("Stage::kick::permission_denied"),new k("You do not have permissions for kick","2001");return a(this,ds).kick(e)}}ds=new WeakMap,_l=new WeakMap,ne=new WeakMap,$o=new WeakMap,js=new WeakMap,st=new WeakMap,Bo=new WeakSet,cp=function(){return a(this,st).getValue("roomNodeClient")},ra=new WeakSet,mu=async function(e){this.status!==e&&a(this,st).setValue("stageStatus",e)},_i([E.trace("Stage.getStageRequests")],qr.prototype,"getAccessRequests",1),_i([E.trace("Stage.requestAccess")],qr.prototype,"requestAccess",1),_i([E.trace("Stage.cancelRequestAccess")],qr.prototype,"cancelRequestAccess",1),_i([E.trace("Stage.grantAccess")],qr.prototype,"grantAccess",1),_i([E.trace("Stage.denyAccess")],qr.prototype,"denyAccess",1),_i([cr.executeWithLock({methodName:"joinStage",lockName:"Stage.join",timeout:5e3}),E.trace("Stage.joinStage")],qr.prototype,"join",1),_i([E.trace("Stage.leaveStage")],qr.prototype,"leave",1);function _O(s){return!(s.viewType==="LIVESTREAM"||s.viewType==="CHAT")}function _h(s){switch(s){case nr.UNSPECIFIED:return"OFF_STAGE";case nr.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case nr.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case nr.OFF_STAGE:return"OFF_STAGE";case nr.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var RO=Object.defineProperty,CO=Object.getOwnPropertyDescriptor,kO=(s,t,e,r)=>{for(var i=r>1?void 0:r?CO(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};class Lf{constructor(t,e,r,i,n){p(this,"stage");m(this,Xr,void 0);m(this,ks,void 0);m(this,Zr,void 0);m(this,Ho,0);m(this,Pt,void 0);f(this,Pt,t),this.stage=new qr(t,i,n,e,r),f(this,Zr,e),f(this,Xr,i),f(this,ks,n),this.setupEvents()}get telemetry(){return a(this,Pt).getValue("telemetry")}get logger(){return a(this,Pt).getValue("logger")}setupEvents(){a(this,Pt).subscribe("stageStatus",t=>{this.stage.emit("stageStatusUpdate",t)}),a(this,Zr).on(U.grantStageAccess,()=>{a(this,Xr).permissions.stageAccess!==H.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),a(this,Zr).on(U.peerStageStatusUpdate,t=>{t!==void 0&&(t.peerId===a(this,Xr).id?this.selfStageStatusHandler(t):this.peerStageStatusHandler(t))}),a(this,Zr).on(U.denyStageAccess,()=>{a(this,Xr).permissions.stageAccess!==H.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),a(this,Zr).on(U.getStageRequests,async t=>{var r;if(a(this,Xr).permissions.stageAccess!==H.Allowed)return;const e=(r=t==null?void 0:t.stageRequests)!=null?r:[];await a(this,Pt).getValue("peerSessionStore").emitAsync(_.GET_STAGE_REQUESTS,e),a(this,Ho)<e.length&&e.length>0&&this.stage.emit("newStageRequest",{count:e.length}),f(this,Ho,e.length),this.stage.emit("stageAccessRequestUpdate",e)})}getCurrentStageRequests(){return a(this,ks).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,Pt).setValue("stageStatus",t)}selfStageStatusHandler(t){const e=_h(t.stageType),r=a(this,Pt).getValue("stageStatus");if(r!==e)switch(t.stageType){case 1:a(this,Pt).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,Pt).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}async peerStageStatusHandler(t){const e=a(this,ks).joined.get(t.peerId),r=a(this,ks).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,Pt).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:a(this,ks).viewMode,page:a(this,ks).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,Pt).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:a(this,ks).viewMode,page:a(this,ks).currentPage});break}a(this,Pt).getValue("peerSessionStore").emit(_.UPDATE_PEER_STAGE_STATUS,{id:e.id,status:e.stageStatus})}}Xr=new WeakMap,ks=new WeakMap,Zr=new WeakMap,Ho=new WeakMap,Pt=new WeakMap,kO([E.trace("Stage.setupEvents")],Lf.prototype,"setupEvents",1);var IO=Object.defineProperty,AO=Object.getOwnPropertyDescriptor,Wd=(s,t,e,r)=>{for(var i=r>1?void 0:r?AO(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&&IO(t,e,i),i};const Oe={getPeer:14,getPeers:15,chatMessage:16,getRoomName:17,getDisplayTitle:18,getPluginInitiator:19,customPluginEventToParent:20,peerJoined:22,peerLeft:23,sendData:24,stageStatusUpdate:25,peerStageStatusUpdate:26};let xn=(zS=class extends Dn{constructor(t,{baseURL:e,createdAt:r,description:i,id:n,name:o,organizationId:c,picture:d,private:l,published:u,staggered:h,tags:g,type:S,updatedAt:y},w,b,C,D,F){const L=t.getValue("logger");super(L);m(this,gt,void 0);p(this,"baseURL");p(this,"createdAt");p(this,"description");p(this,"id");p(this,"name");m(this,zt,void 0);m(this,ia,void 0);m(this,na,void 0);p(this,"organizationId");p(this,"picture");p(this,"private");p(this,"published");p(this,"staggered");p(this,"tags");p(this,"type");p(this,"updatedAt");m(this,Sr,void 0);p(this,"config");m(this,aa,void 0);p(this,"active");p(this,"iframes");p(this,"enabledBy");m(this,ei,void 0);m(this,oa,void 0);f(this,ei,t),this.baseURL=e,this.createdAt=new Date(r),this.description=i,this.id=n,this.name=o,f(this,zt,b),this.organizationId=c,this.picture=d,this.private=l,this.published=u,this.staggered=h,this.tags=g,this.type=S,this.updatedAt=new Date(y),this.active=!1,this.iframes=new Map,f(this,gt,w),f(this,ia,C),f(this,na,D),this.enabledBy="",f(this,oa,F)}get telemetry(){return a(this,ei).getValue("telemetry")}sendIframeEvent(t){this.iframes.size&&this.iframes.forEach(e=>{const{iframe:r}=e;r&&(navigator.isReactNative?r.postMessage(JSON.stringify(t)):r.contentWindow.postMessage(t,"*"))})}async handleIframeMessage(t){var o;if(!this.active)return;const e=t,{payload:r,uuid:i,type:n}=e;switch(n){case G.customPluginEventToRoom:{a(this,gt).customPluginEventToRoom(this.id,r,i);break}case G.customPluginEventToPeers:{a(this,gt).customPluginEventToPeers(this.id,r.peerIds,r,i);break}case G.enablePluginForRoom:{a(this,gt).enablePluginForRoom(this.id,i);break}case G.enablePluginForPeers:{a(this,gt).enablePluginForPeers(this.id,r.peerIds,i);break}case G.disablePluginForRoom:{a(this,gt).disablePluginForRoom(this.id,i);break}case G.disablePluginForPeers:{a(this,gt).disablePluginForPeers(this.id,r.peerIds,i);break}case G.storeInsertKeys:{a(this,gt).storeInsertKeys(this.id,r.store,r.insertKeys,i);break}case G.storeGetKeys:{a(this,gt).storeGetKeys(this.id,r.store,r.getKeys,i);break}case G.storeDeleteKeys:{a(this,gt).storeDeleteKeys(this.id,r.store,r.deleteKeys,i);break}case G.storeDelete:{a(this,gt).storeDelete(this.id,r.store,i);break}case Oe.chatMessage:{const{messagePayload:c,peerIds:d}=r;if(!a(this,na)){this.sendIframeEvent({type:Oe.chatMessage,uuid:e.uuid,payload:{error:"Chat is disabled for this room."}});return}try{await a(this,na).sendMessage(c,d),this.sendIframeEvent({type:Oe.chatMessage,uuid:e.uuid,payload:{success:!0}})}catch(l){this.sendIframeEvent({type:Oe.chatMessage,uuid:e.uuid,payload:{error:l}})}break}case Oe.getPeer:{let c;const{peerId:d}=r,l={...a(this,zt),id:a(this,zt).id,isRecorder:(o=a(this,zt).permissions)==null?void 0:o.isRecorder,isHidden:a(this,zt).permissions.hiddenParticipant,stageStatus:a(this,zt).stageStatus};d?(c=a(this,ia).joined.get(r.peerId),a(this,zt).id===d&&(c=l)):c=l,this.sendIframeEvent({type:Oe.getPeer,payload:{peer:c&&jd(c)},uuid:e.uuid});break}case Oe.getPeers:{const c=a(this,ia).joined.toArray().map(d=>jd(d));this.sendIframeEvent({type:Oe.getPeers,payload:{peers:c},uuid:e.uuid});break}case Oe.getPluginInitiator:{this.sendIframeEvent({type:Oe.getPluginInitiator,payload:{enabledBy:this.enabledBy},uuid:e.uuid});break}case Oe.getDisplayTitle:{this.sendIframeEvent({type:Oe.getDisplayTitle,payload:{displayTitle:a(this,oa)},uuid:e.uuid});break}case Oe.getRoomName:{this.sendIframeEvent({type:Oe.getRoomName,payload:{roomName:a(this,ei).getValue("meetingId")},uuid:e.uuid});break}case Oe.customPluginEventToParent:{this.emit(e.payload.eventName,e.payload.data);break}}}sendData(t){this.active&&(this.logger.info("Plugin::SendData",{plugin:{id:this.id,name:this.name,data:{eventName:t.eventName}}}),this.sendIframeEvent({type:Oe.sendData,uuid:"",payload:t}))}removePluginView(t="default"){var i;const{iframe:e,listener:r}=(i=this.iframes.get(t))!=null?i:{};(e||r)&&(navigator.isReactNative?e.props.onMessage=void 0:window.removeEventListener("message",r),this.iframes.delete(t))}addPluginView(t,e="default"){var o;if(!a(this,aa))throw this.logger.error("Plugin::addPluginView::no_auth_token_set_for_plugin"),new k("No auth token set for plugin.","0602");if(!t)throw this.logger.error("Plugin::addPluginView::iframe_was_not_provided"),new k("Iframe was not provided.","0603");this.removePluginView(e);const r=t,i=new URL(this.baseURL),n={auth:a(this,aa),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:a(this,ei).getValue("apiBase"),pluginId:this.id,roomName:(o=a(this,ei).getValue("meetingId"))!=null?o:"",displayTitle:a(this,oa)};if(Object.keys(n).forEach(c=>{i.searchParams.set(c,n[c])}),r.src=i.href,r.allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",r.title=e,navigator.isReactNative)r.props.onMessage=c=>{this.handleIframeMessage(JSON.parse(c.nativeEvent.data))},this.iframes.set(e,{iframe:r});else{const c=async d=>{d.source===t.contentWindow&&await this.handleIframeMessage(d.data)};window.addEventListener("message",c),this.iframes.set(e,{iframe:r,listener:c})}}setActive(t){var e,r;if(this.active=t,t){this.emit("stateUpdate",{active:this.active,pluginId:this.id,bind:this.addPluginView.bind(this),views:(e=this.config)==null?void 0:e.views});return}this.active=!1,this.emit("stateUpdate",{active:this.active,pluginId:this.id,views:(r=this.config)==null?void 0:r.views})}async activateForSelf(){const t=ht(),e=await t.authorizePlugin(this.id);f(this,aa,e),f(this,Sr,new Date);try{const r=await t.getPluginConfig(this.baseURL);this.config=r}catch(r){this.logger.error("Plugin::activateForSelf",{error:r})}this.setActive(!0),this.emit("enabled")}deactivateForSelf(){Array.from(this.iframes.keys()).forEach(t=>{this.removePluginView(t)}),f(this,Sr,void 0),this.iframes.clear(),this.setActive(!1),this.emit("closed")}async enable(){return this.activateForSelf()}disable(){return this.deactivateForSelf()}async activate(){var t,e;this.active||(e=(t=a(this,zt).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(a(this,gt).addPlugin(this.id,this.staggered),f(this,Sr,new Date),this.logger.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}}))}async deactivate(){var t,e;this.active&&(!((e=(t=a(this,zt).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==a(this,zt).id||(a(this,gt).removePlugin(this.id),this.logger.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:a(this,Sr)?new Date().getTime()-a(this,Sr).getTime():0}}),f(this,Sr,void 0)))}},gt=new WeakMap,zt=new WeakMap,ia=new WeakMap,na=new WeakMap,Sr=new WeakMap,aa=new WeakMap,ei=new WeakMap,oa=new WeakMap,zS);Wd([Ot({maxInvocations:5,period:1})],xn.prototype,"sendData",1),Wd([E.trace("Plugin.activatePlugin")],xn.prototype,"activate",1),Wd([E.trace("Plugin.deactivatePlugin")],xn.prototype,"deactivate",1),xn=Wd([lt("0600")],xn);class xf extends Map{constructor(e,r=void 0){const{onAddEvent:i,onDeleteEvent:n,onClearEvent:o}=e;super();m(this,$e,void 0);m(this,Hi,void 0);p(this,"onAddEvent");p(this,"onDeleteEvent");p(this,"onClearEvent");f(this,$e,new Dn(r)),this.onAddEvent=i,this.onDeleteEvent=n,this.onClearEvent=o,f(this,Hi,new Map)}emit(e,...r){return a(this,$e).emit(e,...r)}on(e,r){return a(this,$e).on(e,r)}addListener(e,r){return a(this,$e).addListener(e,r)}off(e,r){return a(this,$e).off(e,r)}once(e,r){return a(this,$e).once(e,r)}prependListener(e,r){return a(this,$e).prependListener(e,r)}prependOnceListener(e,r){return a(this,$e).prependOnceListener(e,r)}removeListener(e,r){return a(this,$e).removeListener(e,r)}removeAllListeners(e){return a(this,$e).removeAllListeners(e)}listeners(e){return a(this,$e).listeners(e)}listenerCount(e){return a(this,$e).listenerCount(e)}getMaxListeners(){return a(this,$e).getMaxListeners()}setMaxListeners(e){return a(this,$e).setMaxListeners(e)}eventNames(){return a(this,$e).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,Hi).set(e,o),r.on("*",o),i&&a(this,$e).emit(this.onAddEvent,r),n}delete(e,r=!0,i=!1){const n=this.get(e);if(!n)return!1;n.removeListener("*",a(this,Hi).get(e));const o=super.delete(e);return i&&n.removeAllListeners(),r&&a(this,$e).emit(this.onDeleteEvent,n),o}clear(e=!0,r=!1){this.forEach(n=>{n.removeListener("*",a(this,Hi).get(n.id)),r&&n.removeAllListeners()});const i=super.clear();return e&&a(this,$e).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}$e=new WeakMap,Hi=new WeakMap;class Uf extends xf{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 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};let Rh=class{constructor(s){p(this,"all");p(this,"active");this.all=new Uf(s),this.active=new Uf(s)}};Rh=DO([lt("0600")],Rh);var NO=Object.defineProperty,VO=Object.getOwnPropertyDescriptor,Jd=(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&&NO(t,e,i),i};const Ff=(YS=class{constructor(s,t,e,r){p(this,"plugins");m(this,ls,void 0);m(this,ca,void 0);m(this,Is,void 0);f(this,ls,t),f(this,ca,e),f(this,Is,s),this.plugins=r,this.setupEvents()}get telemetry(){return a(this,Is).getValue("telemetry")}get logger(){return a(this,Is).getValue("logger")}static async init(s,t,e,r,i,n,o,c){const d=s.getValue("logger"),l=new Rh(d);return t.forEach(u=>{const h=new xn(s,u,e,n,o,i,c);l.all.add(h)}),new Ff(s,e,r,l)}async getRoomPlugins(){var t;const{plugins:s}=await a(this,ls).getActivePlugins();(t=this.plugins.active)==null||t.toArray().forEach(e=>{this.disablePlugin({id:e.id})}),await Promise.all(s.map(e=>this.enablePlugin({id:e.pluginId,enabledBy:e.enabledBy})))}async enablePlugin({id:s,enabledBy:t}){const e=this.plugins.all.get(s);e&&(await e.activateForSelf(),e.enabledBy=t)}async disablePlugin({id:s}){const t=this.plugins.all.get(s);t&&t.deactivateForSelf()}sendIframeEvent(s,t,e,r){const i=this.plugins.all.get(t);i&&i.sendIframeEvent({type:s,uuid:e,payload:r})}broadcastIframeEvent(s,t){this.plugins.active.forEach(e=>{this.sendIframeEvent(s,e.id,"",t)})}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,Is).getValue("peerSessionStore").onAsync(_.SOCKET_SERVICE_ROOM_JOINED,async()=>{await this.getRoomPlugins(),this.logger.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to fetch plugins.")}),a(this,ls).on(G.addPlugin,async s=>{var e;const t=s.pluginId;(e=this.plugins.all.get(t))!=null&&e.active||await this.enablePlugin({id:t,enabledBy:s.enabledBy})}),a(this,ls).on(G.removePlugin,async s=>{var e;const t=s.pluginId;(e=this.plugins.all.get(t))!=null&&e.active&&await this.disablePlugin({id:t})}),[G.enablePluginForPeers,G.enablePluginForRoom].forEach(s=>{a(this,ls).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{enabledBy:t.enabledBy})})}),[G.disablePluginForPeers,G.disablePluginForRoom].forEach(s=>{a(this,ls).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{disabledBy:t.disabledBy})})}),[G.customPluginEventToPeers,G.customPluginEventToRoom].forEach(s=>{a(this,ls).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{data:JSON.parse(new TextDecoder().decode(t.pluginData))})})}),[G.storeInsertKeys,G.storeGetKeys,G.storeDeleteKeys].forEach(s=>{a(this,ls).on(s,async(t,e)=>{var i;const r=(i=t.storeItems)==null?void 0:i.map(n=>{var o;return{timestamp:n.timestamp,peerId:n.peerId,payload:JSON.parse((o=n.payload)!=null&&o.length?new TextDecoder().decode(n.payload):"{}"),key:n.storeKey}});this.sendIframeEvent(s,t.pluginId,e,{storeName:t.storeName,storeItems:r})})}),a(this,ls).on(G.storeDelete,async(s,t)=>{this.sendIframeEvent(G.storeDelete,s.pluginId,t,{storeName:s.storeName})}),a(this,ca).on(Ge.sendMessageToPeers,s=>{const t=as==null?void 0:as.formatSocketPeerMessage(s.message);this.broadcastIframeEvent(Oe.chatMessage,{message:t})}),a(this,ca).on(Ge.sendMessageToRoom,s=>{const t=as==null?void 0:as.formatSocketPeerMessage(s.message);this.broadcastIframeEvent(Oe.chatMessage,{message:t})}),a(this,Is).getValue("peerSessionStore").on(_.PEER_JOINED_INTERNAL,s=>{const t=jd(s);this.broadcastIframeEvent(Oe.peerJoined,t)}),a(this,Is).getValue("peerSessionStore").on(_.PEER_CLOSED,s=>{this.broadcastIframeEvent(Oe.peerLeft,s)}),a(this,Is).getValue("peerSessionStore").on(_.UPDATE_PEER_STAGE_STATUS,s=>{this.broadcastIframeEvent(Oe.peerStageStatusUpdate,s)}),a(this,Is).subscribe("stageStatus",s=>{this.broadcastIframeEvent(Oe.stageStatusUpdate,s)})}},ls=new WeakMap,ca=new WeakMap,Is=new WeakMap,YS);let vo=Ff;Jd([E.trace("PluginController.getRoomPlugins")],vo.prototype,"getRoomPlugins",1),Jd([E.trace("PluginController.enableForSelf")],vo.prototype,"enablePlugin",1),Jd([E.trace("PluginController.disableForSelf")],vo.prototype,"disablePlugin",1),Jd([E.trace("PluginController.setupEvents")],vo.prototype,"setupEvents",1);class LO{constructor(t){p(this,"mediaJoined");p(this,"socketJoined");p(this,"socketJoinAttempted");p(this,"mediaJoinAttempted");p(this,"socketState");p(this,"mediaState");m(this,qo,void 0);this.mediaJoined=!1,this.socketJoined=!1,this.socketJoinAttempted=!1,this.mediaJoinAttempted=!1,this.socketState={state:void 0,reconnected:!1,reconnectionAttempt:void 0},this.mediaState={recv:void 0,send:void 0},f(this,qo,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&&(a(this,qo).getValue("peerSessionStore").emit(_.SOCKET_STATE_UPDATE,r),this.socketState=r)}}qo=new WeakMap;var xO=Object.defineProperty,UO=Object.getOwnPropertyDescriptor,To=(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};let Ri=(QS=class extends $t{constructor(t,e){const r=t.getValue("logger");super(r);m(this,ua);m(this,da,void 0);m(this,la,void 0);p(this,"recordingPeerIds",[]);p(this,"recordings",[]);f(this,la,t),f(this,da,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,la).getValue("telemetry")}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}async start(t){if(!a(this,da).permissions.canRecord)throw this.logger.error("Recording::start::permission_denied"),new k("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 k(`Cant start recording, recordingState irregular: ${this.recordingState}`,"1005");try{const e=ht(),{recording:r={}}=a(this,la).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::stop::recording_failed_to_start",{error:e}),new k("Error while starting recording","1000",this.logger)}}async stop(t){await x(this,ua,fu).call(this,"stop",["RECORDING","PAUSED"],t)}async pause(t){await x(this,ua,fu).call(this,"pause",["RECORDING"],t)}async resume(t){await x(this,ua,fu).call(this,"resume",["PAUSED"],t)}},da=new WeakMap,la=new WeakMap,ua=new WeakSet,fu=async function(t,e,r){if(!a(this,da).permissions.canRecord)throw this.logger.error("Recording::stop::permission_denied"),new k("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 k("Could not find the specified recording","1004");if(e.includes(n.state)){this.logger.error("Recording::stop::recording_not_in_expected_state",{recording:{state:n.state}});return}i.push(n)}else i=this.recordings.filter(n=>e.includes(n.state));i.forEach(async n=>{const o=n.state;t==="stop"&&(n.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{await ht().updateRecording(n.id,t)}catch(c){throw this.logger.error("Recording::stop::recording_failed_to_stop",{error:c}),n.state!==o&&(n.state=o,this.emit("recordingUpdate",o)),new k("Error while stopping recording","1000",this.logger)}})},QS);To([E.trace("Recording.start")],Ri.prototype,"start",1),To([E.trace("Recording.stop")],Ri.prototype,"stop",1),To([E.trace("Recording.stop")],Ri.prototype,"pause",1),To([E.trace("Recording.stop")],Ri.prototype,"resume",1),Ri=To([lt("1000")],Ri);var FO=Object.defineProperty,$O=Object.getOwnPropertyDescriptor,BO=(s,t,e,r)=>{for(var i=r>1?void 0:r?$O(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 $f{constructor(t,e,r){p(this,"recording");p(this,"room");m(this,qi,void 0);f(this,qi,t),this.recording=new Ri(t,e),this.room=r,this.setupEvents()}get telemetry(){return a(this,qi).getValue("telemetry")}get logger(){return a(this,qi).getValue("logger")}getRecordingTypeFromProtoType(t){let e;switch(t){case Pi.BROWSER:e="BROWSER";break;case Pi.COMPOSITE:e="COMPOSITE";break;case Pi.TRACK:e="TRACK";break;default:e="BROWSER"}return e}setupEvents(){a(this,qi).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(U.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(U.recordingPaused,t=>{const e=[...this.recording.recordings];e.forEach(r=>{r.id===t.recordingId&&(r.state="PAUSED")}),this.recording.updateRecordings(e)}),this.room.on(U.recordingStopped,t=>{const e=[...this.recording.recordings.filter(r=>r.id!==t.recordingId)];this.recording.updateRecordings(e)})}}qi=new WeakMap,BO([E.trace("RecordingController.setupEvents")],$f.prototype,"setupEvents",1);class HO{constructor(t){m(this,ji,void 0);f(this,ji,t)}hasFeature(t){var e;return(e=a(this,ji).getValue("flagsmith").hasFeature(t))!=null?e:!1}getFeatureValue(t){return a(this,ji).getValue("flagsmith").getValue(t)}getAllFeatures(){return a(this,ji).getValue("flagsmith").getAllFlags()}}ji=new WeakMap;class Ch{constructor(t,e,r){p(this,"logger");p(this,"features");p(this,"browserSpecs");p(this,"callStats");this.logger=t,this.features=e,this.browserSpecs=be,this.callStats=r}static init(t){return new Ch(t.getValue("logger"),new HO(t),t.getValue("callstats"))}}class kh{constructor(t){p(this,"internals");this.internals=t}static async init(t){const e=Ch.init(t);return new kh(e)}}var qO=Object.defineProperty,jO=Object.getOwnPropertyDescriptor,qt=(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 Dt extends Dn{constructor(e,r,i=zd,n=!0){const o=e.getValue("logger");super(o);m(this,Ke,void 0);m(this,Ee,void 0);m(this,fe,void 0);m(this,vr,void 0);m(this,us,void 0);m(this,jo,void 0);m(this,Ve,void 0);p(this,"audioUpdateInProgress");p(this,"videoUpdateInProgress");f(this,Ve,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,f(this,Ke,new Kf(e,r)),f(this,Ee,new TD(e,a(this,Ke),void 0,i)),f(this,fe,new RD(e,a(this,Ke),void 0,i)),f(this,us,new bD(a(this,Ve),a(this,Ke))),f(this,vr,new ED(e,a(this,Ke))),f(this,jo,n),a(this,Ee).on("trackMuted",this.onAudioTrackMuted.bind(this)),a(this,Ee).on("trackChanged",this.onAudioTrackChanged.bind(this)),a(this,fe).on("trackChanged",this.onVideoTrackChanged.bind(this)),a(this,fe).on("trackEnded",this.onVideoTrackEnded.bind(this)),a(this,us).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}get telemetry(){return a(this,Ve).getValue("telemetry")}set context(e){f(this,Ve,e)}async onVisibilityChange(){a(this,Ve).getValue("callstats").tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?a(this,Ve).getValue("callstats").browserBackgrounded():(a(this,Ve).getValue("callstats").browserForegrounded(),await this.setupSpeaker())}async repopulateAvailableDevices(){return!0}async setupStreams({audio:e,video:r}){var o;e?a(this,Ve).getValue("callstats").audioOn():a(this,Ve).getValue("callstats").audioOff(),r?a(this,Ve).getValue("callstats").videoOn():a(this,Ve).getValue("callstats").videoOff();let i,n;if(e&&r)try{const c=await a(this,Ke).getAudioAndVideoTrack(a(this,Ee).userSelectedDevice,a(this,fe).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,Ke).getAudioTrack(!1,a(this,Ee).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!n&&r)try{n=await a(this,Ke).getVideoTrack(a(this,fe).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get video track",{error:c})}e&&!i&&a(this,Ve).getValue("callstats").audioOff(),r&&!n&&a(this,Ve).getValue("callstats").videoOff(),await a(this,Ee).setMediaTrack(i),await a(this,fe).setMediaTrack(n);try{await this.setupSpeaker()}catch(c){}if(n){const c=await this.getDeviceById(n.getSettings().deviceId);a(this,Ve).getValue("callstats").selectedDevice("VIDEO",c)}if(i){const c=await this.getDeviceById(i.getSettings().deviceId);a(this,Ve).getValue("callstats").selectedDevice("AUDIO",c)}(o=a(this,vr).currentDevice)!=null&&o.deviceId&&a(this,Ve).getValue("callstats").selectedDevice("SPEAKER",a(this,vr).currentDevice),a(this,Ke).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})}getCurrentDevices(){return{audio:a(this,Ee).currentDevice,video:a(this,fe).currentDevice,speaker:a(this,vr).currentDevice}}get permissions(){return a(this,Ke).permissions}getAllDevices(){return a(this,Ke).getAvailableDevices()}getDeviceById(e,r){return a(this,Ke).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return a(this,Ee).mediaTrack}get audioTrack(){return a(this,Ee).transformedMediaTrack}get audioEnabled(){return a(this,Ee).trackEnabled}async enableAudio(e){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{e?await a(this,Ee).enableTrack(!1,e):await a(this,Ee).unmuteTrack()}catch(r){}finally{this.audioUpdateInProgress=!1}}}disableAudio(){a(this,Ee).mediaTrack&&!a(this,Ee).isCustomTrack?a(this,Ee).muteTrack():a(this,Ee).disableTrack()}getAudioDevices(e){return a(this,Ke).getAudioInputDevices(e)}async setAudioDevice(e,{saveDevicePreference:r}){await a(this,Ee).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Ve).getValue("callstats").selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async setupSpeaker(){const{speaker:e}=this.getCurrentDevices();await a(this,vr).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,vr).setupSpeaker(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Ve).getValue("callstats").selectedDevice("SPEAKER",e),this.emit("DEVICE_CHANGE",{device:e})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return a(this,fe).mediaTrack}get videoTrack(){return a(this,fe).transformedMediaTrack}get videoEnabled(){return a(this,fe).trackEnabled}async enableVideo(e){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{e?await a(this,fe).enableTrack(!1,e):await a(this,fe).unmuteTrack()}catch(r){}finally{this.videoUpdateInProgress=!1}}}disableVideo(){a(this,fe).disableTrack()}getVideoDevices(e){return a(this,Ke).getVideoInputDevices(e)}async setVideoDevice(e,{saveDevicePreference:r}){await a(this,fe).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Ve).getValue("callstats").selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async updateVideoConstraints(e){await a(this,fe).updateConstraints(e)}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:a(this,us).audioMediaTrack,video:a(this,us).videoMediaTrack}}get screenShareEnabled(){return a(this,us).trackEnabled}async enableScreenShare(){await a(this,us).enableScreenShare()}async disableScreenShare(){a(this,us).disableScreenShare()}async updateScreenshareConstraints(e){await a(this,us).updateConstraints(e)}getSpeakerDevices(e){return a(this,Ke).getAudioOutputDevices(e)}addAudioMiddleware(e){return a(this,Ee).addMiddleware(e)}removeAudioMiddleware(e){return a(this,Ee).removeMiddleware(e)}removeAllAudioMiddlewares(){return a(this,Ee).removeAllMiddlewares()}addVideoMiddleware(e){return a(this,fe).addMiddleware(e)}removeVideoMiddleware(e){return a(this,fe).removeMiddleware(e)}removeAllVideoMiddlewares(){return a(this,fe).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return a(this,fe).setVideoMiddlewareGlobalConfig(e)}destruct(){a(this,Ee).disableTrack(),a(this,fe).disableTrack(),a(this,fe).terminateMiddlewareWebWorker(),a(this,us).disableScreenShare(),a(this,Ke).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&&!zd(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,Ee).disableTrack()}removeVideoTrack(){a(this,fe).disableTrack(),a(this,fe).terminateMiddlewareWebWorker()}async removeDocumentEventListeners(){document.removeEventListener("visibilitychange",this.onVisibilityChange)}}Ke=new WeakMap,Ee=new WeakMap,fe=new WeakMap,vr=new WeakMap,us=new WeakMap,jo=new WeakMap,Ve=new WeakMap,qt([E.trace("MediaHandler.setupStreams")],Dt.prototype,"setupStreams",1),qt([E.trace("MediaHandler.enableAudio")],Dt.prototype,"enableAudio",1),qt([E.trace("MediaHandler.disableAudio")],Dt.prototype,"disableAudio",1),qt([E.trace("MediaHandler.setAudioDevice")],Dt.prototype,"setAudioDevice",1),qt([E.trace("MediaHandler.enableVideo")],Dt.prototype,"enableVideo",1),qt([E.trace("MediaHandler.disableVideo")],Dt.prototype,"disableVideo",1),qt([E.trace("MediaHandler.setVideoDevice")],Dt.prototype,"setVideoDevice",1),qt([E.trace("MediaHandler.updateVideoConstraints")],Dt.prototype,"updateVideoConstraints",1),qt([E.trace("MediaHandler.enableScreenShare")],Dt.prototype,"enableScreenShare",1),qt([E.trace("MediaHandler.disableScreenShare")],Dt.prototype,"disableScreenShare",1),qt([E.trace("MediaHandler.updateScreenshareConstraints")],Dt.prototype,"updateScreenshareConstraints",1),qt([E.trace("MediaHandler.destruct")],Dt.prototype,"destruct",1),qt([E.trace("MediaHandler.onDeviceChange")],Dt.prototype,"onDeviceChange",1);function Kd(s,t,e){switch(!0){case be.isChromiumBased():switch(t){case"NotAllowedError":return e.includes("by system")?"SYSTEM_DENIED":s==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case be.isSafari():switch(t){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case be.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 GO=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function zd(s){var e,r;const t=(e=s.label)==null?void 0:e.toLowerCase();return((r=be._bowser)==null?void 0:r.getOSName())==="macOS"&&t.includes("iphone")?!0:GO.some(i=>t==null?void 0:t.includes(i))}async function WO(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 JO=s=>(t,e)=>(s.set(t,e),e),Bf=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,Hf=536870912,qf=Hf*2,KO=(s,t)=>e=>{const r=t.get(e);let i=r===void 0?e.size:r<qf?r+1:0;if(!e.has(i))return s(e,i);if(e.size<Hf){for(;e.has(i);)i=Math.floor(Math.random()*qf);return s(e,i)}if(e.size>Bf)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()*Bf);return s(e,i)},jf=new WeakMap,zO=JO(jf),Yd=KO(zO,jf),YO=s=>s.method!==void 0&&s.method==="call",QO=s=>s.error===null&&typeof s.id=="number",Qd=((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(YO(l)){const{params:{timerId:u,timerType:h}}=l;if(h==="interval"){const g=t.get(u);if(typeof g=="number"){const S=r.get(g);if(S===void 0||S.timerId!==u||S.timerType!==h)throw new Error("The timer is in an undefined state.")}else if(typeof g!="undefined")g();else throw new Error("The timer is in an undefined state.")}else if(h==="timeout"){const g=e.get(u);if(typeof g=="number"){const S=r.get(g);if(S===void 0||S.timerId!==u||S.timerType!==h)throw new Error("The timer is in an undefined state.")}else if(typeof g!="undefined")g(),e.delete(u);else throw new Error("The timer is in an undefined state.")}}else if(QO(l)){const{id:u}=l,h=r.get(u);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:g,timerType:S}=h;r.delete(u),S==="interval"?t.delete(g):e.delete(g)}else{const{error:{message:u}}=l;throw new Error(u)}}),{clearInterval:l=>{const u=Yd(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=Yd(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=Yd(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=Yd(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})}}))})();`),Gf=s=>Qd().clearInterval(s),XO=s=>Qd().clearTimeout(s),Wf=(s,t)=>Qd().setInterval(s,t),Jf=Object.freeze(Object.defineProperty({__proto__:null,clearInterval:Gf,clearTimeout:XO,setInterval:Wf,setTimeout:(s,t)=>Qd().setTimeout(s,t)},Symbol.toStringTag,{value:"Module"}));class ZO{constructor(t){m(this,Gi,void 0);m(this,Go,void 0);f(this,Go,t)}get logger(){return a(this,Go).getValue("logger")}terminateMiddlewareWebWorker(){if(a(this,Gi))try{Gf(a(this,Gi)),f(this,Gi,void 0)}catch(t){this.logger.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}async getTransformedVideoTrack(t,e,r){if(!(t!=null&&t.length))return e;const i=document.createElement("canvas"),n=await Promise.all(t==null?void 0:t.map(g=>g({canvas:i,WorkerTimers:Jf})));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 g=0;g<n.length;g+=1)typeof n[g]=="function"&&await n[g](i,d)}catch(g){this.logger.error("getTransformedVideoTrack::middleware_execution_failed",{error:g})}};try{o.play()}catch(g){}o.addEventListener("play",()=>{i.width=o.width||e.getSettings().width,i.height=o.width||e.getSettings().height,f(this,Gi,Wf(l,50))},!1);const h=i.captureStream().getVideoTracks()[0];return Object.defineProperty(h,"originalSettings",{value:e.getSettings()}),h}}Gi=new WeakMap,Go=new WeakMap;const eD={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}]]],sD=(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,g)=>h-g);let o=Number.MAX_VALUE,c=0;return n.forEach((h,g)=>{Math.abs(h-r)<o&&(o=Math.abs(h-r),c=g)}),i[c][1]};var me=(s=>(s.WEBCAM="webcam",s.WEBCAM_BACKUP="webcam_backup",s.MIC="mic",s.SCREENSHARE_VIDEO="screenshare_video",s.SCREENSHARE_AUDIO="screenshare_audio",s))(me||{});const rD=Xb(),Un=bs(rD.config.media);function iD(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 nD{constructor(t,e){m(this,Wi,void 0);m(this,ti,void 0);p(this,"getScreenShareConstraints",()=>{var l,u,h,g,S,y,w,b,C,D,F;const t=(l=a(this,Wi))==null?void 0:l.screenshare,e=(h=(u=t==null?void 0:t.width)==null?void 0:u.max)!=null?h:1920,r=(S=(g=t==null?void 0:t.height)==null?void 0:g.max)!=null?S:1080,i=(w=(y=t==null?void 0:t.frameRate)==null?void 0:y.max)!=null?w:5;let n=(C=(b=t==null?void 0:t.frameRate)==null?void 0:b.ideal)!=null?C:5;const o=t==null?void 0:t.displaySurface,c=t==null?void 0:t.selfBrowserSurface;a(this,ti).getValue("flagsmith").getValue(Z.VAL_MIN_FRAMERATE)&&(n=parseInt((D=a(this,ti).getValue("flagsmith").getValue(Z.VAL_MIN_FRAMERATE))==null?void 0:D.toString(),10));let d={width:{max:e},height:{max:r},frameRate:{ideal:n,max:i}};if(a(this,ti).getValue("flagsmith").hasFeature(Z.SCREENSHARE_CONSTRAINTS)){const L=(F=a(this,ti).getValue("flagsmith").getValue(Z.SCREENSHARE_CONSTRAINTS))==null?void 0:F.toString();d=JSON.parse(L)}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,Wi))==null?void 0:n.audio,i=r!=null&&r.enableStereo?2:1;return be.isFirefox()||be.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,Wi))==null?void 0:o.video,i=VP(eD);let n=i.vga;if(typeof r=="string"){const l=i[r];l&&(n=l)}else r!==void 0&&(n.height.ideal=r.height.ideal,n.width.ideal=r.width.ideal,n.frameRate.ideal=(d=(c=r.frameRate)==null?void 0:c.ideal)!=null?d:30);return e.video=n,typeof e.video=="boolean"||(t?e.video.deviceId={exact:t}:e.video.facingMode="user"),e});f(this,ti,t),f(this,Wi,e)}getUpdatedVideoConstraints(t){return t}}Wi=new WeakMap,ti=new WeakMap;class Ih extends Error{constructor(e,r,i){super(r);p(this,"constraints");p(this,"name");this.name=e,this.constraints=i}}class aD{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 oD=Object.defineProperty,cD=Object.getOwnPropertyDescriptor,_s=(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};let jt=(XS=class extends aD{constructor(t,e){super();m(this,ha,void 0);m(this,hs,void 0);m(this,Be,void 0);f(this,Be,t),f(this,hs,new nD(t,e)),f(this,ha,new AbortController)}get telemetry(){return a(this,Be).getValue("telemetry")}get logger(){return a(this,Be).getValue("logger")}get constraintsBuilder(){return a(this,hs)}async destruct(){var t;(t=a(this,ha))==null||t.abort()}handlePermissionErrors(t,e){const r=Kd(t,e.name,e.message);return this.permissions[t]=r,a(this,Be).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(D=>D.deviceId===t));let u;t&&l?u=t:c&&((r=c[0])!=null&&r.deviceId)&&(u=(i=c[0])==null?void 0:i.deviceId);const h=!!(d!=null&&d.find(D=>D.deviceId===e));let g;e&&h?g=e:d&&((n=d[0])!=null&&n.deviceId)&&(g=(o=d[0])==null?void 0:o.deviceId);const S={audio:a(this,hs).getAudioConstraints(u).audio,video:a(this,hs).getVideoConstraints(g).video};this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(S)});const y=await navigator.mediaDevices.getUserMedia(S);this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(S)});const w=y.getAudioTracks()[0];let b=y.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",a(this,Be).getValue("flagsmith").hasFeature(Z.OBS_QUALITY)&&b.label.includes("OBS Virtual")){const F=(await this.getVideoInputDevices()).find(L=>L.label.includes("OBS Virtual"));b=await this.getVideoTrack(F.deviceId)}return a(this,Be).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),a(this,Be).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:w,videoTrack:b}}catch(c){throw this.logger.error("WebMediaInterface.getAudioAndVideoTrack",{error:c}),new k("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,Be).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new k("No audio devices available","1606");const i=!!(r!=null&&r.find(l=>l.deviceId===e));let n;e&&i?n=e:(c=r[0])!=null&&c.deviceId&&(n=(d=r[0])==null?void 0:d.deviceId);const o=async l=>{let u;try{r=r.filter(g=>g.deviceId!==l),u=a(this,hs).getAudioConstraints(l),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(u)});const[h]=(await navigator.mediaDevices.getUserMedia(u)).getAudioTracks();return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(u)}),h}catch(h){const g=Kd("audio",h.name,h.message),S=new Ih(h.name,h.message,u);if(g==="COULD_NOT_START"){const y=r.shift();if(!y)throw S;this.logger.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(u),error:h});const w=a(this,hs).getAudioConstraints(y.deviceId);return this.logger.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(w)}),o(y.deviceId)}throw S}};try{const l=await o(n);return l.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",a(this,Be).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),l}catch(l){throw l.constraints&&this.handlePermissionErrors("audio",l),new k(l.message,"1601")}}async getVideoTrack(t){var l,u,h;const e=a(this,Be).getValue("flagsmith").hasFeature(Z.OBS_QUALITY),r=(l=await this.getCurrentDeviceLabel(t))==null?void 0:l.includes("OBS Virtual"),i=e&&r,n=await this.getVideoInputDevices();if(!(n!=null&&n.length))throw this.permissions.video="NO_DEVICES_AVAILABLE",a(this,Be).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new k("No video devices available","1607");const o=!!(n!=null&&n.find(g=>g.deviceId===t));let c;t&&o?c=t:(u=n[0])!=null&&u.deviceId&&(c=(h=n[0])==null?void 0:h.deviceId);const d=async g=>{try{let S=g;const{video:y}=S;i&&typeof y!="boolean"&&(S={video:{deviceId:y.deviceId}}),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(S)});const[w]=(await navigator.mediaDevices.getUserMedia(S)).getVideoTracks();if(i&&typeof y!="boolean"&&typeof y.width=="object"){const{width:b,height:C}=w.getSettings(),{ideal:D}=y.width;w.applyConstraints({width:{ideal:D},height:{ideal:Math.floor(C*D/b)},frameRate:y.frameRate})}return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(S)}),w}catch(S){const y=Kd("video",S.name,S.message),w=new Ih(S.name,S.message,g);if(y==="COULD_NOT_START"){const b=n.shift();if(!b)throw w;this.logger.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(g),error:S});const C=a(this,hs).getVideoConstraints(b.deviceId);return this.logger.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(C)}),d({video:C.video})}throw w}};try{const g=a(this,hs).getVideoConstraints(c),S=await d(g);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",a(this,Be).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),S}catch(g){throw g.constraints&&this.handlePermissionErrors("video",g),new k(g.message,"1602")}}async getScreenShareTracks(){const t=async e=>{try{this.logger.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),a(this,Be).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=Kd("video",r.name,r.message),n=new Ih(r.name,r.message,e),o={video:!0};if($_(e,o)||!a(this,Be).getValue("flagsmith").hasFeature(Z.SCREEENSHARE_CONSTRAINTS_RETRY))throw n;if(i==="COULD_NOT_START")return t(o);throw n}};try{const e=a(this,hs).getScreenShareConstraints(),r=await t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",a(this,Be).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 k(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 zd(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 g=r(i),S=r(n);if(g&&!S)return-1;if(!g&&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 k("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 k("Failed to get device","1609")}}async onDeviceChange(t){if(be.supportsDeviceChangeEvent()){let e=await this.getAvailableDevices();navigator.mediaDevices.addEventListener("devicechange",async r=>{var l,u;const i=h=>`${h.kind}-${h.label}-${h.deviceId}-${h.groupId}`,n=new Set(e.map(h=>i(h))),o=await this.getAvailableDevices(),c=new Set(o.map(h=>i(h))),d={added:o.filter(h=>!n.has(i(h))),removed:e.filter(h=>!c.has(i(h))),devices:o};if(e=o,(l=d.added)!=null&&l.length||(u=d.removed)!=null&&u.length){this.logger.info("repopulated_full_device_list",{devices:JSON.stringify(o)});const h=[...d.added,...d.removed];h.some(g=>g.kind==="audioinput")&&a(this,Be).getValue("callstats").devices("AUDIO",o==null?void 0:o.filter(g=>g.kind==="audioinput")),h.some(g=>g.kind==="videoinput")&&a(this,Be).getValue("callstats").devices("VIDEO",o==null?void 0:o.filter(g=>g.kind==="videoinput")),h.some(g=>g.kind==="audiooutput")&&a(this,Be).getValue("callstats").devices("SPEAKER",o==null?void 0:o.filter(g=>g.kind==="audiooutput")),t(r,d,!1)}},{signal:a(this,ha).signal})}}},ha=new WeakMap,hs=new WeakMap,Be=new WeakMap,XS);_s([E.trace("WebMediaInterface.destruct")],jt.prototype,"destruct",1),_s([E.trace("WebMediaInterface.handlePermissionErrors")],jt.prototype,"handlePermissionErrors",1),_s([E.trace("WebMediaInterface.getAudioAndVideoTrack")],jt.prototype,"getAudioAndVideoTrack",1),_s([E.trace("WebMediaInterface.getAudioTrack")],jt.prototype,"getAudioTrack",1),_s([E.trace("WebMediaInterface.getVideoTrack")],jt.prototype,"getVideoTrack",1),_s([E.trace("WebMediaInterface.getScreenShareTracks")],jt.prototype,"getScreenShareTracks",1),_s([E.trace("WebMediaInterface.getAvailableDevices")],jt.prototype,"getAvailableDevices",1),_s([E.trace("WebMediaInterface.getAvailableDevicesByKind")],jt.prototype,"getAvailableDevicesByKind",1),_s([E.trace("WebMediaInterface.getDevice")],jt.prototype,"getDevice",1),_s([E.trace("WebMediaInterface.onDeviceChange")],jt.prototype,"onDeviceChange",1),jt=_s([lt("1600")],jt);const Kf=jt,Ci={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}},dD=(s=0)=>new Promise(t=>setTimeout(t,s)),lD=(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):dD().then(d))}return d().then(l=>(i.disconnect(),l),l=>{throw i.disconnect(),l})},uD=typeof AudioContext!="undefined"?AudioContext:null;class Ah{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:Ah}})}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 zf=new Ah,hD=3,pD=250;function gD(s){const t={},e=zf.getOrCreate(t);let r=hD;function i(){return r-=1,lD(e,s.srcObject,pD).then(n=>n?r>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{zf.release(t)})}async function Yf(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 gD(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 mD=Object.defineProperty,fD=Object.getOwnPropertyDescriptor,Qf=(s,t,e,r)=>{for(var i=r>1?void 0:r?fD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&mD(t,e,i),i};let Xd=class extends Dn{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=>Ci.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>Ci.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 k("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 k("No device received!","1603");this.userSelectedDevice=t.deviceId,e&&this.setUserPreferredDevice(t.deviceId),await this.onSetDevice(t)}async addMiddleware(t){if(be.isWebKitBased()&&!Bb.hasFeature(Z.ALLOW_SAFARI_MEDIA_MIDDLEWARES))return{success:!1,message:"Middlewares are not supported in this WebKit engine based browser."};if(this.middlewares.includes(t))return{success:!1,message:"This middleware has been applied, already. Skipping."};try{return this.middlewares.push(t),this.trackEnabled&&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))}};Qf([E.trace("BaseMediaHandler.unmuteTrack")],Xd.prototype,"unmuteTrack",1),Xd=Qf([lt("1600")],Xd);const Xf=Xd;var SD=Object.defineProperty,vD=Object.getOwnPropertyDescriptor,Mh=(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&&SD(t,e,i),i};const Oh="[Realtimekit]nonSilentDeviceLabels";class Zd extends Xf{async onSetDevice(t){if(!t)throw this.logger.warn("AudioMediaHandler.setDevice No device received"),new k("No device received!","1603");if(t.kind!=="audioinput")throw this.logger.warn("AudioMediaHandler.setDevice Received non audio device"),new k("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 k(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 WO(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(Ci.getItem(Oh,this.logger));if(o!=null&&o.devices.some(l=>l.label===r.label))return r;if(!await Yf(this.logger,r)){const l=(d=o==null?void 0:o.devices.concat({label:r.label}))!=null?d:[{label:r.label}];return Ci.setItem(Oh,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 Yf(this.logger,r)){const h=(u=o==null?void 0:o.devices.concat({label:r.label}))!=null?u:[{label:r.label}];return Ci.setItem(Oh,JSON.stringify({devices:h}),this.logger),this.logger.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return this.logger.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1}),r}}Mh([E.trace("AudioMediaHandler.setTransformedTrack")],Zd.prototype,"setTransformedTrack",1),Mh([E.trace("AudioMediaHandler.onTrackEnded")],Zd.prototype,"onTrackEnded",1),Mh([E.trace("AudioMediaHandler.conditionallyChangeTrack")],Zd.prototype,"conditionallyChangeTrack",1);const TD=Zd;class yD{constructor(t,e){m(this,Ji,void 0);p(this,"currentDevice");p(this,"userPreferredDeviceKey","Realtimekit::speaker::UserDeviceID");p(this,"logger");p(this,"setUserPreferredDevice",t=>Ci.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>Ci.getItem(this.userPreferredDeviceKey,this.logger));f(this,Ji,e),this.logger=t.getValue("logger")}async setPreferredSpeaker(){const t=this.getUserPreferredDevice(),e=await a(this,Ji).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,Ji)instanceof Kf))return;let r=t;if(t||([r]=(await a(this,Ji).getAvailableDevicesByKind("audiooutput")).filter(d=>!zd(d))),!r)throw new k("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){}})}}Ji=new WeakMap;const ED=yD;class wD extends Dn{constructor(e,r){const i=e.getValue("logger");super(i);p(this,"mediaInterface");p(this,"audioMediaTrack");p(this,"videoMediaTrack");m(this,Wo,void 0);f(this,Wo,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,Wo).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 k("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new k("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)),be.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")}}Wo=new WeakMap;const bD=wD;var PD=Object.defineProperty,_D=Object.getOwnPropertyDescriptor,el=(s,t,e,r)=>{for(var i=r>1?void 0:r?_D(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&PD(t,e,i),i};class yo extends Xf{constructor(e,r,i,n){super(e,r,i,n);m(this,pa,void 0);m(this,Jo,{disablePerFrameCanvasRendering:!1});f(this,pa,new ZO(e))}async onSetDevice(e){if(!e)throw this.logger.warn("VideoMediaHandler.setDevice No device received"),new k("No device received!","1603");if(e.kind!=="videoinput")throw this.logger.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new k("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 k("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,pa).getTransformedVideoTrack(this.middlewares,this.mediaTrack,a(this,Jo)),this.emit("trackChanged")}catch(i){this.logger.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}}async setVideoMiddlewareGlobalConfig(e){f(this,Jo,e)}async updateConstraints(e){if(!this._mediaTrack)throw new k("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new k("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,pa).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}}pa=new WeakMap,Jo=new WeakMap,el([E.trace("VideoMediaHandler.setTransformedTrack")],yo.prototype,"setTransformedTrack",1),el([E.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],yo.prototype,"setVideoMiddlewareGlobalConfig",1),el([E.trace("VideoMediaHandler.onTrackEnded")],yo.prototype,"onTrackEnded",1),el([E.trace("VideoMediaHandler.conditionallyChangeTrack")],yo.prototype,"conditionallyChangeTrack",1);const RD=yo,Zf=bs(Hu()),ma=class{constructor(t){m(this,_t,void 0);m(this,Ki,void 0);m(this,Ko,void 0);m(this,ga,void 0);if(!t)throw new k("Could not load preset.","0904");f(this,_t,t.config),f(this,Ko,t.name),f(this,Ki,t.ui||bs(Hu().ui)),f(this,ga,t.permissions.plugins.config)}static fromResponse(t){return new ma(t)}static default(){return new ma(Zf)}static init(t,e=!0){return!t||e?new ma(Zf):new ma(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,Ki).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return a(this,_t).viewType}get livestreamViewerQualities(){return a(this,_t).livestreamViewerQualities||[]}get maxVideoStreams(){return a(this,_t).maxVideoStreams}get maxScreenShareCount(){return a(this,_t).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(a(this,ga)).filter(t=>a(this,ga)[t].disabled)}get designTokens(){return a(this,Ki).designTokens}get configDiff(){return a(this,Ki).configDiff}get isSimulcastEnabled(){var t,e,r,i;return(i=(r=(e=(t=a(this,_t))==null?void 0:t.media)==null?void 0:e.video)==null?void 0:r.simulcast)!=null?i:!1}get mediaConstraints(){var t,e,r,i,n,o,c,d,l,u,h,g,S,y,w,b,C,D,F,L,B,W,ae,Tt;return{audio:{enableStereo:(i=(r=(e=(t=a(this,_t))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?i:Un.audio.enableStereo,enableHighBitrate:(d=(c=(o=(n=a(this,_t))==null?void 0:n.media)==null?void 0:o.audio)==null?void 0:c.enableHighBitrate)!=null?d:Un.audio.enableHighBitrate},video:{quality:(g=(h=(u=(l=a(this,_t))==null?void 0:l.media)==null?void 0:u.video)==null?void 0:h.quality)!=null?g:Un.video.quality,frameRate:(b=(w=(y=(S=a(this,_t))==null?void 0:S.media)==null?void 0:y.video)==null?void 0:w.frameRate)!=null?b:Un.video.frameRate},screenshare:{quality:(L=(F=(D=(C=a(this,_t))==null?void 0:C.media)==null?void 0:D.screenshare)==null?void 0:F.quality)!=null?L:Un.screenshare.quality,frameRate:(Tt=(ae=(W=(B=a(this,_t))==null?void 0:B.media)==null?void 0:W.screenshare)==null?void 0:ae.frameRate)!=null?Tt:Un.screenshare.frameRate}}}get name(){return a(this,Ko)}};let Dh=ma;_t=new WeakMap,Ki=new WeakMap,Ko=new WeakMap,ga=new WeakMap;var CD=Object.defineProperty,kD=Object.getOwnPropertyDescriptor,eS=(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&&CD(t,e,i),i};class Nh extends $t{constructor(e,r){const i=e.getValue("logger");super(i);m(this,fa,void 0);p(this,"state","IDLE");p(this,"playbackUrl");p(this,"ingestionCredentials");p(this,"viewerCount");m(this,zo,void 0);f(this,fa,r),f(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,fa).permissions.canLivestream)throw this.logger.error("Livestream::start::permission_denied"),new k("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const r=ht(),{playbackUrl:i,ingestionCredentials:n}=await r.startLivestreaming(e);this.playbackUrl=i,this.ingestionCredentials=n,e!=null&&e.manualIngestion&&this.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}catch(r){throw this.logger.error("Recording::stop::livestream_failed_to_start",{error:r}),this.setLivestreamState("IDLE"),new k("Error while starting livestream","1900",this.logger)}}async stop(){if(!a(this,fa).permissions.canLivestream)throw this.logger.error("Livestream::stop::permission_denied"),new k("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 k("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),await ht().stopLivestreaming()}catch(e){throw this.logger.error("Livestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new k("Error while stopping livestream","1900",this.logger)}}}fa=new WeakMap,zo=new WeakMap,eS([E.trace("livestream.start")],Nh.prototype,"start",1),eS([E.trace("livestream.stop")],Nh.prototype,"stop",1);var ID=Object.defineProperty,AD=Object.getOwnPropertyDescriptor,MD=(s,t,e,r)=>{for(var i=r>1?void 0:r?AD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ID(t,e,i),i};class tS{constructor(t,e,r){p(this,"livestream");m(this,Sa,void 0);m(this,va,void 0);m(this,Tr,void 0);m(this,Gs,void 0);f(this,Gs,t),f(this,va,e),this.livestream=new Nh(t,e),f(this,Tr,r),this.setupEvents()}get logger(){return a(this,Gs).getValue("logger")}get telemetry(){return a(this,Gs).getValue("telemetry")}async fetchInitialLivestreamingState(){const t=ht(),{status:e,playbackUrl:r,manualIngest:i,ingestionCredentials:n}=await t.getActiveLivestream();this.livestream.playbackUrl=r,this.livestream.ingestionCredentials=n,e==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),e==="INVOKED"&&i&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}setupEvents(){a(this,Tr).on(U.startedLivestream,async t=>{this.livestream.playbackUrl=t.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{a(this,va).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}}),a(this,Tr).on(U.livestreamingInvoked,async t=>{if(t.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{a(this,va).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}}),a(this,Tr).on(U.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),a(this,Tr).on(U.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),a(this,Tr).on(U.roomPeerCount,t=>{this.livestream.viewerCount=t.count,this.livestream.emit("viewerCountUpdate",t.count)}),a(this,Gs).getValue("peerSessionStore").on(_.PEER_JOINED_INTERNAL,async t=>{var e;((e=t.flags)==null?void 0:e.hiddenParticipant)===!0&&t.recorderType==="LIVESTREAMER"&&(f(this,Sa,t.id),this.livestream.setLivestreamState("LIVESTREAMING"))}),a(this,Gs).getValue("peerSessionStore").on(_.PEER_CLOSED,t=>{t.id===a(this,Sa)&&(f(this,Sa,void 0),this.livestream.setLivestreamState("IDLE"))}),a(this,Gs).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,Gs).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,async()=>{try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Error: LivestreamController.fetchLivestream")}})}}Sa=new WeakMap,va=new WeakMap,Tr=new WeakMap,Gs=new WeakMap,MD([E.trace("LivestreamController.setupEvents")],tS.prototype,"setupEvents",1);var OD=Object.defineProperty,DD=Object.getOwnPropertyDescriptor,Eo=(s,t,e,r)=>{for(var i=r>1?void 0:r?DD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&OD(t,e,i),i};class Fn{constructor({name:t,socketHandler:e,meetingId:r}){m(this,Rl);p(this,"name","");m(this,mt,{});m(this,si,"");m(this,ri,void 0);p(this,"rateLimitConfig",{maxInvocations:5,period:1});p(this,"bulkRateLimitConfig",{maxInvocations:5,period:1});p(this,"listeners",{});this.name=t,f(this,ri,e),f(this,si,r)}async set(t,e,r=!0,i=!1){a(this,mt)[t]=e,r&&this.remoteSet(t,e),i&&(this.listeners[t]&&this.listeners[t].forEach(n=>n({[t]:a(this,mt)[t]})),this.listeners["*"]&&this.listeners["*"].forEach(n=>n({[t]:a(this,mt)[t]})))}remoteSet(t,e){a(this,ri).storeInsertKeys(a(this,si),this.name,[{key:t,payload:e}])}async bulkSet(t){t.forEach(({key:e,payload:r})=>{a(this,mt)[e]=r}),a(this,ri).storeInsertKeys(a(this,si),this.name,t)}async update(t,e,r=!0){x(this,Rl,lv).call(this,t,e,r)}async delete(t,e=!0,r=!1){if(a(this,mt)[t]&&delete a(this,mt)[t],e)return a(this,ri).storeDeleteKeys(a(this,si),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,mt)[e]&&delete a(this,mt)[e]}),a(this,ri).storeDeleteKeys(a(this,si),this.name,t)}get(t){if(a(this,mt)[t])return a(this,mt)[t]}getAll(){return a(this,mt)}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get bulkRateLimits(){return this.bulkRateLimitConfig}updateBulkRateLimits(t,e){this.bulkRateLimitConfig.maxInvocations=t,this.bulkRateLimitConfig.period=e}subscribe(t,e){if(this.listeners[t]){this.listeners[t].push(e);return}this.listeners[t]=[e]}unsubscribe(t,e){var r;if(e){this.listeners[t]=((r=this.listeners[t])==null?void 0:r.filter(i=>i!==e))||[];return}this.listeners[t]&&delete this.listeners[t]}populate(t){f(this,mt,t)}}mt=new WeakMap,si=new WeakMap,ri=new WeakMap,Rl=new WeakSet,lv=function(t,e,r=!0){let i;const n=a(this,mt)[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)},Eo([Ot(Vn,"rateLimitConfig")],Fn.prototype,"remoteSet",1),Eo([Ot(Vn,"bulkRateLimitConfig")],Fn.prototype,"bulkSet",1),Eo([Ot(Vn,"rateLimitConfig")],Fn.prototype,"update",1),Eo([Ot(Vn,"rateLimitConfig")],Fn.prototype,"delete",1),Eo([Ot(Vn,"bulkRateLimitConfig")],Fn.prototype,"bulkDelete",1);class ND{constructor(t,e){m(this,Yo);m(this,Cl);p(this,"stores",new Map);m(this,zi,void 0);m(this,Yi,"");m(this,Qo,void 0);m(this,ii,new Map);f(this,zi,e),f(this,Yi,t.getValue("meetingId")),f(this,Qo,t),x(this,Cl,uv).call(this)}create(t){const e=new Fn({name:t,socketHandler:a(this,zi),meetingId:a(this,Yi)});return a(this,zi).storeGetKeys(a(this,Yi),t,[]),new Promise((i,n)=>{const o=setTimeout(()=>n(Error("Failed")),3e3);a(this,ii).set(t,{rejectTimeout:o,resolve:i,store:e})})}}zi=new WeakMap,Yi=new WeakMap,Yo=new WeakSet,dp=function(){return a(this,Qo).getValue("peerId")},Qo=new WeakMap,ii=new WeakMap,Cl=new WeakSet,uv=function(){[G.storeInsertKeys,G.storeGetKeys,G.storeDeleteKeys].forEach(t=>{a(this,zi).on(t,async e=>{var n,o;if(e.pluginId!==a(this,Yi))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===G.storeGetKeys){const c=a(this,ii).get(e.storeName),d=this.stores.get(e.storeName)||(c==null?void 0:c.store);a(this,ii).get(e.storeName)&&(this.stores.set(e.storeName,c.store),c.resolve(d),clearTimeout(c.rejectTimeout),a(this,ii).delete(e.storeName)),r.forEach(l=>{d.set(l.key,l.payload,!1,!1)});return}const i=this.stores.get(e.storeName)||((o=a(this,ii).get(e.storeName))==null?void 0:o.store);i!==void 0&&(t===G.storeInsertKeys&&r.forEach(({key:c,peerId:d,payload:l})=>{d!==a(this,Yo,dp)&&i.set(c,l,!1,!0)}),t===G.storeDeleteKeys&&r.forEach(({key:c,peerId:d})=>{d!==a(this,Yo,dp)&&i.delete(c,!1,!0)}))})})};function ki(s){var t,e,r,i,n,o,c,d,l,u,h,g,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=(g=s.screenShareTracks)==null?void 0:g.video)==null?void 0:S.id}}}}:{}}var VD=Object.defineProperty,LD=Object.getOwnPropertyDescriptor,$n=(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&&VD(t,e,i),i};const xD=.8,UD=1.2;let dr=(ZS=class extends $t{constructor(t,e,r,i){const n=t.getValue("logger");super(n);m(this,Qi);m(this,ni);m(this,Xi);m(this,kl);m(this,Zi);m(this,Zo);m(this,Al);m(this,Ml);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,Ta,void 0);p(this,"supportsRemoteControl",!1);m(this,ya,void 0);p(this,"presetName");m(this,Yt,void 0);m(this,yr,void 0);m(this,Xo,void 0);m(this,ai,new Map);m(this,Er,1);m(this,Il,Ju(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>UD&&a(this,Er)===1?(f(this,Er,0),a(this,Yt).getValue("peerSessionStore").emit(_.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,Er)})):d<xD&&a(this,Er)===0&&(f(this,Er,1),a(this,Yt).getValue("peerSessionStore").emit(_.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,Er)}))},2e3));f(this,Yt,t);const{id:o,userId:c,displayName:d,device:l,picture:u,isHost:h,flags:g,clientSpecificId:S,stageStatus:y,customParticipantId:w,audioMuted:b,audioTrack:C,videoEnabled:D=!1,videoTrack:F,producers:L,metadata:B}=e;this.id=o,this.userId=c,this.name=d,this.device=l,this.picture=u,this.isHost=h,this.flags=g,this.manualProducerConfig=K_,f(this,ya,y!=null?y:"ON_STAGE"),this.customParticipantId=w!=null?w:S,this.audioEnabled=!b,this.audioTrack=C,this.videoEnabled=D,this.videoTrack=F,this.screenShareTracks={audio:void 0,video:void 0},this.producers=L!=null?L:[],this.presetName=B==null?void 0:B.preset_name,f(this,Ta,!1),f(this,yr,r),f(this,Xo,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),x(this,Zo,lp).call(this)}get clientSpecificId(){return this.customParticipantId}get stageStatus(){return a(this,ya)}get telemetry(){return a(this,Yt).getValue("telemetry")}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(this.logger.info("Participant::setVideoEnabled::videoUpdate",{...ki(this)}),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(this.logger.info("Participant::setAudioEnabled::audioUpdate",{...ki(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",x(this,Zo,lp)),a(this,ni,Ya)&&(this.on("audioUpdate",x(this,Al,pv)),this.on("screenShareUpdate",x(this,Ml,gv)))}async pin(){if(!a(this,Xi,ed))throw new k("Can`t pin participant without joining room","1205");if(!a(this,yr).permissions.pinParticipant)throw new k("You do not have permission to pin participants.","1201");return a(this,Qi,Zc).pinPeer(this.id)}async unpin(){if(!a(this,Xi,ed))throw new k("Can`t unpin participant without joining room","1205");if(!a(this,yr).permissions.pinParticipant)throw new k("You do not have permission to unpin participants.","1201");return a(this,Qi,Zc).pinPeer(null)}setIsPinned(t,e=!0){var i;f(this,Ta,t);const r=t?"pinned":"unpinned";(i=a(this,Zi,td))==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,ed))throw new k("Can`t disable participant audio without joining room","1205");if(a(this,yr).permissions.canDisableParticipantAudio)return a(this,Qi,Zc).disableAudio(t);throw this.logger.error("Participant::unauthorized_disable_audio",{participant:{id:t}}),new k("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,kl,hv))throw new k("Can`t kick participant without joining room","1205");if(a(this,yr).permissions.kickParticipant){await a(this,Yt).getValue("peerSessionStore").emitAsync(_.KICK_PEER,{peerId:t});return}throw this.logger.error("Participant::unauthorized_kick",{participant:{id:t}}),new k("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,ed))throw new k("Can`t disable participant video without joining room","1205");if(a(this,yr).permissions.canDisableParticipantVideo)return a(this,Qi,Zc).disableVideo(t);throw this.logger.error("Participant::unauthorized_disable_video",{participant:{id:t}}),new k("Unauthorized: User does not have permission to disable participant video.","1201")}async getPermissions(){return a(this,Xo).getUserPermissions(this.userId)}setStageStatus(t){f(this,ya,t),this.emit("stageStatusUpdate",this)}get isPinned(){return a(this,Ta)}registerVideoElement(t){var r,i,n,o;if(!t)return;let e;(i=(r=a(this,ai).get(t))==null?void 0:r.observer)==null||i.disconnect(),"ResizeObserver"in window&&(e=new ResizeObserver(()=>a(this,Il).call(this,t)),e.observe(t)),a(this,ai).set(t,{observer:e}),this.updateVideo(t),(o=a(this,Zi,td))==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,td))==null||e.removeSource(this.id);return}t.srcObject=void 0,(i=(r=a(this,ai).get(t))==null?void 0:r.observer)==null||i.disconnect(),a(this,ai).delete(t),(n=a(this,Zi,td))==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"}},Ta=new WeakMap,ya=new WeakMap,Yt=new WeakMap,Qi=new WeakSet,Zc=function(){return a(this,Yt).getValue("roomNodeClient")},ni=new WeakSet,Ya=function(){return a(this,Yt).getValue("audioPlayback")},Xi=new WeakSet,ed=function(){return a(this,Yt).getValue("connectionHandler").mediaJoined},kl=new WeakSet,hv=function(){return a(this,Yt).getValue("connectionHandler").socketJoined},yr=new WeakMap,Xo=new WeakMap,ai=new WeakMap,Zi=new WeakSet,td=function(){return a(this,Yt).getValue("pip")},Er=new WeakMap,Il=new WeakMap,Zo=new WeakSet,lp=function(){Array.from(a(this,ai).keys()).forEach(this.updateVideo)},Al=new WeakSet,pv=function(){var t,e;this.audioEnabled&&this.audioTrack?(t=a(this,ni,Ya))==null||t.addParticipantTrack(this.id,this.audioTrack):(e=a(this,ni,Ya))==null||e.removeParticipantTrack(this.id)},Ml=new WeakSet,gv=function(){var t,e;this.screenShareEnabled&&this.screenShareTracks.audio?(t=a(this,ni,Ya))==null||t.addParticipantTrack(`screenshare-${this.id}`,this.screenShareTracks.audio):(e=a(this,ni,Ya))==null||e.removeParticipantTrack(`screenshare-${this.id}`)},ZS);$n([E.trace("Participant.disableAudio")],dr.prototype,"disableAudio",1),$n([E.trace("Participant.kick")],dr.prototype,"kick",1),$n([E.trace("Participant.disableVideo")],dr.prototype,"disableVideo",1),$n([E.trace("Participant.getPermissions")],dr.prototype,"getPermissions",1),$n([E.trace("Participant.setStageStatus")],dr.prototype,"setStageStatus",1),dr=$n([lt("1200")],dr);class wo extends xf{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 FD extends Dn{constructor(e){super(e);m(this,oi,void 0);f(this,oi,new Map)}__set(e,r){return a(this,oi).set(e,r)}__clear(){return a(this,oi).clear()}get(e){return a(this,oi).get(e)}toArray(){return Array.from(a(this,oi).values())}}oi=new WeakMap;class $D{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 BD{constructor(){p(this,"_activeSpeakerPeers");p(this,"_compulsoryPeers");this._activeSpeakerPeers=new $D,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 sS=new BD;var HD=Object.defineProperty,qD=Object.getOwnPropertyDescriptor,Gt=(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};const jD=["ACTIVE_GRID","PAGINATED","MANUAL"];let Et=(ev=class extends $t{constructor(t,e,r){const i=t.getValue("logger");super(i);m(this,ec);m(this,en);m(this,Ea);p(this,"waitlisted");p(this,"joined");p(this,"active");p(this,"videoSubscribed");p(this,"audioSubscribed");p(this,"pinned");p(this,"all");m(this,Re,void 0);m(this,tn,void 0);m(this,Vt,void 0);p(this,"rateLimitConfig",{maxInvocations:5,period:1});p(this,"viewMode");p(this,"currentPage");p(this,"lastActiveSpeaker");p(this,"selectedPeers",sS);f(this,Re,t),f(this,tn,e),f(this,Vt,r),this.waitlisted=new wo(i),this.joined=new wo(i),this.videoSubscribed=new wo(i),this.audioSubscribed=new wo(i),this.active=this.videoSubscribed,this.pinned=new wo(i),this.all=new FD(i),this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return a(this,Re).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get telemetry(){return a(this,Re).getValue("telemetry")}setupEvents(){a(this,Re).getValue("peerSessionStore").on(_.E2EE_ACTIVE_CONSUMER,({peerId:e})=>{var r;((r=a(this,Re).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,Re).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,Re))==null?void 0:t.getValue("maxPreferredStreams")}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new k("0 <= Max active participants count limit <= 24","1203");a(this,Re).setValue("maxPreferredStreams",t),a(this,Ea,Su)&&a(this,Re).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,sd))throw new k("Can`t accept waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;return a(this,Vt).acceptWaitingRoomRequest([e])}async acceptAllWaitingRoomRequest(t){const e=t.map(r=>{var i,n;return(n=(i=this.waitlisted.get(r))==null?void 0:i.userId)!=null?n:r});return a(this,Vt).acceptWaitingRoomRequest(e)}async rejectWaitingRoomRequest(t){var r,i;if(!a(this,en,sd))throw new k("Can`t reject waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;a(this,Vt).rejectWaitingRoomRequest([e])}async setViewMode(t){if(this.logger.info("Participants::set_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),!(r=>jD.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 k(`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,Re).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="ACTIVE_GRID"?(this.currentPage=0,a(this,Re).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="MANUAL"&&(this.currentPage=0,a(this,Re).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 k("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,Re).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 k("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,Re).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 k(`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,Re).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,Ea,Su))throw new k("Can`t disable all audio without joining room","1205");if(a(this,tn).permissions.canAllowParticipantAudio)return a(this,ec,up).muteAll(t);throw this.logger.error("Participants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new k("Unauthorized: User does not have permission to disable peer audio.","1201")}async disableAllVideo(){if(this.logger.info("Participants::disable_all_video"),!a(this,Ea,Su))throw new k("Can`t disable all video without joining room","1205");if(a(this,tn).permissions.canAllowParticipantVideo)return a(this,ec,up).muteAllVideo();throw this.logger.error("Participants::unauthorized_disable_all_video"),new k("Unauthorized: User does not have permission to disable peer video.","1201")}async disableAudio(t){this.joined.get(t).disableAudio()}async disableVideo(t){this.joined.get(t).disableVideo()}async kick(t){await a(this,Re).getValue("peerSessionStore").emitAsync(_.KICK_PEER,{peerId:t})}async kickAll(){if(this.logger.info("Participants::kick_all"),a(this,Re).getValue("viewType")!=="LIVESTREAM"&&!a(this,en,sd))throw new k("Can`t kick all without joining room","1205");if(!a(this,tn).permissions.kickParticipant)throw this.logger.error("Participants::unauthorized_kick_all"),new k("Unauthorized: User does not have permission to kick peers.","1201");const e=a(this,Re).getValue("flagsmith").hasFeature(Z.PROPAGATE_KICK_ALL);a(this,Vt).kickAll(e)}async broadcastMessage(t,e,r){if(this.logger.info("Participants::broadcastMessage"),!a(this,en,sd))throw new k("Can`t broadcast message without joining room","1205");if(!(t!=null&&t.trim()))throw new k("`type` must be a non-empty string.","1209");if(r)if("meetingIds"in r)await a(this,Vt).broadcastToMeetings(t,r.meetingIds,e);else{let i=[];"participantIds"in r?i=r.participantIds:i=this.joined.toArray().filter(n=>{var o;return(o=r.presetNames)==null?void 0:o.includes(n.presetName)}).map(n=>n.id),await a(this,Vt).broadcastToPeers(t,i,e)}else await a(this,Vt).broadcastMessage(t,e)}async getAllJoinedPeers(t,e,r){return(await a(this,Vt).getRoomPeers(t,e,r)).peers.map(lr.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 k("Cannot update permissions, no valid userIDs found","1204");a(this,Vt).updatePermissions(i,e)}async getParticipantsInMeetingPreJoin(){return a(this,Vt).getRoomPeersNonPaginated()}},Re=new WeakMap,ec=new WeakSet,up=function(){return a(this,Re).getValue("roomNodeClient")},en=new WeakSet,sd=function(){var t;return((t=a(this,Re).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},Ea=new WeakSet,Su=function(){var t;return((t=a(this,Re).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},tn=new WeakMap,Vt=new WeakMap,ev);Gt([E.trace("Participants.setViewMode")],Et.prototype,"setViewMode",1),Gt([E.trace("Participants.setPage")],Et.prototype,"setPage",1),Gt([E.trace("Participants.disableAllAudio")],Et.prototype,"disableAllAudio",1),Gt([E.trace("Participants.disableAllVideo")],Et.prototype,"disableAllVideo",1),Gt([E.trace("Participants.disablePeerAudio")],Et.prototype,"disableAudio",1),Gt([E.trace("Participants.disablePeerVideo")],Et.prototype,"disableVideo",1),Gt([E.trace("Participants.kickPeer")],Et.prototype,"kick",1),Gt([E.trace("Participants.kickAll")],Et.prototype,"kickAll",1),Gt([E.trace("Participants.broadcastMessage"),Ot(Vn,"rateLimitConfig")],Et.prototype,"broadcastMessage",1),Gt([E.trace("Participants.getAllJoinedPeers"),Ot({maxInvocations:10,period:60})],Et.prototype,"getAllJoinedPeers",1),Gt([E.trace("Participant.updatePermissions"),Ot({maxInvocations:1e3,period:60})],Et.prototype,"updatePermissions",1),Gt([E.trace("Participants.getParticipantsInMeetingPreJoin")],Et.prototype,"getParticipantsInMeetingPreJoin",1),Et=Gt([lt("1200")],Et);var GD=Object.defineProperty,WD=Object.getOwnPropertyDescriptor,Ii=(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};const rS=(tv=class{constructor(s,t,e){p(this,"participants");p(this,"self");p(this,"selectedPeers",sS);p(this,"maxSpatialLayerUpdates",new Map);p(this,"consumerPeerMap");p(this,"events");p(this,"roomSocketHandler");p(this,"context");p(this,"videoPeerConsumerMap",new Map);m(this,ps,{mode:"ACTIVE_GRID",page:0});m(this,As,!1);m(this,wa,!1);p(this,"updateConsumerSpatialLayers",Ju(()=>{const s={},t=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(t.entries()).forEach(([e,r])=>{s[r]===void 0&&(s[r]={layer:r,consumerIds:[]}),s[r].consumerIds.push(e)}),Object.keys(s).forEach(e=>{const r=s[e];this.logger.log(`Switching max spatial layer to ${r.layer}`,{consumerIds:r.consumerIds}),this.roomNodeClient.switchConsumersToLayer(r.consumerIds,r.layer)})},2e3));p(this,"updateConsumers",async(s,t)=>{this.logger.info(`updateConsumers: Starting consumer updates - AddProducers: ${s.length}, RemoveProducers: ${t.length}, ConsumersSyncing: ${a(this,As)}`);try{s.length!==0&&(this.logger.info(`updateConsumers: Creating consumers for ${s.length} producers: [${s.map(e=>e.producerId).join(", ")}]`),await this.roomNodeClient.createConsumers(s),this.logger.info("updateConsumers: Successfully created consumers."))}catch(e){this.logger.error("updateConsumers: Error creating consumers",{error:e})}try{t.length!==0&&(this.logger.info(`updateConsumers: Closing consumers for ${t.length} producers: [${t.map(e=>e.producerId).join(", ")}]`),await this.roomNodeClient.closeConsumers(t),this.logger.info("updateConsumers: Successfully closed consumers."))}catch(e){this.logger.error("updateConsumers: Error closing consumers",{error:e})}this.logger.info("updateConsumers: Completed consumer updates.")});this.context=s,this.roomSocketHandler=e,this.participants=new Et(s,t,this.roomSocketHandler),this.self=t,this.consumerPeerMap=new Map,this.events=ws,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(U.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),this.context.getValue("peerSessionStore").on(_.SOCKET_PEERS,async s=>{const t=this.context.getValue("flagsmith").hasFeature(Z.DEBUG_SOCKET_JOIN);if(t){const e=s&&(s==null?void 0:s.length)<20?{peers:JSON.stringify(s.map(r=>r.peerId))}:void 0;this.logger.info("Processing socket peers",e)}s==null||s.forEach(e=>{e.waitlisted||this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(e))}),t&&this.logger.info("Processed socket peers")}),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.logger.info("events.peerJoinedBroadcast",{peers:s.peerId}),this.onParticipantMediaJoined(s.peerId,s.producerStates,s.capabilities)}),this.roomSocketHandler.on(this.events.selfJoinComplete,({participants:s,selectedPeers:t,roomState:e})=>{if(this.context.getValue("flagsmith").hasFeature(Z.DEBUG_SOCKET_JOIN)){const n=s&&(s==null?void 0:s.length)<20?{peers:JSON.stringify(s.map(o=>o.peerId))}:void 0;this.logger.info("events.selfJoinComplete",n)}s.forEach(({peerId:n,producerStates:o,capabilities:c})=>this.onParticipantMediaJoined(n,o,c));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.context.getValue("flagsmith").hasFeature(Z.DISABLE_LAYER_SWITCH)||(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,As)}, 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,As)}, 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 dr(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,ps).mode!==s&&(a(this,ps).mode=s),e&&a(this,ps).page!==e&&(a(this,ps).page=e);const{mode:r,page:i}=a(this,ps);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,ps))==null?void 0:e.mode)==="PAGINATED"&&!a(this,As)?200:0;this.logger.info(`scheduleSyncConsumers():: Source: ${s}, ViewMode: ${(r=a(this,ps))==null?void 0:r.mode}, ConsumersSyncing: ${a(this,As)}, Delay: ${t}, Page: ${(i=a(this,ps))==null?void 0:i.page}`),setTimeout(()=>this.syncConsumers(),t)}async syncConsumers(){var o,c,d,l,u;if(((d=(c=(o=this.context.getValue("connectionHandler"))==null?void 0:o.mediaState)==null?void 0:c.recv)==null?void 0:d.state)!=="connected"){this.logger.info("syncConsumers: Connection not ready, exiting.");return}if(a(this,As)){f(this,wa,!0),this.logger.info("syncConsumers: Sync in progress, marking resyncRequired=true and exiting.");return}this.logger.info("syncConsumers: Starting sync operation."),f(this,As,!0),f(this,wa,!1);let s=[];this.participants.videoSubscribed.forEach(h=>{var y,w;const g=this.participants.joined.get(h.id),S=(w=(y=h.producers)==null?void 0:y.filter(b=>b.kind==="video"))!=null?w:[];g&&(S!=null&&S.length)&&S.forEach(b=>{var F,L,B,W;const C=((L=(F=g.manualProducerConfig)==null?void 0:F.video)!=null?L:!0)&&b.kind==="video"&&!b.screenShare,D=((W=(B=g.manualProducerConfig)==null?void 0:B.screenshareVideo)!=null?W:!0)&&b.kind==="video"&&b.screenShare;(C||D)&&(b.pause||s.push(b))})}),this.participants.audioSubscribed.forEach(h=>{var y,w;const g=this.participants.joined.get(h.id),S=(w=(y=h.producers)==null?void 0:y.filter(b=>b.kind==="audio"))!=null?w:[];g&&(S!=null&&S.length)&&S.forEach(b=>{var F,L,B,W;const C=((L=(F=g.manualProducerConfig)==null?void 0:F.audio)!=null?L:!0)&&b.kind==="audio"&&!b.screenShare,D=((W=(B=g.manualProducerConfig)==null?void 0:B.screenshareAudio)!=null?W:!0)&&b.kind==="audio"&&b.screenShare;(C||D)&&s.push(b)})}),s=J_(s,h=>h.producerId);const t=new Map;s.forEach(h=>{t.set(h.producerId,h)});const e=(l=this.roomNodeClient)==null?void 0:l.getConsumers(),r=s.filter(h=>!(e!=null&&e.has(h.producerId))),i=[];let n=Array.from((u=e==null?void 0:e.values())!=null?u:[]).map(h=>h.peerId);n=W_(n),n==null||n.forEach(h=>{var S;const g=this.participants.joined.get(h);if(!g){this.logger.warn(`Peer with ${h} doesn't exist in joined list but producers of it are being consumed.`);return}(S=g.producers)!=null&&S.length&&g.producers.forEach(y=>{const w=y.consumer&&e.has(y.consumer.id);!t.has(y.producerId)&&(e.has(y.producerId)||w)&&i.push(y)})}),this.logger.info(`syncConsumers: Computed changes - AddProducers: ${r.length} [${r.map(h=>h.producerId).join(", ")}], RemoveProducers: ${i.length} [${i.map(h=>h.producerId).join(", ")}]`.substring(0,5e3));try{r.length>0||i.length>0?(this.logger.info(`syncConsumers: Calling updateConsumers with changes. Adding ${r.length} and removing ${i.length}.`),await this.updateConsumers(r,i),this.logger.info("syncConsumers: updateConsumers completed successfully.")):this.logger.info("syncConsumers: No changes needed, skipping updateConsumers.")}catch(h){this.logger.error("syncConsumers: updateConsumers failed with error.",{error:h})}finally{this.logger.info("syncConsumers: Setting consumersSyncing=false and completing sync."),f(this,As,!1)}a(this,wa)&&(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=rS.formatSocketPeerMessage(s);return new dr(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,e){if(!this.mediaJoined||s===this.self.id)return;const r=this.participants.joined.get(s);if(!r){this.logger.warn(`Received media.peerJoinedBroadcast for non-existent peer ${s}`);return}this.logger.info("PEER_INFO:::SOCKET_ON_MEDIA_JOIN",{participant:{id:r.id,maskedName:[...(r==null?void 0:r.name)||""].map((i,n)=>n%2?"*":i).join("")}}),this.logger.info(`onParticipantMediaJoined: peer ${s} has joined media room. Processing.`),t.forEach(i=>{i.kind===qs.AUDIO&&!i.screenShare?r.setAudioEnabled(!i.pause):i.kind===qs.VIDEO&&!i.screenShare&&(r.setVideoEnabled(!i.pause),this.updatePipSource(r.id,!i.pause)),r.producers.push({...i,producingTransportId:i.producingTransportId,kind:i.kind===qs.AUDIO?"audio":"video",producingPeerId:s,mimeType:i.mimeType})}),this.roomNodeClient.handlePeerCapabilities(s,e),this.context.getValue("flagsmith").hasFeature(Z.FORCE_VIDEO_CODEC)||this.roomNodeClient.shareWebcam(this.self.videoTrack),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(U.joinRoom,({peer:s})=>{if(!s.waitlisted){const t=this.context.getValue("flagsmith").hasFeature(Z.DEBUG_SOCKET_JOIN);t&&this.logger.info("Processing socket join",{peers:s.peerId}),this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(s)),t&&this.logger.info("Processed socket join",{peers:s.peerId})}}),this.roomSocketHandler.on(U.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,()=>{this.participants.joined.clear(),this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear(),this.participants.pinned.clear(),this.participants.currentPage=0,this.participants.viewMode="ACTIVE_GRID",this.participants.emit("viewModeChanged",{viewMode:"ACTIVE_GRID",currentPage:this.participants.currentPage,pageCount:this.participants.pageCount})}),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,({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,async({viewMode:s,page:t,createAllConsumers:e}={viewMode:"ACTIVE_GRID",page:0,createAllConsumers:!1})=>{this.logger.info(`UPDATE_ACTIVE event received - viewMode: ${a(this,ps).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){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.handlePeerLeaving(s),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 g;const t=this.processMedia(s),{peerId:e,kind:r,appData:i,track:n,remotelyPaused:o,producerId:c,rtpReceiver:d,localId:l}=t;if(!e)return;this.logger.info("ParticipantController::processConsumerResumed",{consumer:{id:s,peerId:e,kind:r,appData:i,remotelyPaused:o,producerId:c}});const u=this.participants.joined.get(e);if(!u)return;const h=u.producers.find(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),(g=this.context)==null||g.getValue("callstats").consumerSharedMediaState(s,{screen:!0});return}r==="video"?(u.videoTrack=n,u.setVideoEnabled(!0),this.updatePipSource(u.id,!0),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!0})):r==="audio"&&(u.audioTrack=n,u.setAudioEnabled(u.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:u.audioEnabled}))}processConsumerPaused(s){this.logger.info(`ParticipantController::processConsumerPaused called for consumerId: ${s}`);const{peerId:t,kind:e,track:r,appData:i,remotelyPaused:n,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(s);if(!t)return;this.logger.info("ParticipantController::processConsumerPaused",{consumer:{id:s,peerId:t,kind:e,appData:i,remotelyPaused:n,producerId:o}});const l=this.participants.joined.get(t);if(!l)return;const u=l.producers.find(h=>h.producerId===o);u&&(u.consumer={id:s,peerId:t,kind:e,appData:i,paused:n,producerId:o,rtpReceiver:c,localId:d}),r&&i.e2ee&&this.context.getValue("peerSessionStore").emit(_.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||this.context.getValue("flagsmith").hasFeature(Z.SCREEENSHARE_ERR_HACK))&&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})}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})}},ps=new WeakMap,As=new WeakMap,wa=new WeakMap,tv);let lr=rS;Ii([E.trace("ParticipantController.setupEvents")],lr.prototype,"setupEvents",1),Ii([E.trace("ParticipantController.setupEvents")],lr.prototype,"setupEventsGlobal",1),Ii([E.trace("ParticipantController.processMedia")],lr.prototype,"processMedia",1),Ii([E.trace("ParticipantController.processConsumerClosed")],lr.prototype,"processConsumerClosed",1),Ii([E.trace("ParticipantController.processConsumerResumed")],lr.prototype,"processConsumerResumed",1),Ii([E.trace("ParticipantController.processConsumerPaused")],lr.prototype,"processConsumerPaused",1),Ii([E.trace("ParticipantController.processNewConsumer")],lr.prototype,"processNewConsumer",1);const Te=bs(Hu().permissions),_a=class extends $t{constructor(e,r,i,n=!1){const o=e.getValue("logger");super(o);m(this,Rt);m(this,q,void 0);m(this,ba,void 0);m(this,Pa,void 0);m(this,Ol,e=>{var l,u,h;const{chat:r,connectedMeetings:i,plugins:n,polls:o,media:c,...d}=e;if(r&&(r.private&&Lr(a(this,q).chat.private,r.private),r.public&&Lr(a(this,q).chat.public,r.public),this.emit("chatUpdate")),i&&Lr(a(this,q).connectedMeetings,i),c){const g=y=>{switch(y){case xr.NONE:return H.Allowed;case xr.ALLOWED:return H.Allowed;case xr.NOT_ALLOWED:return H.NotAllowed;case xr.CAN_REQUEST:return H.CanRequest;default:return}},S={audio:void 0,video:void 0,screenshare:void 0};(l=c.audio)!=null&&l.canProduce&&(S.audio={canProduce:g(c.audio.canProduce)}),(u=c.video)!=null&&u.canProduce&&(S.video={canProduce:g(c.video.canProduce)}),(h=c.screenshare)!=null&&h.canProduce&&(S.screenshare={canProduce:g(c.screenshare.canProduce)}),Lr(a(this,q).media,S)}n&&(Lr(a(this,q).plugins,n),this.emit("pluginsUpdate")),o&&(Lr(a(this,q).polls,o),this.emit("pollsUpdate")),Object.keys(d).length!==0&&Lr(a(this,q),d),this.emit("permissionsUpdate",e)});if(!r)throw this.logger.error("PermissionPreset::load_preset_permissions_failed"),new k("Could not load preset permissions.","0904");f(this,Pa,e),f(this,ba,i),f(this,q,r),n&&this.setupEvents()}setupEvents(){a(this,Pa).getValue("peerSessionStore").on(_.UPDATE_PERMISSIONS,a(this,Ol))}static fromResponse(e,r,i){return new _a(i,e,r,!0)}static default(e,r){return new _a(e,Te,r)}static init(e,r,i){let n;return i?n=new _a(e,i,r,!0):n=new _a(e,Te,r),n}get mediaRoomType(){return"CF"}get stageEnabled(){var e;return((e=a(this,q))==null?void 0:e.stageEnabled)||a(this,ba)===tr.Webinar||a(this,ba)===tr.Livestream}get acceptStageRequests(){var e,r;return this.stageEnabled?((e=a(this,q))==null?void 0:e.acceptStageRequests)||((r=a(this,q))==null?void 0:r.canAcceptProductionRequests):!1}get stageAccess(){var e,r,i;return((e=a(this,q))==null?void 0:e.stageAccess)===H.NotAllowed?H.NotAllowed:((r=a(this,q))==null?void 0:r.stageAccess)===H.CanRequest?H.CanRequest:((i=a(this,q))==null?void 0:i.stageAccess)===H.Allowed||a(this,q).media.audio.canProduce===H.Allowed||a(this,q).media.video.canProduce===H.Allowed||a(this,q).media.screenshare.canProduce===H.Allowed?H.Allowed:a(this,q).media.audio.canProduce===H.CanRequest||a(this,q).media.video.canProduce===H.CanRequest||a(this,q).media.screenshare.canProduce===H.CanRequest?H.CanRequest:H.NotAllowed}get acceptWaitingRequests(){var e,r;return(r=(e=a(this,q))==null?void 0:e.acceptWaitingRequests)!=null?r:Te.acceptWaitingRequests}get requestProduceVideo(){var e,r,i;return((i=(r=(e=a(this,q))==null?void 0:e.media)==null?void 0:r.video)==null?void 0:i.canProduce)===H.CanRequest}get requestProduceAudio(){var e,r,i;return((i=(r=(e=a(this,q))==null?void 0:e.media)==null?void 0:r.audio)==null?void 0:i.canProduce)===H.CanRequest}get requestProduceScreenshare(){var e,r,i;return((i=(r=(e=a(this,q))==null?void 0:e.media)==null?void 0:r.screenshare)==null?void 0:i.canProduce)===H.CanRequest}get canAllowParticipantAudio(){var e,r;return(r=(e=a(this,q))==null?void 0:e.disableParticipantAudio)!=null?r:Te.disableParticipantAudio}get canAllowParticipantScreensharing(){var e,r;return(r=(e=a(this,q))==null?void 0:e.canAcceptProductionRequests)!=null?r:Te.canAcceptProductionRequests}get canAllowParticipantVideo(){var e,r;return(r=(e=a(this,q))==null?void 0:e.disableParticipantVideo)!=null?r:Te.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var e,r;return(r=(e=a(this,q))==null?void 0:e.kickParticipant)!=null?r:Te.kickParticipant}get pinParticipant(){var e,r;return(r=(e=a(this,q))==null?void 0:e.pinParticipant)!=null?r:Te.pinParticipant}get canRecord(){var e,r;return(r=(e=a(this,q))==null?void 0:e.canRecord)!=null?r:Te.canRecord}get waitingRoomType(){var e,r;return(r=(e=a(this,q))==null?void 0:e.waitingRoomType)!=null?r:Te.waitingRoomType}get waitingRoomBehaviour(){var e,r;return(r=(e=a(this,q))==null?void 0:e.waitingRoomType)!=null?r:Te.waitingRoomType}get plugins(){var e,r;return(r=(e=a(this,q))==null?void 0:e.plugins)!=null?r:Te.plugins}get polls(){var e,r;return(r=(e=a(this,q))==null?void 0:e.polls)!=null?r:Te.polls}get produceVideo(){return this.canProduceVideo}get requestProduce(){return a(this,q).media.audio.canProduce===H.CanRequest||a(this,q).media.video.canProduce===H.CanRequest||a(this,q).media.screenshare.canProduce===H.CanRequest}get canProduceVideo(){var r;const e=(r=a(this,q).media.video.canProduce)!=null?r:Te.media.video.canProduce;return this.stageEnabled&&(a(this,Rt,es)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Rt,es)==="ON_STAGE")&&e===H.CanRequest?H.Allowed:this.stageEnabled&&(a(this,Rt,es)==="OFF_STAGE"||a(this,Rt,es)==="REQUESTED_TO_JOIN_STAGE")&&e===H.Allowed?H.NotAllowed:e}get produceScreenshare(){return this.canProduceScreenshare}get canProduceScreenshare(){var r;const e=(r=a(this,q).media.screenshare.canProduce)!=null?r:Te.media.screenshare.canProduce;return this.stageEnabled&&(a(this,Rt,es)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Rt,es)==="ON_STAGE")&&e===H.CanRequest?H.Allowed:this.stageEnabled&&(a(this,Rt,es)==="OFF_STAGE"||a(this,Rt,es)==="REQUESTED_TO_JOIN_STAGE")&&e===H.Allowed?H.NotAllowed:e}get produceAudio(){return this.canProduceAudio}get canProduceAudio(){var r;const e=(r=a(this,q).media.audio.canProduce)!=null?r:Te.media.audio.canProduce;return this.stageEnabled&&(a(this,Rt,es)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Rt,es)==="ON_STAGE")&&e===H.CanRequest?H.Allowed:this.stageEnabled&&(a(this,Rt,es)==="OFF_STAGE"||a(this,Rt,es)==="REQUESTED_TO_JOIN_STAGE")&&e===H.Allowed?H.NotAllowed:e}get chatPublic(){var e,r,i;return(i=(r=(e=a(this,q))==null?void 0:e.chat)==null?void 0:r.public)!=null?i:Te.chat.public}get chatPrivate(){var e,r,i;return(i=(r=(e=a(this,q))==null?void 0:e.chat)==null?void 0:r.private)!=null?i:Te.chat.private}get connectedMeetings(){var e,r;return(r=(e=a(this,q))==null?void 0:e.connectedMeetings)!=null?r:Te==null?void 0:Te.connectedMeetings}get hiddenParticipant(){var e,r;return(r=(e=a(this,q))==null?void 0:e.hiddenParticipant)!=null?r:Te.hiddenParticipant}get showParticipantList(){var e;return(e=a(this,q).showParticipantList)!=null?e:Te.showParticipantList}get canChangeParticipantRole(){var e,r;return(r=(e=a(this,q))==null?void 0:e.canChangeParticipantPermissions)!=null?r:Te.canChangeParticipantPermissions}get canChangeParticipantPermissions(){var e,r;return(r=(e=a(this,q))==null?void 0:e.canChangeParticipantPermissions)!=null?r:Te.canChangeParticipantPermissions}get canChangeTheme(){return!1}get canPresent(){return a(this,q).media.audio.canProduce===H.Allowed||a(this,q).media.video.canProduce===H.Allowed||a(this,q).media.screenshare.canProduce===H.Allowed}get acceptPresentRequests(){return this.acceptStageRequests}get canEditDisplayName(){var e;return(e=a(this,q).canEditDisplayName)!=null?e:!1}get maxScreenShareCount(){return 1}get isRecorder(){return a(this,q).isRecorder}get canSpotlight(){return a(this,q).canSpotlight}get canLivestream(){return a(this,q).canLivestream}get transcriptionEnabled(){return a(this,q).transcriptionEnabled}};let Vh=_a;q=new WeakMap,ba=new WeakMap,Pa=new WeakMap,Ol=new WeakMap,Rt=new WeakSet,es=function(){return a(this,Pa).getValue("stageStatus")};class iS extends $t{constructor(e,r){super(r);p(this,"localMediaHandler");m(this,Qt,void 0);f(this,Qt,e)}async updatePermission(){var d,l;const e=(u,h)=>{this.mediaPermissions[u]=h;const g={message:this.mediaPermissions[u],kind:u};h==="DENIED"?a(this,Qt).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_ERROR,g):a(this,Qt).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,g)};if(be.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(be.init(),i&&f(this,Qt,i),!this.localMediaHandler)try{let g=!0;if((n=i==null?void 0:i.getValue("defaults"))!=null&&n.mediaHandler)g=!1,this.localMediaHandler=i.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:S}=navigator;this.localMediaHandler=await S.init(e)}else this.localMediaHandler=new Dt(i,e.constraints,(o=i==null?void 0:i.getValue("defaults"))==null?void 0:o.isNonPreferredDevice,(c=i==null?void 0:i.getValue("defaults"))==null?void 0:c.autoSwitchAudioDevice);if(i==null||i.getValue("peerSessionStore").on(_.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:y,message:w,constraints:b}=S;this.populateMediaPermissionsInCallstats({message:w,kind:y}),y==="audio"?(this.logger.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):y==="video"&&(this.logger.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),this.logger.error("SelfController::mediaPermissionError",{error:{message:w},constraints:b,mediaPermissionsErrors:{kind:y,message:w}}),this.emit("mediaPermissionError",S),this.emit("mediaPermissionUpdate",{message:w,kind:y})}),g){this.logger.info(`Setting up SelfMedia streams using media handler. audio:${(d=e==null?void 0:e.audio)!=null?d:!0} video:${(l=e==null?void 0:e.video)!=null?l:!0}`);const 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(g){this.logger.error("Self::init::Failed To Setup Streams",{error:{name:g.name,message:g.message}})}}set context(e){f(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 JD=Object.defineProperty,KD=Object.getOwnPropertyDescriptor,wt=(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};let Ze=(sv=class extends iS{constructor(t,e,r,i,n){var c;const o=t.getValue("logger");super(t,o);m(this,wr);m(this,ze);m(this,ka);m(this,He);m(this,tc);p(this,"name");p(this,"picture");p(this,"customParticipantId");p(this,"waitlistStatus");m(this,Ra,void 0);m(this,Ct,void 0);m(this,Ca,void 0);p(this,"role");p(this,"userId");p(this,"organizationId");p(this,"supportsRemoteControl",!1);p(this,"device");m(this,We,void 0);p(this,"hidden",!1);p(this,"presetName");p(this,"roomState","init");m(this,Ia,new Set);m(this,Aa,new Set);f(this,We,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=(c=e.customParticipantId)!=null?c:e.clientSpecificId,this.waitlistStatus="none",f(this,Ct,r),f(this,Ra,i),this.hidden=!1,f(this,Ca,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=be.isElectron(),this.device=be.getDeviceInfo(),this.presetName=n,this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),x(this,tc,hp).call(this)}get telemetry(){return a(this,We).getValue("telemetry")}get stageStatus(){return a(this,We).getValue("stageStatus")}get producers(){var t,e;return Array.from((e=(t=a(this,ze,ct).getProducers())==null?void 0:t.values())!=null?e:[])}get id(){return this.peerId}get peerId(){return a(this,We).getValue("peerId")}static async __init__(t,e,r,i,n,o=!1){var g,S,y,w,b,C;let c=(S=(g=t.getValue("defaults"))==null?void 0:g.audio)!=null?S:!0,d=(w=(y=t.getValue("defaults"))==null?void 0:y.video)!=null?w:!0;r.canProduceAudio!=="ALLOWED"&&(c=!1),r.canProduceVideo!=="ALLOWED"&&(d=!1);const l=new Ze(t,e,r,i,n),u=iD(i.mediaConstraints);Lr(u,(b=t.getValue("defaults"))==null?void 0:b.mediaConfiguration);const h=(C=t.getValue("defaults"))==null?void 0:C.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,Ct).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",x(this,tc,hp));const t=a(this,ka,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",{...ki(this)}),a(this,He,Xe)&&this.audioEnabled)try{await a(this,ze,ct).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",{...ki(this)}),a(this,He,Xe)&&this.rawVideoTrack===void 0)this.logger.info("Self::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&a(this,He,Xe))try{const e=await a(this,ze,ct).shareWebcam(this.videoTrack);e&&e.id!==this.videoTrack.id&&a(this,We).getValue("flagsmith").hasFeature(Z.EXP_RESHARE)&&await a(this,ze,ct).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,ka,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,He,Xe)){this.logger.error("Self.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{await a(this,ze,ct).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",{...ki(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",{...ki(this)})}),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{var e;(e=a(this,We))==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,He,Xe)&&await a(this,ze,ct).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(e=a(this,We))==null||e.getValue("callstats").videoOff()}),a(this,Ct).on("permissionsUpdate",e=>{var r,i,n;(r=e==null?void 0:e.media)!=null&&r.audio&&a(this,Ct).canProduceAudio!==H.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,Ct).canProduceVideo!==H.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,Ct).canProduceScreenshare!==H.Allowed&&(this.disableScreenShare(),this.logger.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return a(this,Ct)}get config(){return a(this,Ra)}get roomJoined(){var t;return a(this,Ra).viewType===tr.Livestream&&this.stageStatus!=="ON_STAGE"?((t=a(this,We).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:a(this,He,Xe)}setName(t){if(!t)throw new k("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!==H.NotAllowed&&!(a(this,Ct).canProduceAudio===H.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if((e=a(this,We))==null||e.getValue("callstats").audioOn(),await this.localMediaHandler.enableAudio(t),a(this,He,Xe)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{await a(this,ze,ct).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,Ct).canProduceVideo!==H.NotAllowed&&!(a(this,Ct).canProduceVideo===H.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if((e=a(this,We))==null||e.getValue("callstats").videoOn(),await this.localMediaHandler.enableVideo(t),a(this,He,Xe)&&this.stageStatus==="ON_STAGE")try{await a(this,ze,ct).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",{...ki(this)})}}async updateVideoConstraints(t){if(!this.localMediaHandler.updateVideoConstraints)throw new k("Unsupported","1102");await this.localMediaHandler.updateVideoConstraints(t)}async enableScreenShare(){if(!a(this,He,Xe))throw new k("Can`t enable screenshare without joining room","1105");if(a(this,Ct).canProduceScreenshare!==H.NotAllowed&&!(a(this,Ct).canProduceScreenshare===H.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,ze,ct).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 k("Unsupported","1102");await this.localMediaHandler.updateScreenshareConstraints(t)}async disableAudio(){var t;this.audioEnabled&&(this.localMediaHandler.disableAudio(),a(this,He,Xe)&&a(this,ze,ct).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),(t=a(this,We))==null||t.getValue("callstats").audioOff())}async disableVideo(){var t;this.videoEnabled&&(await this.localMediaHandler.disableVideo(),a(this,He,Xe)&&await a(this,ze,ct).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(t=a(this,We))==null||t.getValue("callstats").videoOff())}async disableScreenShare(){this.screenShareEnabled&&(await this.localMediaHandler.disableScreenShare(),a(this,He,Xe)&&await a(this,ze,ct).disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var i;f(this,Ca,t);const r=t?"pinned":"unpinned";(i=a(this,wr,Rn))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}get isPinned(){return a(this,Ca)}async pin(){if(!a(this,He,Xe))throw new k("Can`t pin participants without joining room","1105");return this.show(),a(this,ze,ct).pinPeer(this.id)}async unpin(){if(!a(this,He,Xe))throw new k("Can`t unpin participants without joining room","1105");return a(this,ze,ct).pinPeer(null)}async hide(){if(!a(this,He,Xe))throw new k("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})}show(){if(!a(this,He,Xe))throw new k("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 k("No device selected","1104");const e=this.getCurrentDevices();if(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]}),a(this,We).getValue("flagsmith").hasFeature(Z.SKIP_SETTING_IN_USE_DEVICE)))throw new k("Cannot set device currently in use","1106");switch(t.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(t,{saveDevicePreference:!0})}catch(o){a(this,He,Xe)&&await a(this,ze,ct).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,He,Xe)&&await a(this,ze,ct).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,ka,vu))==null?void 0:t.play()}registerVideoElement(t,e=!1){var r,i;t&&(e?a(this,Ia).add(t):a(this,Aa).add(t),this.updateVideo(t),e||(i=a(this,wr,Rn))==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,wr,Rn).removeSource(this.id);return}t.srcObject=void 0,e?a(this,Ia).delete(t):(a(this,Aa).delete(t),a(this,wr,Rn).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,wr,Rn))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(n=a(this,wr,Rn))==null||n.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},Ra=new WeakMap,Ct=new WeakMap,Ca=new WeakMap,We=new WeakMap,wr=new WeakSet,Rn=function(){return a(this,We).getValue("pip")},ze=new WeakSet,ct=function(){return a(this,We).getValue("roomNodeClient")},ka=new WeakSet,vu=function(){return a(this,We).getValue("audioPlayback")},He=new WeakSet,Xe=function(){var t;return((t=a(this,We).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Ia=new WeakMap,Aa=new WeakMap,tc=new WeakSet,hp=function(){Array.from(a(this,Aa)).forEach(t=>this.updateVideo(t,!1)),Array.from(a(this,Ia)).forEach(t=>this.updateVideo(t,!0))},sv);wt([E.trace("Self.cleanupEvents")],Ze.prototype,"cleanupEvents",1),wt([E.trace("Self.setupEvents")],Ze.prototype,"setupEvents",1),wt([E.trace("Self.setupTracks")],Ze.prototype,"setupTracks",1),wt([E.trace("Self.destructMediaHandler")],Ze.prototype,"destructMediaHandler",1),wt([E.trace("Self.removeDocumentEventListeners")],Ze.prototype,"removeDocumentEventListeners",1),wt([cr.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"Self.toggleAudio",timeout:3e3}),E.trace("Self.enableAudio")],Ze.prototype,"enableAudio",1),wt([cr.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"Self.toggleVideo",timeout:3e3}),E.trace("Self.enableVideo")],Ze.prototype,"enableVideo",1),wt([E.trace("Self.updateVideoConstraints")],Ze.prototype,"updateVideoConstraints",1),wt([E.trace("Self.enableScreenShare"),cr.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3})],Ze.prototype,"enableScreenShare",1),wt([E.trace("Self.updateScreenshareConstraints")],Ze.prototype,"updateScreenshareConstraints",1),wt([cr.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"Self.toggleAudio",timeout:3e3}),E.trace("Self.disableAudio")],Ze.prototype,"disableAudio",1),wt([cr.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"Self.toggleVideo",timeout:3e3}),E.trace("Self.disableVideo")],Ze.prototype,"disableVideo",1),wt([cr.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3}),E.trace("Self.disableScreenShare")],Ze.prototype,"disableScreenShare",1),wt([E.trace("Self.setDevice")],Ze.prototype,"setDevice",1),Ze=wt([lt("1100")],Ze);class Lh extends Error{constructor(t){super(t!=null?t:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Lh)}}class xh extends Error{constructor(t){super(t!=null?t:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,xh)}}class Uh{constructor(t,e=!1){p(this,"pendingTasks",new Map);p(this,"nextTaskId",0);p(this,"stopping",!1);m(this,sc,void 0);this.log=e,f(this,sc,{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 Lh);this.stopping=!1}remove(t){const e=Array.from(this.pendingTasks.values())[t];e&&e.reject(new xh)}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,sc).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)}}}sc=new WeakMap;function zD(s,t){const e=new Error(t);return e.name=s,e}class bo extends Error{constructor(t){super(t),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,bo):this.stack=new Error(t).stack}}class Nt extends Error{constructor(t){super(t),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Nt):this.stack=new Error(t).stack}}class Ai extends Error{constructor(t){super(t),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Nt):this.stack=new Error(t).stack}}const nS=s=>new Promise(t=>setTimeout(t,s));async function aS(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 YD(s){return s.map(t=>({channels:t.channels,clockRate:t.clockRate,mimeType:t.mimeType,sdpFmtpLine:t.sdpFmtpLine}))}function QD(s){return s.map(t=>({uri:t.uri}))}function tl(s){return{codecs:YD(s.codecs),headerExtensions:QD(s.headerExtensions?s.headerExtensions:[])}}function XD(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:tl(t),video:tl(e)};return{sender:{audio:tl(r),video:tl(i)},receiver:n}}class ZD{constructor(t){m(this,rt,void 0);p(this,"events");f(this,rt,t),this.events=ws}async joinRoom(t,e,r,i=!1,n=null){const o={roomUuid:t,displayName:e,prejoined:i,capabilities:r};return n&&(o.location=n),(await a(this,rt).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:fC.toBinary(o),timeout:5e3})).payload}async connectTransport(t){const e=(await a(this,rt).sendMessagePromise(this.events.createWebRTCTransport,jR.toBinary(t))).payload,{transportId:r,description:i,producerIds:n}=jm.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,rt).sendMessagePromise(this.events.produce,MC.toBinary(t))).payload,r=pk.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,rt).sendMessagePromise(this.events.consume,_C.toBinary(t))).payload,{consumerIdsMap:{map:r},description:i}=uk.fromBinary(e);return{consumerStateMap:r,sessionDescription:i}}async closeProducer(t){const e=(await a(this,rt).sendMessagePromise(this.events.closeProducer,UC.toBinary(t))).payload,{description:r}=yk.fromBinary(e);return r}async closeConsumer(t){return(await a(this,rt).sendMessagePromise(this.events.closeConsumer,$C.toBinary(t))).payload}async updateConsumersSimulcastConfig(t){return(await a(this,rt).sendMessagePromise(this.events.updateConsumersSimulcastConfig,IC.toBinary(t))).payload}async hostControlForPeer(t,e){const r={audio:e==="audio",screeShare:!1,video:e==="video",participantId:t},i=(await a(this,rt).sendMessagePromise(this.events.hostControlPeer,WC.toBinary(r))).payload;if(!i)return!1;const{status:n}=Ck.fromBinary(i);return n==="success"}async hostControlForAll(t){const e={audio:t==="audio",screenShare:!1,video:t==="video"},r=(await a(this,rt).sendMessagePromise(this.events.hostControlAllPeers,KC.toBinary(e))).payload;if(!r)return!1;const{status:i}=Ik.fromBinary(r);return i==="success"}async kickAll(){const t={propagateKickAcrossRooms:!1};a(this,rt).sendMessagePromise(U.kickAll,Ym.toBinary(t))}async kickPeer(t){a(this,rt).sendMessagePromise(U.kick,hf.toBinary(t))}async changeDisplayName(t){const e=(await a(this,rt).sendMessagePromise(this.events.changeDisplayName,jC.toBinary(t))).payload;if(!e)return!1;const{status:r}=Mk.fromBinary(e);return r==="success"}async notifySelfJoinComplete(){const t={},e=(await a(this,rt).sendMessagePromise(this.events.selfJoinComplete,vC.toBinary(t))).payload;return nh.fromBinary(e)}async audioActivity(t){a(this,rt).sendMessage(this.events.audioActivity,WR.toBinary(t))}}rt=new WeakMap;var Bn=(s=>(s.NEW="new",s.CONNECTING="connecting",s.RECONNECTING="reconnecting",s.DISCONNECTED="disconnected",s.CONNECTED="connected",s.FAILED="failed",s.CLOSED="closed",s))(Bn||{});class sl extends dt.EventEmitter{constructor(e){super();m(this,rc,void 0);f(this,rc,e),this.setMaxListeners(1/0)}get logger(){return a(this,rc).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)}})}}rc=new WeakMap;class Fh extends sl{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(`${this.name}::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:async i=>{this.logger.info(`${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"});const e=await this.pc.createOffer();return await this.pc.setLocalDescription(e),this.logger.info(`connect offer: ${JSON.stringify(e)}`),{offerSdp:e,callback:async i=>{this.logger.debug(`${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(`stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(i)}]`),await this.pc.setLocalDescription(i),{offerSdp:i,callback:async o=>{this.logger.debug(`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}})}),this.pc.addEventListener("datachannel",e=>{this.logger.info("data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{this.logger.info("data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{this.logger.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{this.logger.error("data channel error: ",{rtcChannel:{label:e.channel.label}})}}),this.addCustomEventListeners()}addCustomEventListeners(){}}class $h extends Fh{static createFactory(t){return()=>new $h(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 g;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=((g=h.sdpFmtpLine)==null?void 0:g.split(";"))||[];S.push(...u.parameters);const y=Array.from(new Set(S).values());h.sdpFmtpLine=y.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
|
|
14
|
-
`}this.midTransceiverMap.set(n.mid,n);const c=async d=>(this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),await this.pc.setRemoteDescription(d),n.mid);return this.logger.debug(`send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(o,void 0,2)}]`),{offerSdp:o,callback:c,sender:n.sender,mid:n.mid}}addCustomEventListeners(){this.pc.addEventListener("datachannel",t=>{const{channel:e}=t;e.onmessage=r=>{this.safeEmit("datachannel",t.channel,String.fromCharCode(...new Uint8Array(r.data)))}})}}var oS={},rl={},e1={get exports(){return rl},set exports(s){rl=s}},cS=e1.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(cS).forEach(function(s){var t=cS[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=rl,n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);s.parse=function(c){var d={},l=[],u=d;return c.split(/(\r\n|\r|\n)/).filter(n).forEach(function(h){var g=h[0],S=h.slice(2);g==="m"&&(l.push({rtp:[],fmtp:[]}),u=l[l.length-1]);for(var y=0;y<(i[g]||[]).length;y+=1){var w=i[g][y];if(w.reg.test(S))return r(w,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}})})}}(oS);var Bh=rl,t1=/%[sdv%]/g,s1=function(s){var t=1,e=arguments,r=e.length;return s.replace(t1,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""}})},Po=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 s1.apply(null,i)},r1=["v","o","s","i","u","e","p","c","b","t","r","z","a"],i1=["i","c","b","a"],n1=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){Bh[n].forEach(function(o){o.name in s&&s[o.name]!=null?i.push(Po(n,o,s)):o.push in s&&s[o.push]!=null&&s[o.push].forEach(function(c){i.push(Po(n,o,c))})})}),s.media.forEach(function(n){i.push(Po("m",Bh.m[0],n)),r.forEach(function(o){Bh[o].forEach(function(c){c.name in n&&n[c.name]!=null?i.push(Po(o,c,n)):c.push in n&&n[c.push]!=null&&n[c.push].forEach(function(d){i.push(Po(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 Qp extends lt{constructor(e){super();p(this,"call");p(this,"timeOut");this.call=new Xs(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 mT=8,fT=1/1e3;class ST extends Qp{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(Xs.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)*mT/(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*fT)})}}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 Eu extends Qp{constructor(e,r=Xs.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 vT extends Eu{constructor(t){super(t,Xs.isHost)}}class TT extends Eu{constructor(t){super(t,Xs.isRelay)}}class yT extends Eu{constructor(t){super(t,Xs.isReflexive)}}class ET{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=Vr(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=Vr(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 Xp=new ET,Zp=[{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 eg(s){const[t,e]=s.split(",");return{coords:{latitude:Number(t),longitude:Number(e)}}}class tg{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 sg extends lt{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 lt}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 w,b,C,D,F,L,B,Q,se,nt,Vs,_n,Ls;const c=e,d=new tg,l=r.length?new Set(r):void 0,u=[],h=[],g=[],S=new Map,y=new Map;for(const I of c.values()){if(l){if(l.size===0)break;if(l.has(I.type))i&&l.delete(I.type);else continue}switch(I.type){case"local-candidate":{u.push(this.getIceCandidateStats(I));break}case"remote-candidate":{h.push(this.getIceCandidateStats(I));break}case"candidate-pair":{const{nominated:T}=I,{selected:P}=I,$=I,Ce={nominated:T!=null?T:P,currentRoundTripTime:$.currentRoundTripTime,totalRoundTripTime:$.totalRoundTripTime,bytesReceived:$.bytesReceived,bytesSent:$.bytesSent,availableOutgoingBitrate:$.availableOutgoingBitrate,availableIncomingBitrate:$.availableIncomingBitrate,lastPacketReceivedTimestamp:$.lastPacketReceivedTimestamp,lastPacketSentTimestamp:$.lastPacketSentTimestamp,localCandidateId:$.localCandidateId,remoteCandidateId:$.remoteCandidateId,bytesDiscardedOnSend:$.bytesDiscardedOnSend,packetsSent:$.packetsSent,packetsReceived:$.packetsReceived,packetsDiscardedOnSend:$.packetsDiscardedOnSend};g.push(Ce),(I.nominated===!0||I.selected===!0)&&(d.candidatePair=Ce);break}case"transport":{const T=I;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 P={bytesReceived:T.bytesReceived,bytesSent:T.bytesSent,packetsSent:T.packetsSent,packetsReceived:T.packetsReceived,dtlsCipher:T.dtlsCipher,dtlsState:T.dtlsState,iceRole:T.iceRole};if(d.transport=P,o){if(o.producing){const $=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,$,P)}if(o.consuming){const $=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,$,P)}}break}case"remote-inbound-rtp":{const T=I,P={jitter:T.jitter,fractionLost:T.fractionLost,roundTripTime:T.roundTripTime,roundTripTimeMeasurements:T.roundTripTimeMeasurements,totalRoundTripTime:T.totalRoundTripTime,packetsLost:T.packetsLost};d.remoteInboundRtp.set(T.localId,P);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(I.id))break;const T=I,P=n||this.outboundProducerMap.get(I.id),$=this.pausedProducerMap.get(P);if($){if($.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const Ce=this.overallProducersStatsMap[P];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.outboundProducerMap.has(I.id)){d.staleProducerStreamMap=!0;break}const qe=this.callStatsInstance.producers.get(P);if(((w=qe==null?void 0:qe.track)==null?void 0:w.readyState)==="ended")break;d.producerStreamMap.has(P)||d.producerStreamMap.set(P,{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 R=T,Je={frameHeight:R.frameHeight,frameWidth:R.frameWidth,framesEncoded:R.framesEncoded,framesDropped:R.framesDropped,framesPerSecond:R.framesPerSecond,framesSent:R.framesSent,keyFramesEncoded:R.keyFramesEncoded,firCount:R.firCount,encoderImplementation:R.encoderImplementation,hugeFramesSent:R.hugeFramesSent,pliCount:R.pliCount,qpSum:R.qpSum,qualityLimitationDurations:R.qualityLimitationDurations,qualityLimitationReason:R.qualityLimitationReason,qualityLimitationResolutionChanges:R.qualityLimitationResolutionChanges,totalEncodeTime:R.targetBitrate,totalPacketSendDelay:R.totalPacketSendDelay,retransmittedBytesSent:R.retransmittedBytesSent,retransmittedPacketsSent:R.retransmittedPacketsSent,scalabilityMode:R.scalabilityMode,powerEfficientEncoder:R.powerEfficientEncoder,...V};d.outboundVideoRtp.set(I.id,Je),d.producerStreamMap.get(P).outboundVideoRtpId.push(I.id),this.processOutboundProducerVideoStats(P,Ce,Je)}else if(T.mediaType==="audio"||T.kind==="audio"){const R=T,Je={retransmittedBytesSent:R.retransmittedBytesSent,retransmittedPacketsSent:R.retransmittedPacketsSent,...V};d.outboundAudioRtp.set(I.id,Je),d.producerStreamMap.get(P).outboundAudioRtpId.push(I.id),this.processOutboundProducerAudioStats(P,Ce,Je)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(I.id))break;const T=I,P=n||this.inboundConsumerMap.get(I.id),$=this.pausedConsumerMap.get(P);if($){if($.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(T.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const Ce=this.overallConsumersStatsMap[P];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.inboundConsumerMap.has(I.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(P)||d.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const qe={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,R={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,...qe};R.score=Yp({frameWidth:R.frameWidth||0,framesDecoded:(R.framesDecoded||0)-(((b=this.videoConsumerToStatsMap.get(P))==null?void 0:b.framesDecoded)||0),framesPerSecond:R.framesPerSecond||0,packetsLost:(R.packetsLost||0)-(((C=this.videoConsumerToStatsMap.get(P))==null?void 0:C.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((D=this.videoConsumerToStatsMap.get(P))==null?void 0:D.packetsReceived)||0),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),y.set(P,{score:+(R.score*10).toFixed(),frameWidth:R.frameWidth||0,frameHeight:R.frameHeight||0,framesPerSecond:R.framesPerSecond||0,packetsLostPercentage:cd({packetsLost:(R.packetsLost||0)-(((F=this.videoConsumerToStatsMap.get(P))==null?void 0:F.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((L=this.videoConsumerToStatsMap.get(P))==null?void 0:L.packetsReceived)||0)}),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((R.bytesReceived||0)-(((B=this.videoConsumerToStatsMap.get(P))==null?void 0:B.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,R),d.inboundVideoRtp.set(I.id,R),d.consumerStreamMap.get(P).inboundVideoRtpId.push(I.id),this.processInboundConsumerVideoStats(P,Ce,R)}else if(T.mediaType==="audio"||T.kind==="audio"){const V=T,R={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,...qe};R.score=zp({concealmentEvents:(R.concealmentEvents||0)-(((Q=this.audioConsumerToStatsMap.get(P))==null?void 0:Q.concealmentEvents)||0),packetsLost:(R.packetsLost||0)-(((se=this.audioConsumerToStatsMap.get(P))==null?void 0:se.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((nt=this.audioConsumerToStatsMap.get(P))==null?void 0:nt.packetsReceived)||0),jitter:R.jitter||0}),y.set(P,{score:+(R.score*10).toFixed(),packetsLostPercentage:cd({packetsLost:(R.packetsLost||0)-(((Vs=this.audioConsumerToStatsMap.get(P))==null?void 0:Vs.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((_n=this.audioConsumerToStatsMap.get(P))==null?void 0:_n.packetsReceived)||0)}),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((R.bytesReceived||0)-(((Ls=this.audioConsumerToStatsMap.get(P))==null?void 0:Ls.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,R),d.inboundAudioRtp.set(I.id,R),d.consumerStreamMap.get(P).inboundAudioRtpId.push(I.id),this.processInboundConsumerAudioStats(P,Ce,R)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}}}if(d.producerStreamMap.forEach((I,T)=>{var P,$,Ce,qe,V,R,Je,Dr,xc,Uc,Fc,$c,Bc,Hc,qc,jc,Gc,Wc,Jc,Kc,zc,Yc,Qc;if(I.outboundVideoRtpId.length>0){const he=[];I.outboundVideoRtpId.forEach(Zh=>{he.push(d.outboundVideoRtp.get(Zh))});const ee=this.getWorkingSimulcastVideoStats(he);ee.score=Jp({frameWidth:ee.frameWidth||0,framesPerSecond:ee.framesPerSecond||0,jitter:((P=ee.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsSent:(ee.packetsSent||0)-((($=this.videoProducerToStatsMap.get(T))==null?void 0:$.packetsSent)||0),packetsLost:(((Ce=ee.remoteData)==null?void 0:Ce.packetsLost)||0)-(((V=(qe=this.videoProducerToStatsMap.get(T))==null?void 0:qe.remoteData)==null?void 0:V.packetsLost)||0),framesEncoded:(ee.framesEncoded||0)-(((R=this.videoProducerToStatsMap.get(T))==null?void 0:R.framesEncoded)||0)}),S.set(T,{score:+(ee.score*10).toFixed(),frameWidth:ee.frameWidth||0,frameHeight:ee.frameHeight||0,framesPerSecond:ee.framesPerSecond||0,jitter:((Je=ee.remoteData)==null?void 0:Je.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsLostPercentage:od({packetsSent:(ee.packetsSent||0)-(((Dr=this.videoProducerToStatsMap.get(T))==null?void 0:Dr.packetsSent)||0),packetsLost:(((xc=ee.remoteData)==null?void 0:xc.packetsLost)||0)-(((Fc=(Uc=this.videoProducerToStatsMap.get(T))==null?void 0:Uc.remoteData)==null?void 0:Fc.packetsLost)||0)}),bitrate:((ee.bytesSent||0)-((($c=this.videoProducerToStatsMap.get(T))==null?void 0:$c.bytesSent)||0))*8/7,cpuLimitations:ee.qualityLimitationReason==="cpu",bandwidthLimitations:ee.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(T,ee)}else if(I.outboundAudioRtpId.length>0){const he=d.outboundAudioRtp.get(I.outboundAudioRtpId[0]);he.score=Wp({packetsSent:(he.packetsSent||0)-(((Bc=this.audioProducerToStatsMap.get(T))==null?void 0:Bc.packetsSent)||0),packetsLost:(((Hc=he.remoteData)==null?void 0:Hc.packetsLost)||0)-(((jc=(qc=this.audioProducerToStatsMap.get(T))==null?void 0:qc.remoteData)==null?void 0:jc.packetsLost)||0),jitter:((Gc=he.remoteData)==null?void 0:Gc.jitter)||0}),S.set(T,{score:+(he.score*10).toFixed(),bitrate:((he.bytesSent||0)-(((Wc=this.audioProducerToStatsMap.get(T))==null?void 0:Wc.bytesSent)||0))*8/7,packetsLostPercentage:od({packetsSent:(he.packetsSent||0)-(((Jc=this.audioProducerToStatsMap.get(T))==null?void 0:Jc.packetsSent)||0),packetsLost:(((Kc=he.remoteData)==null?void 0:Kc.packetsLost)||0)-(((Yc=(zc=this.audioProducerToStatsMap.get(T))==null?void 0:zc.remoteData)==null?void 0:Yc.packetsLost)||0)}),jitter:((Qc=he.remoteData)==null?void 0:Qc.jitter)||0,isScreenShare:this.screenShareProducers.has(T)}),this.audioProducerToStatsMap.set(T,he)}}),g.forEach(I=>{const T=u.find($=>$.id===I.localCandidateId?(I.localCandidateId=$.id,$):null),P=h.find($=>$.id===I.remoteCandidateId?(I.remoteCandidateId=$.id,$):null);T&&(I.localCandidateType=T.type,I.localCandidateAddress=Vr(T.address),I.localCandidatePort=T.port,I.localCandidateProtocol=T.protocol,I.localCandidateUrl=T.url,I.localCandidateNetworkType=T.networkType,I.localCandidateRelatedAddress=Vr(T.relatedAddress),I.localCandidateRelatedPort=T.relatedPort),P&&(I.remoteCandidateType=P.type,I.remoteCandidateAddress=Vr(P.address),I.remoteCandidatePort=P.port,I.remoteCandidateProtocol=P.protocol,I.remoteCandidateUrl=P.url)}),d.candidatePair&&(d.transport?(d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.availableIncomingBitrate=d.candidatePair.availableIncomingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:d.candidatePair.availableIncomingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=g),d.transport&&!d.transport.roundTripTime){let I=0,T=0;d.remoteInboundRtp.forEach((P,$)=>{P.roundTripTime&&P.roundTripTime>I&&(I=P.roundTripTime,T=P.totalRoundTripTime)}),d.transport.roundTripTime=I,d.transport.totalRoundTripTime=T}if(y.size>0)try{this.observer.emit("consumer_score",y)}catch(I){}if(S.size>0)try{this.observer.emit("producer_score",S)}catch(I){}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||Zp},i=new Promise((u,h)=>{try{const g=new vT(r);g.addListener("done",u),g.addListener("failed",()=>{u({connectivity:!1})}),g.start(2e3)}catch(g){h(g)}}),n=new Promise((u,h)=>{try{const g=new TT(r);g.addListener("done",u),g.addListener("failed",()=>{u({connectivity:!1})}),g.start(2e3)}catch(g){h(g)}}),o=new Promise((u,h)=>{try{const g=new yT(r);g.addListener("done",u),g.addListener("failed",()=>{u({connectivity:!1})}),g.start(2e3)}catch(g){h(g)}}),[c,d,l]=await Promise.all([i,n,o]);return{host:c==null?void 0:c.connectivity,relay:d==null?void 0:d.connectivity,reflexive:l==null?void 0:l.connectivity}}catch(r){return{host:!1,relay:!1,reflexive:!1}}}async getThroughput(e){try{const i=await new Promise((n,o)=>{try{const c={iceServers:e||Zp},d=new ST(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 Xp.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?eg(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?eg(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 bT extends sg{}class rg extends sg{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 w,b,C,D,F,L,B,Q,se,nt,Vs,_n,Ls;const c=e,d=new tg,l=r.length?new Set(r):void 0,u=[],h=[],g=[],S=new Map,y=new Map;for(const I of c.values()){if(l){if(l.size===0)break;if(l.has(I.type))i&&l.delete(I.type);else continue}switch(I.type){case"local-candidate":{u.push(this.getIceCandidateStats(I));break}case"remote-candidate":{h.push(this.getIceCandidateStats(I));break}case"candidate-pair":{const{nominated:T}=I,{selected:P}=I,$=I,Ce={nominated:T!=null?T:P,currentRoundTripTime:$.currentRoundTripTime,totalRoundTripTime:$.totalRoundTripTime,bytesReceived:$.bytesReceived,bytesSent:$.bytesSent,availableOutgoingBitrate:$.availableOutgoingBitrate,availableIncomingBitrate:$.availableIncomingBitrate,lastPacketReceivedTimestamp:$.lastPacketReceivedTimestamp,lastPacketSentTimestamp:$.lastPacketSentTimestamp,localCandidateId:$.localCandidateId,remoteCandidateId:$.remoteCandidateId,bytesDiscardedOnSend:$.bytesDiscardedOnSend,packetsSent:$.packetsSent,packetsReceived:$.packetsReceived,packetsDiscardedOnSend:$.packetsDiscardedOnSend};g.push(Ce),(I.nominated===!0||I.selected===!0)&&(d.candidatePair=Ce);break}case"transport":{const T=I;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 P={bytesReceived:T.bytesReceived,bytesSent:T.bytesSent,packetsSent:T.packetsSent,packetsReceived:T.packetsReceived,dtlsCipher:T.dtlsCipher,dtlsState:T.dtlsState,iceRole:T.iceRole};if(d.transport=P,o){if(o.producing){const $=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,$,P)}if(o.consuming){const $=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,$,P)}}break}case"remote-inbound-rtp":{const T=I,P={jitter:T.jitter,fractionLost:T.fractionLost,roundTripTime:T.roundTripTime,roundTripTimeMeasurements:T.roundTripTimeMeasurements,totalRoundTripTime:T.totalRoundTripTime,packetsLost:T.packetsLost};d.remoteInboundRtp.set(T.localId,P);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(I.id))break;const T=I,P=n||this.outboundProducerMap.get(I.id),$=this.pausedProducerMap.get(P);if($){if($.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const Ce=this.overallProducersStatsMap[P];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.outboundProducerMap.has(I.id)){d.staleProducerStreamMap=!0;break}const qe=this.callStatsInstance.producers.get(P);if(((w=qe==null?void 0:qe.track)==null?void 0:w.readyState)==="ended")break;d.producerStreamMap.has(P)||d.producerStreamMap.set(P,{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 R=T,Je={frameHeight:R.frameHeight,frameWidth:R.frameWidth,framesEncoded:R.framesEncoded,framesDropped:R.framesDropped?R.framesDropped:R.droppedFrames,framesPerSecond:R.framesPerSecond?R.framesPerSecond:R.framerateMean,framesSent:R.framesSent,keyFramesEncoded:R.keyFramesEncoded,firCount:R.firCount,encoderImplementation:R.encoderImplementation,hugeFramesSent:R.hugeFramesSent,pliCount:R.pliCount,qpSum:R.qpSum,qualityLimitationReason:R.qualityLimitationReason,qualityLimitationDurations:R.qualityLimitationDurations,qualityLimitationResolutionChanges:R.qualityLimitationResolutionChanges,totalEncodeTime:R.totalEncodeTime,totalPacketSendDelay:R.totalEncodeTime,retransmittedBytesSent:R.retransmittedBytesSent,retransmittedPacketsSent:R.retransmittedPacketsSent,scalabilityMode:R.scalabilityMode,powerEfficientEncoder:R.powerEfficientEncoder,...V};d.outboundVideoRtp.set(I.id,Je),d.producerStreamMap.get(P).outboundVideoRtpId.push(I.id),this.processOutboundProducerVideoStats(P,Ce,Je)}else if(T.mediaType==="audio"||T.kind==="audio"){const R=T,Je={retransmittedBytesSent:R.retransmittedBytesSent,retransmittedPacketsSent:R.retransmittedPacketsSent,...V};d.outboundAudioRtp.set(I.id,Je),d.producerStreamMap.get(P).outboundAudioRtpId.push(I.id),this.processOutboundProducerAudioStats(P,Ce,Je)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(I.id))break;const T=I,P=n||this.inboundConsumerMap.get(I.id),$=this.pausedConsumerMap.get(P);if($){if($.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(T.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const Ce=this.overallConsumersStatsMap[P];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.inboundConsumerMap.has(I.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(P)||d.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const qe={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,R={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,...qe};R.score=Yp({frameWidth:R.frameWidth||0,framesDecoded:(R.framesDecoded||0)-(((b=this.videoConsumerToStatsMap.get(P))==null?void 0:b.framesDecoded)||0),framesPerSecond:R.framesPerSecond||0,packetsLost:(R.packetsLost||0)-(((C=this.videoConsumerToStatsMap.get(P))==null?void 0:C.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((D=this.videoConsumerToStatsMap.get(P))==null?void 0:D.packetsReceived)||0),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),y.set(P,{score:+(R.score*10).toFixed(),frameWidth:R.frameWidth||0,frameHeight:R.frameHeight||0,framesPerSecond:R.framesPerSecond||0,packetsLostPercentage:cd({packetsLost:(R.packetsLost||0)-(((F=this.videoConsumerToStatsMap.get(P))==null?void 0:F.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((L=this.videoConsumerToStatsMap.get(P))==null?void 0:L.packetsReceived)||0)}),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((R.bytesReceived||0)-(((B=this.videoConsumerToStatsMap.get(P))==null?void 0:B.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,R),d.inboundVideoRtp.set(I.id,R),d.consumerStreamMap.get(P).inboundVideoRtpId.push(I.id),this.processInboundConsumerVideoStats(P,Ce,R)}else if(T.mediaType==="audio"||T.kind==="audio"){const V=T,R={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,...qe};R.score=zp({concealmentEvents:(R.concealmentEvents||0)-(((Q=this.audioConsumerToStatsMap.get(P))==null?void 0:Q.concealmentEvents)||0),packetsLost:(R.packetsLost||0)-(((se=this.audioConsumerToStatsMap.get(P))==null?void 0:se.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((nt=this.audioConsumerToStatsMap.get(P))==null?void 0:nt.packetsReceived)||0),jitter:R.jitter||0}),y.set(P,{score:+(R.score*10).toFixed(),packetsLostPercentage:cd({packetsLost:(R.packetsLost||0)-(((Vs=this.audioConsumerToStatsMap.get(P))==null?void 0:Vs.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((_n=this.audioConsumerToStatsMap.get(P))==null?void 0:_n.packetsReceived)||0)}),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((R.bytesReceived||0)-(((Ls=this.audioConsumerToStatsMap.get(P))==null?void 0:Ls.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,R),d.inboundAudioRtp.set(I.id,R),d.consumerStreamMap.get(P).inboundAudioRtpId.push(I.id),this.processInboundConsumerAudioStats(P,Ce,R)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}}}if(d.producerStreamMap.forEach((I,T)=>{var P,$,Ce,qe,V,R,Je,Dr,xc,Uc,Fc,$c,Bc,Hc,qc,jc,Gc,Wc,Jc,Kc,zc,Yc,Qc;if(I.outboundVideoRtpId.length>0){const he=[];I.outboundVideoRtpId.forEach(Zh=>{he.push(d.outboundVideoRtp.get(Zh))});const ee=this.getWorkingSimulcastVideoStats(he);ee.score=Jp({frameWidth:ee.frameWidth||0,framesPerSecond:ee.framesPerSecond||0,jitter:((P=ee.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsSent:(ee.packetsSent||0)-((($=this.videoProducerToStatsMap.get(T))==null?void 0:$.packetsSent)||0),packetsLost:(((Ce=ee.remoteData)==null?void 0:Ce.packetsLost)||0)-(((V=(qe=this.videoProducerToStatsMap.get(T))==null?void 0:qe.remoteData)==null?void 0:V.packetsLost)||0),framesEncoded:(ee.framesEncoded||0)-(((R=this.videoProducerToStatsMap.get(T))==null?void 0:R.framesEncoded)||0)}),S.set(T,{score:+(ee.score*10).toFixed(),frameWidth:ee.frameWidth||0,frameHeight:ee.frameHeight||0,framesPerSecond:ee.framesPerSecond||0,jitter:((Je=ee.remoteData)==null?void 0:Je.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsLostPercentage:od({packetsSent:(ee.packetsSent||0)-(((Dr=this.videoProducerToStatsMap.get(T))==null?void 0:Dr.packetsSent)||0),packetsLost:(((xc=ee.remoteData)==null?void 0:xc.packetsLost)||0)-(((Fc=(Uc=this.videoProducerToStatsMap.get(T))==null?void 0:Uc.remoteData)==null?void 0:Fc.packetsLost)||0)}),bitrate:((ee.bytesSent||0)-((($c=this.videoProducerToStatsMap.get(T))==null?void 0:$c.bytesSent)||0))*8/7,cpuLimitations:ee.qualityLimitationReason==="cpu",bandwidthLimitations:ee.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(T,ee)}else if(I.outboundAudioRtpId.length>0){const he=d.outboundAudioRtp.get(I.outboundAudioRtpId[0]);he.score=Wp({packetsSent:(he.packetsSent||0)-(((Bc=this.audioProducerToStatsMap.get(T))==null?void 0:Bc.packetsSent)||0),packetsLost:(((Hc=he.remoteData)==null?void 0:Hc.packetsLost)||0)-(((jc=(qc=this.audioProducerToStatsMap.get(T))==null?void 0:qc.remoteData)==null?void 0:jc.packetsLost)||0),jitter:((Gc=he.remoteData)==null?void 0:Gc.jitter)||0}),S.set(T,{score:+(he.score*10).toFixed(),bitrate:((he.bytesSent||0)-(((Wc=this.audioProducerToStatsMap.get(T))==null?void 0:Wc.bytesSent)||0))*8/7,packetsLostPercentage:od({packetsSent:(he.packetsSent||0)-(((Jc=this.audioProducerToStatsMap.get(T))==null?void 0:Jc.packetsSent)||0),packetsLost:(((Kc=he.remoteData)==null?void 0:Kc.packetsLost)||0)-(((Yc=(zc=this.audioProducerToStatsMap.get(T))==null?void 0:zc.remoteData)==null?void 0:Yc.packetsLost)||0)}),jitter:((Qc=he.remoteData)==null?void 0:Qc.jitter)||0,isScreenShare:this.screenShareProducers.has(T)}),this.audioProducerToStatsMap.set(T,he)}}),g.forEach(I=>{const T=u.find($=>$.id===I.localCandidateId?(I.localCandidateId=$.id,$):null),P=h.find($=>$.id===I.remoteCandidateId?(I.remoteCandidateId=$.id,$):null);T&&(I.localCandidateType=T.type,I.localCandidateAddress=Vr(T.address),I.localCandidatePort=T.port,I.localCandidateProtocol=T.protocol,I.localCandidateUrl=T.url,I.localCandidateNetworkType=T.networkType,I.localCandidateRelatedAddress=Vr(T.relatedAddress),I.localCandidateRelatedPort=T.relatedPort),P&&(I.remoteCandidateType=P.type,I.remoteCandidateAddress=Vr(P.address),I.remoteCandidatePort=P.port,I.remoteCandidateProtocol=P.protocol,I.remoteCandidateUrl=P.url)}),d.candidatePair&&(d.transport?(d.transport.bytesReceived=d.candidatePair.bytesReceived,d.transport.bytesSent=d.candidatePair.bytesSent,d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.availableIncomingBitrate=d.candidatePair.availableIncomingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:d.candidatePair.availableIncomingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=g),d.transport&&!d.transport.roundTripTime){let I=0,T=0;d.remoteInboundRtp.forEach((P,$)=>{P.roundTripTime&&P.roundTripTime>I&&(I=P.roundTripTime,T=P.totalRoundTripTime)}),d.transport.roundTripTime=I,d.transport.totalRoundTripTime=T}if(y.size>0)try{this.observer.emit("consumer_score",y)}catch(I){}if(S.size>0)try{this.observer.emit("producer_score",S)}catch(I){}return d}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((i,n)=>{const o=this.producerMap.get(n),c=o.track.getSettings(),d=i.outboundVideoRtpId.map(u=>{const h=e.outboundVideoRtp.get(u);return h.frameHeight||(h.frameHeight=c.height,h.frameWidth=c.width,h.framesPerSecond=c.frameRate),h}),l={producerId:n,appData:o.appData,videoStats:d,audioStats:i.outboundAudioRtpId.map(u=>e.outboundAudioRtp.get(u))};r.push(l)})}catch(i){console.error("getProducersReport: ",i,e)}return r}getConsumerStatsFromParsedConsumerStats(e,r,i){let n;try{const{peerId:o,producerId:c,appData:d}=this.consumerPeerIdMap.get(i),l=r==null?void 0:r.inboundVideoRtpId.map(u=>{const g=this.consumerMap.get(i).track.getSettings(),S=e.inboundVideoRtp.get(u);return S.frameHeight||(S.frameHeight=g.height,S.frameWidth=g.width,S.framesPerSecond=g.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 wT extends rg{}function hd(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 ig(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=>{hd(this,t,e,o)}):n}catch(n){hd(this,t,e,n)}return null},s}const Y=(s,t)=>(e,r,i)=>{const n=i.value;return i.value=function(...o){try{const c=n.apply(this,o);return c&&c instanceof Promise?c.catch(d=>{hd(this,s,t,d)}):c}catch(c){hd(this,s,t,c)}return null},i},PT=(s,t)=>(e,r,i)=>{if(i)return ig(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,ig(o,s,t))}};var K=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 z=console;let W=class extends lt{constructor(e="https://api.testingv3.dyte.in",r="Blink",i=Za.PROD,n,o,c,d){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",{});switch(this.env=i,this.apiHostnames=d,this.logger=o,this.peerId=c,this.eventHandler=new cT({logger:o,peerId:c,apiHostnames:d}),this.logger.debug("callStats::engineName: ",{engineName:r}),r){case"Blink":this.measurements=new bT;break;case"Gecko":this.measurements=new rg;break;case"WebKit":this.measurements=new wT;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 lt,this.measurements.observer.on("consumer_score",l=>{o.debug(`callStats::consumer_score ${[...l.entries()]}`),this.eventHandler.emit("consumer_score",l)}),this.measurements.observer.on("producer_score",l=>{o.debug(`callStats::producer_score ${[...l.entries()]}`),this.eventHandler.emit("producer_score",l)})}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:N.PRECALL_TEST_BEGIN,timestamp:r}),this.connectionInfoPromise&&this.connectionInfoPromise.then(i=>{this.eventHandler.callEvent({event:N.PRECALL_TEST_COMPLETE,metaData:{connectionInfo:i},timestamp:r})})}sendScreenShareToggleEvent(e,r=null,i){this.currentUserMediaStates.screen=e,this.eventHandler.callEvent({event:e?N.SCREENSHARE_STARTED:N.SCREENSHARE_STOPPED,metaData:{ssrc:r},timestamp:i})}sendScreenShareRequestedEvent(e){this.eventHandler.callEvent({event:N.SCREENSHARE_START_REQUESTED,timestamp:e})}sendActiveSpeakerEvent(e,r){this.eventHandler.callEvent({event:N.DOMINANT_SPEAKER,metaData:{peerId:e},timestamp:r})}devices(e,r,i){this.eventHandler.callEvent({event:e===ts.AUDIO&&N.AUDIO_DEVICES_UPDATES||e===ts.VIDEO&&N.VIDEO_DEVICES_UPDATES||e===ts.SPEAKER&&N.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:r},timestamp:i})}selectedDevice(e,r,i){this.eventHandler.callEvent({event:e===ts.AUDIO&&N.SELECTED_MICROHPONE_UPDATE||e===ts.VIDEO&&N.SELECTED_CAMERA_UPDATE||e===ts.SPEAKER&&N.SELECTED_SPEAKER_UPDATE,metaData:{device:r},timestamp:i})}mediaPermission(e,r,i){this.eventHandler.callEvent({event:N.MEDIA_PERMISSION,metaData:{deviceType:e,permission:r},timestamp:i})}mediaPlaybackFailed(e,r){this.eventHandler.callEvent({event:e===ts.AUDIO&&N.AUDIO_PLAY_FAILED||e===ts.VIDEO&&N.VIDEO_PLAY_FAILED,metaData:{deviceType:e},timestamp:r})}mediaTrackMuted(e,r){this.eventHandler.callEvent({event:e===ts.AUDIO&&N.AUDIO_TRACK_MUTED||e===ts.VIDEO&&N.VIDEO_TRACK_MUTED,metaData:{deviceType:e},timestamp:r})}tabChanged(e,r){this.eventHandler.callEvent({event:N.TAB_CHANGE,metaData:{isMeetingsTabActive:e},timestamp:r})}browserBackgrounded(e){this.eventHandler.callEvent({event:N.BROWSER_BACKGROUNDED,timestamp:e})}browserForegrounded(e){this.eventHandler.callEvent({event:N.BROWSER_FOREGROUNDED,timestamp:e})}legacySwitch(e,r){this.eventHandler.callEvent({event:N.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:N.CALL_JOIN_BEGIN,metaData:{peerMetaData:e},timestamp:r})}sendNetworkQualityTestBeginEvent(e,r){this.eventHandler.callEvent({event:N.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:N.NET_QUALITY_TEST_END,timestamp:r,metaData:n})})}sendWebSocketConnectedEvent(e){this.eventHandler.callEvent({event:N.WEBSOCKET_CONNECTED,timestamp:e})}sendTransportConnectedEvent(e){this.eventHandler.callEvent({event:N.TRANSPORT_CONNECTED,timestamp:e})}sendAudioToggleEvent(e,r){this.currentUserMediaStates.audio=e;let i;e?i=N.AUDIO_ON:i=N.AUDIO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendVideoToggleEvent(e,r){this.currentUserMediaStates.video=e;let i;e?i=N.VIDEO_ON:i=N.VIDEO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendParticipantRoleToggleEvent(e,r){this.eventHandler.callEvent({event:N.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:N.PING_STAT,metaData:o,timestamp:r})}sendIVSPlayerRebufferEvent(e){this.eventHandler.callEvent({event:N.IVS_PLAYER_REBUFFERING,timestamp:e})}sendIVSPlayerAudioBlockEvent(e){this.eventHandler.callEvent({event:N.IVS_PLAYER_AUDIO_BLOCKED,timestamp:e})}sendIVSPlayerPlaybackBlockedEvent(e){this.eventHandler.callEvent({event:N.IVS_PLAYER_PLAYBACK_BLOCKED,timestamp:e})}sendIVSPlayerNetworkUnavailableEvent(e){this.eventHandler.callEvent({event:N.IVS_PLAYER_NETWORK_UNAVAILABLE,timestamp:e})}sendIVSPlayerInitializedEvent(e){this.eventHandler.callEvent({event:N.IVS_PLAYER_INITIALIZED,timestamp:e})}sendIVSPlayerWorkerErrorEvent(e){this.eventHandler.callEvent({event:N.IVS_PLAYER_WORKER_ERROR,timestamp:e})}sendIVSPlayerErrorEvent(e,r){this.eventHandler.callEvent({event:N.IVS_PLAYER_ERROR,timestamp:r,metaData:e})}sendIVSPlayerRecoverableErrorEvent(e,r){this.eventHandler.callEvent({event:N.IVS_PLAYER_RECOVERABLE_ERROR,timestamp:r,metaData:e})}sendIVSPlayerAnalyticsEvent(e,r){this.eventHandler.callEvent({event:N.IVS_PLAYER_ANALYTICS_EVENT,timestamp:r,metaData:e})}sendIVSPlayerPlaybackRateChangedEvent(e,r){this.eventHandler.callEvent({event:N.IVS_PLAYER_PLAYBACK_RATE_CHANGED,timestamp:r,metaData:{updatedPlaybackRate:e}})}sendIVSPlayerQualityChanged(e,r){this.eventHandler.callEvent({event:N.IVS_PLAYER_QUALITY_CHANGED,timestamp:r,metaData:e})}sendPlayerLiveLatency(e,r){this.eventHandler.callEvent({event:N.LIVESTREAM_LATENCY,timestamp:r,metaData:{latency:e}})}sendDisconnectEvent(e){this.eventHandler.callEvent({event:N.DISCONNECT,timestamp:e})}sendReconnectEvent(e){this.eventHandler.callEvent({event:N.RECONNECT_ATTEMPT,timestamp:e})}expectedVideoResolution(e,r,i){this.eventHandler.callEvent({event:N.EXPECTED_VIDEO_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}expectedScreenshareResolution(e,r,i){this.eventHandler.callEvent({event:N.EXPECTED_SCREENSHARE_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}};K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"registerIceServers",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"registerConsumer",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"registerProducer",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendConsumerSharedMediaStateEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"registerProducingTransport",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"registerConsumingTransport",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"deRegisterConsumer",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"deRegisterProducer",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"disconnectConsumingTransport",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"disconnectProducingTransport",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendPreCallTestBeginEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendScreenShareToggleEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendScreenShareRequestedEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendActiveSpeakerEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"devices",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"selectedDevice",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"mediaPermission",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"mediaPlaybackFailed",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"mediaTrackMuted",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"tabChanged",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"browserBackgrounded",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"browserForegrounded",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"legacySwitch",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"getPreCallTestResults",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendCallJoinBeginEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendNetworkQualityTestBeginEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendWebSocketConnectedEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendTransportConnectedEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendAudioToggleEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendVideoToggleEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendParticipantRoleToggleEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"startPingStats",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"stopPingStats",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendPingStatsEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerRebufferEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerAudioBlockEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerPlaybackBlockedEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerNetworkUnavailableEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerInitializedEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerWorkerErrorEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerErrorEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerRecoverableErrorEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerAnalyticsEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerQualityChanged",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendPlayerLiveLatency",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendDisconnectEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendReconnectEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"expectedVideoResolution",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"expectedScreenshareResolution",null),W=K([PT(TypeError,(s,t)=>z.error(t,s))],W);const _T=W;class ng extends lt{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=Za.PROD,iceServers:n,apiBase:o="https://api.cluster.dyte.in",flags:c,logger:d=console,apiHostnames:l,skipConnectivityChecks:u=!1}){var h,g,S;try{this.peerId=e,this.logger=d,this.ipInformation=await Xp.getIPDetails({peerId:e,apiHostnames:l,logger:d}),this.backend=new _T(o,r,i,c,d,e,l),this.iceServers=n,(h=this.backend)==null||h.registerIceServers(this.iceServers),this.initialized=!0,(S=(g=this.backend)==null?void 0:g.eventHandler)==null||S.emit("initialized",this.ipInformation),this.emit("initialized",this.ipInformation),this.startPreCallTest(u)}catch(y){this.logger.error("callStats::CallStatsIntegration: ",{error:y}),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,g,S,y,w;switch(e){case"PlayerRebuffering":(n=this.backend)==null||n.sendIVSPlayerRebufferEvent(i);break;case"PlayerAudioBlocked":(o=this.backend)==null||o.sendIVSPlayerAudioBlockEvent(i);break;case"PlayerPlaybackBlocked":(c=this.backend)==null||c.sendIVSPlayerPlaybackBlockedEvent(i);break;case"PlayerNetworkUnavailable":(d=this.backend)==null||d.sendIVSPlayerNetworkUnavailableEvent(i);break;case"PlayerInitialized":(l=this.backend)==null||l.sendIVSPlayerInitializedEvent(i);break;case"PlayerWorkerError":(u=this.backend)==null||u.sendIVSPlayerWorkerErrorEvent(i);break;case"PlayerError":(h=this.backend)==null||h.sendIVSPlayerErrorEvent(r,i);break;case"PlayerRecoverableError":(g=this.backend)==null||g.sendIVSPlayerRecoverableErrorEvent(r,i);break;case"PlayerAnalyticsEvent":(S=this.backend)==null||S.sendIVSPlayerAnalyticsEvent(r,i);break;case"PlayerPlaybackRateChanged":(y=this.backend)==null||y.sendIVSPlayerPlaybackRateChangedEvent(r,i);break;case"PlayerQualityChanged":(w=this.backend)==null||w.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 ng().setMaxListeners(30);function RT(){this.__data__=[],this.size=0}function eo(s,t){return s===t||s!==s&&t!==t}function pd(s,t){for(var e=s.length;e--;)if(eo(s[e][0],t))return e;return-1}var CT=Array.prototype,kT=CT.splice;function IT(s){var t=this.__data__,e=pd(t,s);if(e<0)return!1;var r=t.length-1;return e==r?t.pop():kT.call(t,e,1),--this.size,!0}function AT(s){var t=this.__data__,e=pd(t,s);return e<0?void 0:t[e][1]}function MT(s){return pd(this.__data__,s)>-1}function OT(s,t){var e=this.__data__,r=pd(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=RT,Zs.prototype.delete=IT,Zs.prototype.get=AT,Zs.prototype.has=MT,Zs.prototype.set=OT;function DT(){this.__data__=new Zs,this.size=0}function NT(s){var t=this.__data__,e=t.delete(s);return this.size=t.size,e}function VT(s){return this.__data__.get(s)}function LT(s){return this.__data__.has(s)}var xT=typeof global=="object"&&global&&global.Object===Object&&global;const ag=xT;var UT=typeof self=="object"&&self&&self.Object===Object&&self,FT=ag||UT||Function("return this")();const fs=FT;var $T=fs.Symbol;const Us=$T;var og=Object.prototype,BT=og.hasOwnProperty,HT=og.toString,to=Us?Us.toStringTag:void 0;function qT(s){var t=BT.call(s,to),e=s[to];try{s[to]=void 0;var r=!0}catch(n){}var i=HT.call(s);return r&&(t?s[to]=e:delete s[to]),i}var jT=Object.prototype,GT=jT.toString;function WT(s){return GT.call(s)}var JT="[object Null]",KT="[object Undefined]",cg=Us?Us.toStringTag:void 0;function Si(s){return s==null?s===void 0?KT:JT:cg&&cg in Object(s)?qT(s):WT(s)}function ss(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var zT="[object AsyncFunction]",YT="[object Function]",QT="[object GeneratorFunction]",XT="[object Proxy]";function bu(s){if(!ss(s))return!1;var t=Si(s);return t==YT||t==QT||t==zT||t==XT}var ZT=fs["__core-js_shared__"];const wu=ZT;var dg=function(){var s=/[^.]+$/.exec(wu&&wu.keys&&wu.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function ey(s){return!!dg&&dg in s}var ty=Function.prototype,sy=ty.toString;function vi(s){if(s!=null){try{return sy.call(s)}catch(t){}try{return s+""}catch(t){}}return""}var ry=/[\\^$.*+?()[\]{}|]/g,iy=/^\[object .+?Constructor\]$/,ny=Function.prototype,ay=Object.prototype,oy=ny.toString,cy=ay.hasOwnProperty,dy=RegExp("^"+oy.call(cy).replace(ry,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ly(s){if(!ss(s)||ey(s))return!1;var t=bu(s)?dy:iy;return t.test(vi(s))}function uy(s,t){return s==null?void 0:s[t]}function Ti(s,t){var e=uy(s,t);return ly(e)?e:void 0}var hy=Ti(fs,"Map");const so=hy;var py=Ti(Object,"create");const ro=py;function gy(){this.__data__=ro?ro(null):{},this.size=0}function my(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var fy="__lodash_hash_undefined__",Sy=Object.prototype,vy=Sy.hasOwnProperty;function Ty(s){var t=this.__data__;if(ro){var e=t[s];return e===fy?void 0:e}return vy.call(t,s)?t[s]:void 0}var yy=Object.prototype,Ey=yy.hasOwnProperty;function by(s){var t=this.__data__;return ro?t[s]!==void 0:Ey.call(t,s)}var wy="__lodash_hash_undefined__";function Py(s,t){var e=this.__data__;return this.size+=this.has(s)?0:1,e[s]=ro&&t===void 0?wy:t,this}function yi(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])}}yi.prototype.clear=gy,yi.prototype.delete=my,yi.prototype.get=Ty,yi.prototype.has=by,yi.prototype.set=Py;function _y(){this.size=0,this.__data__={hash:new yi,map:new(so||Zs),string:new yi}}function Ry(s){var t=typeof s;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?s!=="__proto__":s===null}function gd(s,t){var e=s.__data__;return Ry(t)?e[typeof t=="string"?"string":"hash"]:e.map}function Cy(s){var t=gd(this,s).delete(s);return this.size-=t?1:0,t}function ky(s){return gd(this,s).get(s)}function Iy(s){return gd(this,s).has(s)}function Ay(s,t){var e=gd(this,s),r=e.size;return e.set(s,t),this.size+=e.size==r?0:1,this}function er(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])}}er.prototype.clear=_y,er.prototype.delete=Cy,er.prototype.get=ky,er.prototype.has=Iy,er.prototype.set=Ay;var My=200;function Oy(s,t){var e=this.__data__;if(e instanceof Zs){var r=e.__data__;if(!so||r.length<My-1)return r.push([s,t]),this.size=++e.size,this;e=this.__data__=new er(r)}return e.set(s,t),this.size=e.size,this}function Ss(s){var t=this.__data__=new Zs(s);this.size=t.size}Ss.prototype.clear=DT,Ss.prototype.delete=NT,Ss.prototype.get=VT,Ss.prototype.has=LT,Ss.prototype.set=Oy;function Dy(s,t){for(var e=-1,r=s==null?0:s.length;++e<r&&t(s[e],e,s)!==!1;);return s}var Ny=function(){try{var s=Ti(Object,"defineProperty");return s({},"",{}),s}catch(t){}}();const md=Ny;function Pu(s,t,e){t=="__proto__"&&md?md(s,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):s[t]=e}var Vy=Object.prototype,Ly=Vy.hasOwnProperty;function lg(s,t,e){var r=s[t];(!(Ly.call(s,t)&&eo(r,e))||e===void 0&&!(t in s))&&Pu(s,t,e)}function io(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?Pu(e,c,d):lg(e,c,d)}return e}function xy(s,t){for(var e=-1,r=Array(s);++e<s;)r[e]=t(e);return r}function Fs(s){return s!=null&&typeof s=="object"}var Uy="[object Arguments]";function ug(s){return Fs(s)&&Si(s)==Uy}var hg=Object.prototype,Fy=hg.hasOwnProperty,$y=hg.propertyIsEnumerable,By=ug(function(){return arguments}())?ug:function(s){return Fs(s)&&Fy.call(s,"callee")&&!$y.call(s,"callee")};const no=By;var Hy=Array.isArray;const Ft=Hy;function qy(){return!1}var pg=typeof exports=="object"&&exports&&!exports.nodeType&&exports,gg=pg&&typeof module=="object"&&module&&!module.nodeType&&module,jy=gg&&gg.exports===pg,mg=jy?fs.Buffer:void 0,Gy=mg?mg.isBuffer:void 0,Wy=Gy||qy;const kn=Wy;var Jy=9007199254740991,Ky=/^(?:0|[1-9]\d*)$/;function _u(s,t){var e=typeof s;return t=t==null?Jy:t,!!t&&(e=="number"||e!="symbol"&&Ky.test(s))&&s>-1&&s%1==0&&s<t}var zy=9007199254740991;function Ru(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=zy}var Yy="[object Arguments]",Qy="[object Array]",Xy="[object Boolean]",Zy="[object Date]",eE="[object Error]",tE="[object Function]",sE="[object Map]",rE="[object Number]",iE="[object Object]",nE="[object RegExp]",aE="[object Set]",oE="[object String]",cE="[object WeakMap]",dE="[object ArrayBuffer]",lE="[object DataView]",uE="[object Float32Array]",hE="[object Float64Array]",pE="[object Int8Array]",gE="[object Int16Array]",mE="[object Int32Array]",fE="[object Uint8Array]",SE="[object Uint8ClampedArray]",vE="[object Uint16Array]",TE="[object Uint32Array]",ve={};ve[uE]=ve[hE]=ve[pE]=ve[gE]=ve[mE]=ve[fE]=ve[SE]=ve[vE]=ve[TE]=!0,ve[Yy]=ve[Qy]=ve[dE]=ve[Xy]=ve[lE]=ve[Zy]=ve[eE]=ve[tE]=ve[sE]=ve[rE]=ve[iE]=ve[nE]=ve[aE]=ve[oE]=ve[cE]=!1;function yE(s){return Fs(s)&&Ru(s.length)&&!!ve[Si(s)]}function Cu(s){return function(t){return s(t)}}var fg=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ao=fg&&typeof module=="object"&&module&&!module.nodeType&&module,EE=ao&&ao.exports===fg,ku=EE&&ag.process,bE=function(){try{var s=ao&&ao.require&&ao.require("util").types;return s||ku&&ku.binding&&ku.binding("util")}catch(t){}}();const In=bE;var Sg=In&&In.isTypedArray,wE=Sg?Cu(Sg):yE;const fd=wE;var PE=Object.prototype,_E=PE.hasOwnProperty;function vg(s,t){var e=Ft(s),r=!e&&no(s),i=!e&&!r&&kn(s),n=!e&&!r&&!i&&fd(s),o=e||r||i||n,c=o?xy(s.length,String):[],d=c.length;for(var l in s)(t||_E.call(s,l))&&!(o&&(l=="length"||i&&(l=="offset"||l=="parent")||n&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||_u(l,d)))&&c.push(l);return c}var RE=Object.prototype;function Sd(s){var t=s&&s.constructor,e=typeof t=="function"&&t.prototype||RE;return s===e}function Tg(s,t){return function(e){return s(t(e))}}var CE=Tg(Object.keys,Object);const kE=CE;var IE=Object.prototype,AE=IE.hasOwnProperty;function yg(s){if(!Sd(s))return kE(s);var t=[];for(var e in Object(s))AE.call(s,e)&&e!="constructor"&&t.push(e);return t}function oo(s){return s!=null&&Ru(s.length)&&!bu(s)}function vd(s){return oo(s)?vg(s):yg(s)}function ME(s,t){return s&&io(t,vd(t),s)}function OE(s){var t=[];if(s!=null)for(var e in Object(s))t.push(e);return t}var DE=Object.prototype,NE=DE.hasOwnProperty;function VE(s){if(!ss(s))return OE(s);var t=Sd(s),e=[];for(var r in s)r=="constructor"&&(t||!NE.call(s,r))||e.push(r);return e}function co(s){return oo(s)?vg(s,!0):VE(s)}function LE(s,t){return s&&io(t,co(t),s)}var Eg=typeof exports=="object"&&exports&&!exports.nodeType&&exports,bg=Eg&&typeof module=="object"&&module&&!module.nodeType&&module,xE=bg&&bg.exports===Eg,wg=xE?fs.Buffer:void 0,Pg=wg?wg.allocUnsafe:void 0;function _g(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 Rg(s,t){var e=-1,r=s.length;for(t||(t=Array(r));++e<r;)t[e]=s[e];return t}function UE(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 Cg(){return[]}var FE=Object.prototype,$E=FE.propertyIsEnumerable,kg=Object.getOwnPropertySymbols,BE=kg?function(s){return s==null?[]:(s=Object(s),UE(kg(s),function(t){return $E.call(s,t)}))}:Cg;const Iu=BE;function HE(s,t){return io(s,Iu(s),t)}function Ig(s,t){for(var e=-1,r=t.length,i=s.length;++e<r;)s[i+e]=t[e];return s}var qE=Tg(Object.getPrototypeOf,Object);const Au=qE;var jE=Object.getOwnPropertySymbols,GE=jE?function(s){for(var t=[];s;)Ig(t,Iu(s)),s=Au(s);return t}:Cg;const Ag=GE;function WE(s,t){return io(s,Ag(s),t)}function Mg(s,t,e){var r=t(s);return Ft(s)?r:Ig(r,e(s))}function Mu(s){return Mg(s,vd,Iu)}function JE(s){return Mg(s,co,Ag)}var KE=Ti(fs,"DataView");const Ou=KE;var zE=Ti(fs,"Promise");const Du=zE;var YE=Ti(fs,"Set");const An=YE;var QE=Ti(fs,"WeakMap");const Nu=QE;var Og="[object Map]",XE="[object Object]",Dg="[object Promise]",Ng="[object Set]",Vg="[object WeakMap]",Lg="[object DataView]",ZE=vi(Ou),eb=vi(so),tb=vi(Du),sb=vi(An),rb=vi(Nu),Ei=Si;(Ou&&Ei(new Ou(new ArrayBuffer(1)))!=Lg||so&&Ei(new so)!=Og||Du&&Ei(Du.resolve())!=Dg||An&&Ei(new An)!=Ng||Nu&&Ei(new Nu)!=Vg)&&(Ei=function(s){var t=Si(s),e=t==XE?s.constructor:void 0,r=e?vi(e):"";if(r)switch(r){case ZE:return Lg;case eb:return Og;case tb:return Dg;case sb:return Ng;case rb:return Vg}return t});const Mn=Ei;var ib=Object.prototype,nb=ib.hasOwnProperty;function ab(s){var t=s.length,e=new s.constructor(t);return t&&typeof s[0]=="string"&&nb.call(s,"index")&&(e.index=s.index,e.input=s.input),e}var ob=fs.Uint8Array;const Td=ob;function Vu(s){var t=new s.constructor(s.byteLength);return new Td(t).set(new Td(s)),t}function cb(s,t){var e=t?Vu(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.byteLength)}var db=/\w*$/;function lb(s){var t=new s.constructor(s.source,db.exec(s));return t.lastIndex=s.lastIndex,t}var xg=Us?Us.prototype:void 0,Ug=xg?xg.valueOf:void 0;function ub(s){return Ug?Object(Ug.call(s)):{}}function Fg(s,t){var e=t?Vu(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.length)}var hb="[object Boolean]",pb="[object Date]",gb="[object Map]",mb="[object Number]",fb="[object RegExp]",Sb="[object Set]",vb="[object String]",Tb="[object Symbol]",yb="[object ArrayBuffer]",Eb="[object DataView]",bb="[object Float32Array]",wb="[object Float64Array]",Pb="[object Int8Array]",_b="[object Int16Array]",Rb="[object Int32Array]",Cb="[object Uint8Array]",kb="[object Uint8ClampedArray]",Ib="[object Uint16Array]",Ab="[object Uint32Array]";function Mb(s,t,e){var r=s.constructor;switch(t){case yb:return Vu(s);case hb:case pb:return new r(+s);case Eb:return cb(s,e);case bb:case wb:case Pb:case _b:case Rb:case Cb:case kb:case Ib:case Ab:return Fg(s,e);case gb:return new r;case mb:case vb:return new r(s);case fb:return lb(s);case Sb:return new r;case Tb:return ub(s)}}var $g=Object.create,Ob=function(){function s(){}return function(t){if(!ss(t))return{};if($g)return $g(t);s.prototype=t;var e=new s;return s.prototype=void 0,e}}();const Db=Ob;function Bg(s){return typeof s.constructor=="function"&&!Sd(s)?Db(Au(s)):{}}var Nb="[object Map]";function Vb(s){return Fs(s)&&Mn(s)==Nb}var Hg=In&&In.isMap,Lb=Hg?Cu(Hg):Vb;const xb=Lb;var Ub="[object Set]";function Fb(s){return Fs(s)&&Mn(s)==Ub}var qg=In&&In.isSet,$b=qg?Cu(qg):Fb;const Bb=$b;var Hb=1,qb=2,jb=4,jg="[object Arguments]",Gb="[object Array]",Wb="[object Boolean]",Jb="[object Date]",Kb="[object Error]",Gg="[object Function]",zb="[object GeneratorFunction]",Yb="[object Map]",Qb="[object Number]",Wg="[object Object]",Xb="[object RegExp]",Zb="[object Set]",ew="[object String]",tw="[object Symbol]",sw="[object WeakMap]",rw="[object ArrayBuffer]",iw="[object DataView]",nw="[object Float32Array]",aw="[object Float64Array]",ow="[object Int8Array]",cw="[object Int16Array]",dw="[object Int32Array]",lw="[object Uint8Array]",uw="[object Uint8ClampedArray]",hw="[object Uint16Array]",pw="[object Uint32Array]",pe={};pe[jg]=pe[Gb]=pe[rw]=pe[iw]=pe[Wb]=pe[Jb]=pe[nw]=pe[aw]=pe[ow]=pe[cw]=pe[dw]=pe[Yb]=pe[Qb]=pe[Wg]=pe[Xb]=pe[Zb]=pe[ew]=pe[tw]=pe[lw]=pe[uw]=pe[hw]=pe[pw]=!0,pe[Kb]=pe[Gg]=pe[sw]=!1;function lo(s,t,e,r,i,n){var o,c=t&Hb,d=t&qb,l=t&jb;if(e&&(o=i?e(s,r,i,n):e(s)),o!==void 0)return o;if(!ss(s))return s;var u=Ft(s);if(u){if(o=ab(s),!c)return Rg(s,o)}else{var h=Mn(s),g=h==Gg||h==zb;if(kn(s))return _g(s,c);if(h==Wg||h==jg||g&&!i){if(o=d||g?{}:Bg(s),!c)return d?WE(s,LE(o,s)):HE(s,ME(o,s))}else{if(!pe[h])return i?s:{};o=Mb(s,h,c)}}n||(n=new Ss);var S=n.get(s);if(S)return S;n.set(s,o),Bb(s)?s.forEach(function(b){o.add(lo(b,t,e,b,s,n))}):xb(s)&&s.forEach(function(b,C){o.set(C,lo(b,t,e,C,s,n))});var y=l?d?JE:Mu:d?co:vd,w=u?void 0:y(s);return Dy(w||s,function(b,C){w&&(C=b,b=s[C]),lg(o,C,lo(b,t,e,C,s,n))}),o}var gw=1,mw=4;function Lu(s){return lo(s,gw|mw)}var fw="[object Symbol]";function yd(s){return typeof s=="symbol"||Fs(s)&&Si(s)==fw}var Sw=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,vw=/^\w*$/;function xu(s,t){if(Ft(s))return!1;var e=typeof s;return e=="number"||e=="symbol"||e=="boolean"||s==null||yd(s)?!0:vw.test(s)||!Sw.test(s)||t!=null&&s in Object(t)}var Tw="Expected a function";function Uu(s,t){if(typeof s!="function"||t!=null&&typeof t!="function")throw new TypeError(Tw);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(Uu.Cache||er),e}Uu.Cache=er;var yw=500;function Ew(s){var t=Uu(s,function(r){return e.size===yw&&e.clear(),r}),e=t.cache;return t}var bw=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ww=/\\(\\)?/g,Pw=Ew(function(s){var t=[];return s.charCodeAt(0)===46&&t.push(""),s.replace(bw,function(e,r,i,n){t.push(i?n.replace(ww,"$1"):r||e)}),t});const _w=Pw;function Rw(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 Cw=1/0,Jg=Us?Us.prototype:void 0,Kg=Jg?Jg.toString:void 0;function zg(s){if(typeof s=="string")return s;if(Ft(s))return Rw(s,zg)+"";if(yd(s))return Kg?Kg.call(s):"";var t=s+"";return t=="0"&&1/s==-Cw?"-0":t}function kw(s){return s==null?"":zg(s)}function Yg(s,t){return Ft(s)?s:xu(s,t)?[s]:_w(kw(s))}var Iw=1/0;function Ed(s){if(typeof s=="string"||yd(s))return s;var t=s+"";return t=="0"&&1/s==-Iw?"-0":t}function Qg(s,t){t=Yg(t,s);for(var e=0,r=t.length;s!=null&&e<r;)s=s[Ed(t[e++])];return e&&e==r?s:void 0}function Aw(s,t,e){var r=s==null?void 0:Qg(s,t);return r===void 0?e:r}function Mw(s,t,e){t=Yg(t,s);for(var r=-1,i=t.length,n=!1;++r<i;){var o=Ed(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&&Ru(i)&&_u(o,i)&&(Ft(s)||no(s)))}var tr=(s=>(s.GroupCall="GROUP_CALL",s.Webinar="WEBINAR",s.AudioRoom="AUDIO_ROOM",s.Livestream="LIVESTREAM",s.Chat="CHAT",s))(tr||{}),H=(s=>(s.Allowed="ALLOWED",s.NotAllowed="NOT_ALLOWED",s.CanRequest="CAN_REQUEST",s))(H||{}),Xg="hXgU8Wc8pwuGNq9ms5q9Hh";typeof process!="undefined"&&(NS=process==null?void 0:process.env)!=null&&NS.FLAGSMITH_ENVIRONMENT_KEY&&(Xg=process.env.FLAGSMITH_ENVIRONMENT_KEY);function Ow(s=[]){const t={};return s.forEach(e=>{t[e.feature.name]={enabled:e.enabled,value:e.feature_state_value}}),t}var Zg=class{constructor(s=Xg){p(this,"flags",{});p(this,"environmentKey",null);this.environmentKey=s}async identifyAndFetchFlagsWithRetry({primaryEndpoint:s,secondaryEndpoint:t,forceEvaluate:e,timeout:r,uniqueIdentifier:i,traitsObj:n,logger:o}){const c=JSON.parse(JSON.stringify(n)),d=Object.entries(c).map(u=>({trait_key:u[0],trait_value:u[1]})),l=[s,t,t];for(const u of l)try{const h=new AbortController,g=setTimeout(()=>h.abort(),r),S=`_${(Math.random()+1).toString(36).substring(2)}`,y=await fetch(`https://${u}/api/v1/identities/`,{method:"POST",headers:{"Content-Type":"application/json","X-Environment-Key":this.environmentKey},body:JSON.stringify({identifier:i+(e?S:""),traits:d}),signal:h.signal});if(clearTimeout(g),!y.ok)throw new Error(`Request failed with status ${y.status}`);const w=await y.json();return Ow(w.flags||[])}catch(h){o.error("Flagsmith identify failed!!",{error:h,url:u})}return{}}async identify(s,t={},e=!1,r=5e3,i="edge.api.flagsmith.com",n=console){return this.flags=await this.identifyAndFetchFlagsWithRetry({traitsObj:t,uniqueIdentifier:s,forceEvaluate:e,timeout:r,primaryEndpoint:i,secondaryEndpoint:"edge.api.flagsmith.com",logger:n}),this.flags}getValue(s){return this.flags&&this.flags[s]&&this.flags[s].value}hasFeature(s){return this.flags&&this.flags[s]&&this.flags[s].enabled}getAllFlags(){return this.flags}},Dw=new Zg;function Nw(s){return new Zg(s)}var em=[-2,-1,0,1,2],Vw=[0,1,2,3,4];function Lw(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 xw=(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)]},Uw=(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]},Fw=(s,t,e)=>{const r=i=>i.toString(16).padStart(2,"0");return`#${r(s)}${r(t)}${r(e)}`},tm=(s,t=em,e=.4)=>{const r=[],[i,n,o]=Lw(s),[c,d,l]=Uw(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(b=>b===0);if(h===-1)throw new Error("Invalid reducer provided, it must contain atleast one zero");const g=5-h,S=h+1,y=(100-u)/g,w=u/S;for(const b of t){let C;b<0?C=u+b*w*e:b>0?C=u+b*y*e:C=u;const[D,F,L]=xw(c,d,C/100);r.push(Fw(D,F,L))}return r},sm={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"}},$w=s=>{const[t,e,r,i,n]=tm(s,em);return{300:t,400:e,500:r,600:i,700:n}},Bw=s=>{if(s==="#FFFFFF")return sm.light.background;if(s==="#000000")return sm.dark.background;const[t,e,r,i,n]=tm(s,Vw);return{1e3:t,900:e,800:r,700:i,600:n}},Hw={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:$w("#2160FD"),background:Bw("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function rm(){return Lu(Hw)}var qw={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:rm(),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 jw(){return Lu(qw)}var Gw={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:rm(),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 Fu(){return Lu(Gw)}class Ww{constructor(){m(this,No,void 0)}get telemetry(){var t;return(t=a(this,No))==null?void 0:t.getValue("telemetry")}init(t){f(this,No,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)}}No=new WeakMap;class Jw extends lt.EventEmitter{constructor(e){super();m(this,pr,void 0);m(this,gr,void 0);p(this,"asyncPromiseTimeout");p(this,"logger");this.logger=e,f(this,pr,new Map),f(this,gr,new Map),this.asyncPromiseTimeout=8e3}async emitAsync(e,...r){a(this,pr).set(e,[]);const i=a(this,gr).get(e).map(()=>new Promise(n=>{a(this,pr).get(e).push(n)}));super.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,pr).delete(e)}onAsync(e,r){const i=a(this,pr),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,gr).get(e)||a(this,gr).set(e,[]),a(this,gr).get(e).push(n),super.on(e,n)}reset(){f(this,pr,new Map),f(this,gr,new Map),super.removeAllListeners()}}pr=new WeakMap,gr=new WeakMap;var Kw=/\s/;function zw(s){for(var t=s.length;t--&&Kw.test(s.charAt(t)););return t}var Yw=/^\s+/;function Qw(s){return s&&s.slice(0,zw(s)+1).replace(Yw,"")}var im=0/0,Xw=/^[-+]0x[0-9a-f]+$/i,Zw=/^0b[01]+$/i,eP=/^0o[0-7]+$/i,tP=parseInt;function nm(s){if(typeof s=="number")return s;if(yd(s))return im;if(ss(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=ss(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=Qw(s);var e=Zw.test(s);return e||eP.test(s)?tP(s.slice(2),e?2:8):Xw.test(s)?im:+s}function $u(s){return s}function sP(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 rP(){}var iP=800,nP=16,aP=Date.now;function oP(s){var t=0,e=0;return function(){var r=aP(),i=nP-(r-e);if(e=r,i>0){if(++t>=iP)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}function cP(s){return function(){return s}}var dP=md?function(s,t){return md(s,"toString",{configurable:!0,enumerable:!1,value:cP(t),writable:!0})}:$u,lP=oP(dP);const uP=lP;function hP(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 pP(s){return s!==s}function gP(s,t,e){for(var r=e-1,i=s.length;++r<i;)if(s[r]===t)return r;return-1}function mP(s,t,e){return t===t?gP(s,t,e):hP(s,pP,e)}function fP(s,t){var e=s==null?0:s.length;return!!e&&mP(s,t,0)>-1}var am=Math.max;function SP(s,t,e){return t=am(t===void 0?s.length-1:t,0),function(){for(var r=arguments,i=-1,n=am(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),sP(s,this,c)}}function vP(s,t){return uP(SP(s,t,$u),s+"")}function TP(s,t,e){if(!ss(e))return!1;var r=typeof t;return(r=="number"?oo(e)&&_u(t,e.length):r=="string"&&t in e)?eo(e[t],s):!1}function yP(s){return vP(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&&TP(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 EP="[object Object]",bP=Function.prototype,wP=Object.prototype,om=bP.toString,PP=wP.hasOwnProperty,_P=om.call(Object);function RP(s){if(!Fs(s)||Si(s)!=EP)return!1;var t=Au(s);if(t===null)return!0;var e=PP.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&om.call(e)==_P}var CP=4;function kP(s){return lo(s,CP)}var IP="__lodash_hash_undefined__";function AP(s){return this.__data__.set(s,IP),this}function MP(s){return this.__data__.has(s)}function uo(s){var t=-1,e=s==null?0:s.length;for(this.__data__=new er;++t<e;)this.add(s[t])}uo.prototype.add=uo.prototype.push=AP,uo.prototype.has=MP;function OP(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 cm(s,t){return s.has(t)}var DP=1,NP=2;function dm(s,t,e,r,i,n){var o=e&DP,c=s.length,d=t.length;if(c!=d&&!(o&&d>c))return!1;var l=n.get(s),u=n.get(t);if(l&&u)return l==t&&u==s;var h=-1,g=!0,S=e&NP?new uo:void 0;for(n.set(s,t),n.set(t,s);++h<c;){var y=s[h],w=t[h];if(r)var b=o?r(w,y,h,t,s,n):r(y,w,h,s,t,n);if(b!==void 0){if(b)continue;g=!1;break}if(S){if(!OP(t,function(C,D){if(!cm(S,D)&&(y===C||i(y,C,e,r,n)))return S.push(D)})){g=!1;break}}else if(!(y===w||i(y,w,e,r,n))){g=!1;break}}return n.delete(s),n.delete(t),g}function VP(s){var t=-1,e=Array(s.size);return s.forEach(function(r,i){e[++t]=[i,r]}),e}function Bu(s){var t=-1,e=Array(s.size);return s.forEach(function(r){e[++t]=r}),e}var LP=1,xP=2,UP="[object Boolean]",FP="[object Date]",$P="[object Error]",BP="[object Map]",HP="[object Number]",qP="[object RegExp]",jP="[object Set]",GP="[object String]",WP="[object Symbol]",JP="[object ArrayBuffer]",KP="[object DataView]",lm=Us?Us.prototype:void 0,Hu=lm?lm.valueOf:void 0;function zP(s,t,e,r,i,n,o){switch(e){case KP:if(s.byteLength!=t.byteLength||s.byteOffset!=t.byteOffset)return!1;s=s.buffer,t=t.buffer;case JP:return!(s.byteLength!=t.byteLength||!n(new Td(s),new Td(t)));case UP:case FP:case HP:return eo(+s,+t);case $P:return s.name==t.name&&s.message==t.message;case qP:case GP:return s==t+"";case BP:var c=VP;case jP:var d=r&LP;if(c||(c=Bu),s.size!=t.size&&!d)return!1;var l=o.get(s);if(l)return l==t;r|=xP,o.set(s,t);var u=dm(c(s),c(t),r,i,n,o);return o.delete(s),u;case WP:if(Hu)return Hu.call(s)==Hu.call(t)}return!1}var YP=1,QP=Object.prototype,XP=QP.hasOwnProperty;function ZP(s,t,e,r,i,n){var o=e&YP,c=Mu(s),d=c.length,l=Mu(t),u=l.length;if(d!=u&&!o)return!1;for(var h=d;h--;){var g=c[h];if(!(o?g in t:XP.call(t,g)))return!1}var S=n.get(s),y=n.get(t);if(S&&y)return S==t&&y==s;var w=!0;n.set(s,t),n.set(t,s);for(var b=o;++h<d;){g=c[h];var C=s[g],D=t[g];if(r)var F=o?r(D,C,g,t,s,n):r(C,D,g,s,t,n);if(!(F===void 0?C===D||i(C,D,e,r,n):F)){w=!1;break}b||(b=g=="constructor")}if(w&&!b){var L=s.constructor,B=t.constructor;L!=B&&"constructor"in s&&"constructor"in t&&!(typeof L=="function"&&L instanceof L&&typeof B=="function"&&B instanceof B)&&(w=!1)}return n.delete(s),n.delete(t),w}var e_=1,um="[object Arguments]",hm="[object Array]",bd="[object Object]",t_=Object.prototype,pm=t_.hasOwnProperty;function s_(s,t,e,r,i,n){var o=Ft(s),c=Ft(t),d=o?hm:Mn(s),l=c?hm:Mn(t);d=d==um?bd:d,l=l==um?bd:l;var u=d==bd,h=l==bd,g=d==l;if(g&&kn(s)){if(!kn(t))return!1;o=!0,u=!1}if(g&&!u)return n||(n=new Ss),o||fd(s)?dm(s,t,e,r,i,n):zP(s,t,d,e,r,i,n);if(!(e&e_)){var S=u&&pm.call(s,"__wrapped__"),y=h&&pm.call(t,"__wrapped__");if(S||y){var w=S?s.value():s,b=y?t.value():t;return n||(n=new Ss),i(w,b,e,r,n)}}return g?(n||(n=new Ss),ZP(s,t,e,r,i,n)):!1}function wd(s,t,e,r,i){return s===t?!0:s==null||t==null||!Fs(s)&&!Fs(t)?s!==s&&t!==t:s_(s,t,e,r,wd,i)}var r_=1,i_=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 Ss;if(r)var g=r(l,u,d,s,t,h);if(!(g===void 0?wd(u,l,r_|i_,r,h):g))return!1}}return!0}function gm(s){return s===s&&!ss(s)}function a_(s){for(var t=vd(s),e=t.length;e--;){var r=t[e],i=s[r];t[e]=[r,i,gm(i)]}return t}function mm(s,t){return function(e){return e==null?!1:e[s]===t&&(t!==void 0||s in Object(e))}}function o_(s){var t=a_(s);return t.length==1&&t[0][2]?mm(t[0][0],t[0][1]):function(e){return e===s||n_(e,s,t)}}function c_(s,t){return s!=null&&t in Object(s)}function d_(s,t){return s!=null&&Mw(s,t,c_)}var l_=1,u_=2;function h_(s,t){return xu(s)&&gm(t)?mm(Ed(s),t):function(e){var r=Aw(e,s);return r===void 0&&r===t?d_(e,s):wd(t,r,l_|u_)}}function p_(s){return function(t){return t==null?void 0:t[s]}}function g_(s){return function(t){return Qg(t,s)}}function m_(s){return xu(s)?p_(Ed(s)):g_(s)}function f_(s){return typeof s=="function"?s:s==null?$u:typeof s=="object"?Ft(s)?h_(s[0],s[1]):o_(s):m_(s)}function S_(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 v_=S_();const T_=v_;var y_=function(){return fs.Date.now()};const qu=y_;var E_="Expected a function",b_=Math.max,w_=Math.min;function ju(s,t,e){var r,i,n,o,c,d,l=0,u=!1,h=!1,g=!0;if(typeof s!="function")throw new TypeError(E_);t=nm(t)||0,ss(e)&&(u=!!e.leading,h="maxWait"in e,n=h?b_(nm(e.maxWait)||0,t):n,g="trailing"in e?!!e.trailing:g);function S(Q){var se=r,nt=i;return r=i=void 0,l=Q,o=s.apply(nt,se),o}function y(Q){return l=Q,c=setTimeout(C,t),u?S(Q):o}function w(Q){var se=Q-d,nt=Q-l,Vs=t-se;return h?w_(Vs,n-nt):Vs}function b(Q){var se=Q-d,nt=Q-l;return d===void 0||se>=t||se<0||h&&nt>=n}function C(){var Q=qu();if(b(Q))return D(Q);c=setTimeout(C,w(Q))}function D(Q){return c=void 0,g&&r?S(Q):(r=i=void 0,o)}function F(){c!==void 0&&clearTimeout(c),l=0,r=d=i=c=void 0}function L(){return c===void 0?o:D(qu())}function B(){var Q=qu(),se=b(Q);if(r=arguments,i=this,d=Q,se){if(c===void 0)return y(d);if(h)return clearTimeout(c),c=setTimeout(C,t),S(d)}return c===void 0&&(c=setTimeout(C,t)),o}return B.cancel=F,B.flush=L,B}function Gu(s,t,e){(e!==void 0&&!eo(s[t],e)||e===void 0&&!(t in s))&&Pu(s,t,e)}function P_(s){return Fs(s)&&oo(s)}function Wu(s,t){if(!(t==="constructor"&&typeof s[t]=="function")&&t!="__proto__")return s[t]}function __(s){return io(s,co(s))}function R_(s,t,e,r,i,n,o){var c=Wu(s,e),d=Wu(t,e),l=o.get(d);if(l){Gu(s,e,l);return}var u=n?n(c,d,e+"",s,t,o):void 0,h=u===void 0;if(h){var g=Ft(d),S=!g&&kn(d),y=!g&&!S&&fd(d);u=d,g||S||y?Ft(c)?u=c:P_(c)?u=Rg(c):S?(h=!1,u=_g(d,!0)):y?(h=!1,u=Fg(d,!0)):u=[]:RP(d)||no(d)?(u=c,no(c)?u=__(c):(!ss(c)||bu(c))&&(u=Bg(d))):h=!1}h&&(o.set(d,u),i(u,d,r,n,o),o.delete(d)),Gu(s,e,u)}function fm(s,t,e,r,i){s!==t&&T_(t,function(n,o){if(i||(i=new Ss),ss(n))R_(s,t,o,e,fm,r,i);else{var c=r?r(Wu(s,o),n,o+"",s,t,i):void 0;c===void 0&&(c=n),Gu(s,o,c)}},co)}function C_(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 k_="[object Map]",I_="[object Set]",A_=Object.prototype,M_=A_.hasOwnProperty;function O_(s){if(s==null)return!0;if(oo(s)&&(Ft(s)||typeof s=="string"||typeof s.splice=="function"||kn(s)||fd(s)||no(s)))return!s.length;var t=Mn(s);if(t==k_||t==I_)return!s.size;if(Sd(s))return!yg(s).length;for(var e in s)if(M_.call(s,e))return!1;return!0}function D_(s,t){return wd(s,t)}var N_=yP(function(s,t,e){fm(s,t,e)});const Lr=N_;var V_=1/0,L_=An&&1/Bu(new An([,-0]))[1]==V_?function(s){return new An(s)}:rP;const x_=L_;var U_=200;function Sm(s,t,e){var r=-1,i=fP,n=s.length,o=!0,c=[],d=c;if(e)o=!1,i=C_;else if(n>=U_){var l=t?null:x_(s);if(l)return Bu(l);o=!1,i=cm,d=new uo}else d=t?[]:c;e:for(;++r<n;){var u=s[r],h=t?t(u):u;if(u=e||u!==0?u:0,o&&h===h){for(var g=d.length;g--;)if(d[g]===h)continue e;t&&d.push(h),c.push(u)}else i(d,h,e)||(d!==c&&d.push(h),c.push(u))}return c}function F_(s){return s&&s.length?Sm(s):[]}function $_(s,t){return s&&s.length?Sm(s,f_(t)):[]}var Ju=(s=>(s.PARTICIPANT="PARTICIPANT",s.PEER="PEER",s.CLIENT="CLIENT",s))(Ju||{});const Z={PROPAGATE_KICK_ALL:"propagate_kick_across_rooms",REFRESH_ID_ON_DISCONNECTION:"refresh_id_on_disconnection",SKIP_OTEL_TRACES:"skip_otel_traces",CF_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED:"cf_transport_force_relay_on_ice_failed",LOG_LEVEL:"log_level",V1_PLUGINS:"v1_plugins",LIVESTREAM:"feat_livestream",VAL_MIN_FRAMERATE:"val_min_framerate",SCREEENSHARE_ERR_HACK:"screenshare_err_hack",SCREEENSHARE_CONSTRAINTS_RETRY:"screenshare_constraints_retry",SCREENSHARE_CONSTRAINTS:"screenshare_constraints",OBS_QUALITY:"obs_quality",ALLOW_SAFARI_MEDIA_MIDDLEWARES:"allow_safari_media_middlewares",EXP_RESHARE:"exp_reshare",SKIP_SETTING_IN_USE_DEVICE:"skip_setting_in_use_device",PRECALL_BANDWIDTH_TEST:"precall_bandwidth_test",DEBUG_SOCKET_JOIN:"debug_socket_join",FORCE_RELAY:"force_relay",FORCE_VIDEO_CODEC:"force_video_codec",TRACK_HINT:"track_hint",PRECREATE_PRODUCERS:"precreate_producers",DISABLE_OPUS_DTX_CF:"disable_opus_dtx_cf",ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS:"enable_audio_activity_debug_logs",DISABLE_LAYER_SWITCH:"disable_layer_switch"};function Pd(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 B_={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},ho={baseURL:"http://localhost:5000",createdAt:"2021-08-05T10:49:56.602Z",description:"Develop plugins locally",id:"09259e3b-7be8-46f6-9801-106bf1866e1c",name:"Localhost Dev",organizationId:"4ad15a19-80e2-4105-bf43-48039fd2963e",picture:"https://dyte-uploads.s3.ap-south-1.amazonaws.com/dyte.png",private:!1,published:!0,staggered:!1,tags:["#localhost","#dev"],type:"self_hosted",updatedAt:"2021-08-05T10:50:07.681Z"},H_={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 On(s,t){const e=s.getValue("overrides");return e&&e[t]?e[t]:!1}function q_({baseURI:s}){return s.includes("preprod.realtime")?Za.PREPROD:s.includes("staging.realtime")?Za.DEVEL:Za.PROD}function bi({servicePrefix:s,baseURI:t}){return`${s}.${t}`}function j_(s){const t=s.getValue("baseURI");return{location:bi({servicePrefix:"location",baseURI:t}),locationLegacy:bi({servicePrefix:"location-legacy",baseURI:t}),daCollector:bi({servicePrefix:"da-collector",baseURI:t})}}const G_='<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>',W_='<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>',_d=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})},wi={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"}};function J_(s){var r,i,n;const t=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((r=window.location.host)==null?void 0:r.includes(wi.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 e;if(s!=null&&s.getValue("flagsmith").hasFeature(Z.LOG_LEVEL)){let r=((e=s.getValue("flagsmith").getValue(Z.LOG_LEVEL))==null?void 0:e.toString())||"all";if(r=r.toLowerCase().trim(),r==="off")return!1;if(r!=="all"){const i=["debug","log","info","warn","error"],n=i.indexOf(t),o=i.indexOf(r);if(n<o)return!1}}return!0}function vm(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"?vm(s[r],i,e):["number","string","boolean"].includes(typeof s[r])&&(e[i]=s[r])}),e}function Tm(s,t,e={},r=""){const i={};try{const n=JSON.stringify(e),o=JSON.parse(n),c=vm(o,r),d=JSON.stringify(c);return JSON.parse(d)}catch(n){const o=Pd(n);i[`${r}.error.message`]=o.message||"",i[`${r}.error.stack`]=o.stack||"",i[`${r}.error.reason`]=o.reason||"",i[`${r}.error.source`]="safelyFlattenObjForOpenTelemetry"}return i}class E{constructor(){p(this,"logsCache",[]);p(this,"logsProcessorTimer");p(this,"tracingEnabled",!0);p(this,"initialized",!1);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",{})}get logsEndpoint(){const t=sr.getContext(this.meetingMetadata.peerId);return`https://${bi({servicePrefix:"api-silos",baseURI:t.getValue("baseURI")})}/otel/logs`}resetPeerId(t){this.meetingMetadata.peerId=t}init(t,e,r){this.tracingEnabled=!0,this.initialized=!1,this.logsCache=[];const i=t.getValue("peerId");this.meetingMetadata=e,this.tracingEnabled=r,this.meetingMetadata.peerId=i,this.meetingMetadata.sdkVersion=t.getValue("sdkVersion");const{RNDeviceInfoImpl:n}=navigator;this.meetingMetadata.deviceInfo=navigator.isReactNative?n==null?void 0:n.getDeviceInfo():we.getDeviceInfo(),this.meetingMetadata.visitedUrl=!navigator.isReactNative&&typeof window!="undefined"&&window.location.href,this.logsProcessorTimer=setInterval(this.processCachedLogs.bind(this),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){var g;const l=this==null?void 0:this.telemetry;if(!l||!l.initialized||navigator.isReactNative||!l.tracingEnabled||(g=sr.getContext(l.meetingMetadata.peerId))!=null&&g.getValue("flagsmith").hasFeature(Z.SKIP_OTEL_TRACES))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 S=performance.now();S-u>10&&l.addLogInCurrentSpan("info",`${t}_timing`,{execTime:S-u})}).catch(()=>{const S=performance.now();l.addLogInCurrentSpan("info",`${t}_timing`,{execTime:S-u})}),h},n}}injectContext(t){var i;const e=fi().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:Pd(r.error)});const n=sr.getContext(this.meetingMetadata.peerId);if(J_(n)&&(O_(r)?console[t]("InternalLogs:: ",t,e):console[t]("InternalLogs:: ",t,e,r)),!!K_(n,t))try{const c=Tm(n,e,r,"metadata"),d=new Date,l={message:e,level:t,...c,loggedAt:d.toISOString(),loggedAtTzOffset:d.getTimezoneOffset()};i?this.sendOtelLogsToNewRelic([l]):this.logsCache.push(l)}catch(c){this.addLogInCurrentSpan("error","opentelemetry::addLogInCurrentSpan_failed",{error:Pd(c)})}}sendOtelLogsToNewRelic(t){const e=sr.getContext(this.meetingMetadata.peerId);fetch(this.logsEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({meetingMetadata:Tm(e,"sendOtelLogsToNewRelic",this.meetingMetadata,"meetingMetadata"),serviceName:e.getValue("sdkName"),logs:t})}).catch(r=>{this.addLogInCurrentSpan("error","opentelemetry::sendOtelLogToNewRelic_failed",{error:Pd(r)}),this.logsCache.push(...t)})}processCachedLogs(){const t=this.logsCache.splice(0,25);t!=null&&t.length&&this.sendOtelLogsToNewRelic(t)}destruct(){clearInterval(this.logsProcessorTimer),this.processCachedLogs()}}function z_(s){const t={...s},e=new Map,r=(l,u)=>(e.has(l)||e.set(l,new Set),e.get(l).add(u),()=>{var h;return(h=e.get(l))==null?void 0:h.delete(u)}),i=(l,u)=>{var h;(h=e.get(l))==null||h.delete(u)},n=l=>{var u;(u=e.get(l))==null||u.forEach(h=>{try{h(t[l])}catch(g){}})};return{subscribe:r,unsubscribe:i,notify:n,setValue:(l,u,h=!0)=>{t[l]=u,h&&n(l)},getValue:l=>t[l],getAllValues:()=>t}}class Y_{constructor(){p(this,"contexts",new Map);p(this,"mostRecentPeerId",null)}createContext(t,e){if(this.contexts.has(t))return this.contexts.get(t);const r=new E,i=new Ww;this.contexts.set(t,z_(e)),this.contexts.get(t).setValue("peerSessionStore",new Jw(i));const n=new ng;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.contexts.get(t).setValue("flagsmith",Nw()),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 sr=new Y_,Q_={"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"},Rd={"0000":"Internal exception.","0001":"Failed to initialize.","0002":"Failed to join room.","0003":"Failed to leave room.","0004":"Invalid auth token","0010":"Browser not supported","0011":"HTTP Network Error","0012":"Websocket Network Error","0013":"Rate Limited","0100":"Internal exception","0101":"Permission denied","0102":"Prerequisite module missing","0200":"Internal exception.","0300":"Internal exception","0400":"Internal exception","0404":"Missing prerequisites to establish a websocket connection","0500":"Internal exception","0501":"Permission denied.","0502":"Invalid message body.","0503":"Text Message is too large","0504":"Message not found by the given id","0505":"Action not permitted without joining room","0506":"Message search is disabled","0600":"Internal exception","0601":"Permission denied.","0602":"Auth token not set for plugin","0603":"Iframe was not provided","0700":"Internal exception","0705":"Action not permitted without joining room","0800":"Internal exception","0801":"Permission denied","0900":"Internal exception","0904":"Could not load preset",1e3:"Internal exception",1001:"Permission denied",1004:"Could not find specified recording",1005:"Action not permitted in given recording state",1100:"Internal exception",1101:"Permission denied",1102:"Unsupported",1103:"Name cannot be empty",1104:"No device selected while calling meeting.self.setDevice",1105:"Action not permitted without joining room",1106:"Can't set currently used device",1200:"Internal exception",1201:"Permission denied",1202:"Invalid page number was requested",1203:"Invalid participant count per page was requested",1204:"No participants exists with the given UserIds",1205:"Action not permitted without joining room",1206:"Manual Subscription Mode was not ACTIVATED",1207:"Invalid view mode",1208:"Manual Subscription not enabled for organization",1209:"Broadcast message type must be a non-empty string",1300:"Internal exception",1400:"Internal exception",1402:"No existing remote requests",1403:"No peer exists with given id",1500:"Internal exception",1600:"Internal exception",1601:"Failed to get audio track",1602:"Failed to get video track",1603:"Incorrect device",1604:"Failed to change device",1605:"Failed to get audio & video track",1606:"No audio input devices are available",1607:"No video input devices are available",1608:"No audio output devices (speakers) are available",1609:"Failed to fetch list of media devices",1610:"No media track exists",1611:"Failed to unmute track",1612:"Failed to get screenshare tracks",1701:"Crypto error",1800:"Internal exception",1801:"Can't fetch transcript file",1900:"Internal exception",1901:"Permission denied.",1902:"Livestream that has not yet started, can't be stopped",2e3:"Internal exception",2001:"Permission denied",2002:"Unsupported",2003:"Stage is disabled",2004:"Method not implemented",2005:"Action not permitted without joining room",2006:"Action not permitted in current stage status",9900:"Internal exception"};Object.keys(Rd).forEach(s=>{Rd[s]=`{${Q_[s.slice(0,2)]}} ${Rd[s]}`});class k 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?Rd[this.code]:"";this.message=`${o}: ${c}
|
|
10
|
+
${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=sr.getContext(sr.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 Cd(s,t,e,r){if(r instanceof k)throw r;if(r instanceof t){const i=new k(r.message,e);throw i.stack=r.stack,i}else throw r}function ym(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){Cd(this,t,e,o)}}),n&&(s.set=function(o){try{return n.apply(this,[o])}catch(c){Cd(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=>{Cd(this,t,e,o)}):n}catch(n){Cd(this,t,e,n)}},s}function X_(s,t){return(e,r,i)=>{if(i)return ym(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,ym(o,s,t))}}}const ut=s=>X_(Error,s);function Z_(s){let t=0,e,r;if(!s)return t;for(e=0;e<s.length;e+=1)r=s.charCodeAt(e),t=(t<<5)-t+r,t|=0;return Math.abs(t)%100+1}function eR(){we.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.PRODUCER_CLOSED="websocket/producer-closed",s.NEW_CONSUMER="websocket/new-consumer",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.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))(_||{});class Dn extends lt.EventEmitter{constructor(e){super();p(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}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 $t extends lt.EventEmitter{constructor(e){super();p(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}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)}}function tR(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 Em=1080,bm=1920,sR=(s,t,e,r,i,n)=>{let o=.5,c=.5;const d=i,l=n,u=Math.min(e/d,r/l);let h=d*u,g=l*u,S,y,w,b,C=1;return h<e&&(C=e/h),Math.abs(C-1)<1e-14&&g<r&&(C=r/g),h*=C,g*=C,w=d/(h/e),b=l/(g/r),S=(d-w)*o,y=(l-b)*c,S<0&&(S=0),y<0&&(y=0),w>d&&(w=d),b>l&&(b=l),[S,y,w,b,s,t,e,r]},Xh=class extends $t{constructor(e,r,i,n){const o=e.getValue("logger");super(o);m(this,ns,void 0);m(this,xi,void 0);m(this,pt,void 0);m(this,as,void 0);m(this,Ne,{height:Em,width:bm});m(this,_s,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"});m(this,mr,void 0);m(this,wt,{});m(this,Fe,void 0);m(this,Jn,void 0);m(this,Kn,void 0);m(this,fr,void 0);m(this,zn,!1);p(this,"cleanupEventListeners",()=>{a(this,xi).unsubscribe("stageStatus",this.handlePipMediaControls),a(this,Fe).removeListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,Fe).removeListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,Fe).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,Fe).videoEnabled?a(this,Fe).disableVideo():a(this,Fe).enableVideo(),this.emit("cameraToggled")),e==="MIC"&&(a(this,Fe).audioEnabled?a(this,Fe).disableAudio():a(this,Fe).enableAudio(),this.emit("micToggled")),e==="END"&&(a(this,xi).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,fr)==="active"){this.disable(!0);return}a(this,wt)!==void 0&&this.paintCanvas(),a(this,mr)!==void 0&&f(this,mr,requestAnimationFrame(()=>this.animate()))});p(this,"disable",(e=!1)=>{f(this,fr,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(a(this,mr)),e!==!0&&document.body.removeChild(a(this,pt)),f(this,mr,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()});f(this,xi,e),f(this,fr,"idle"),f(this,Fe,r),f(this,_s,{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 _d(G_),n=await _d(W_)}catch(o){}return new Xh(e,r,i,n)}async setupIcon(e,r){switch(e){case"handRaise":f(this,Kn,r);break;case"pin":f(this,Jn,r);break}}async overrideIcon(e,r){switch(e){case"handRaise":f(this,Kn,await _d(r));break;case"pin":f(this,Jn,await _d(r));break}}constructImage(e){const r=new Image,i=new Blob([e],{type:"image/svg+xml"}),n=window.URL.createObjectURL(i);return new Promise(o=>{r.onload=()=>{o(r),window.URL.revokeObjectURL(n)},r.src=n})}createVideoContainer(){f(this,pt,document.createElement("div")),a(this,pt).style.width="0.1px",a(this,pt).style.height="0.1px",a(this,pt).style.overflow="hidden",a(this,pt).style.position="absolute",a(this,pt).style.bottom="0",a(this,pt).style.right="0",a(this,pt).style.opacity="0",a(this,pt).appendChild(a(this,as))}setupEventListeners(){a(this,xi).subscribe("stageStatus",this.handlePipMediaControls),a(this,Fe).addListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,Fe).addListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,Fe).addListener("roomLeft",()=>this.disable())}createCanvas(){const e=document.createElement("canvas");e.height=a(this,Ne).height,e.width=a(this,Ne).width,f(this,ns,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,Fe).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||a(this,Fe).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const r=Object.values(a(this,wt)).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,ns)===void 0)return;const o=a(this,ns).getContext("2d"),c=a(this,ns).width,d=0,l=0,u=r-d*2,h=i-d*2,g=Math.floor(c/u),S=Math.floor(e/g),w=e%g*(u+d)+d,b=S*(h+d)+d,{displayText:C,image:D}=n!=null?n:{};o.fillStyle=C||D?a(this,_s).videoBackground:a(this,_s).background,o.strokeStyle=a(this,_s).brand,o.beginPath(),o.moveTo(w+l,b),o.arcTo(w+u,b,w+u,b+l,l),o.arcTo(w+u,b+h,w+u-l,b+h,l),o.arcTo(w,b+h,w,b+h-l,l),o.arcTo(w,b,w+l,b,l),o.closePath(),o.fill(),o.stroke();const F=u/6,L=u/2+w,B=h/2+b;o.save(),(C||D)&&(o.beginPath(),o.arc(L,B,F,0,Math.PI*2),o.fillStyle=a(this,_s).brand,o.fill(),D?(o.clip(),o.drawImage(D,L-F,B-F,F*2,F*2),o.restore()):C&&(o.fillStyle=a(this,_s).textOnBrand,o.font=`${F/2}px sans-serif`,o.textAlign="center",o.textBaseline="middle",o.fillText(C,L,B)),this.drawIcons(n,w,b,Math.max(u,h)))}drawIcons(e,r,i,n){const o=Math.min(Math.max(n*.15,100),200),c=o*.2,d=o*.2;let l=r+c;const u=i+c,h=g=>{const S=a(this,ns).getContext("2d");S.save(),S.fillStyle=a(this,_s).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 g=="string"?(S.font=`${o/1.5}px sans-serif`,S.fillStyle=a(this,_s).text,S.textAlign="center",S.textBaseline="top",S.fillText(g,o/2+l,u+c)):S.drawImage(g,l+c,u+c,o-c*2,o-c*2),l+=o+c,S.restore()};e.pinned&&h(a(this,Jn)),e.handRaised&&h(a(this,Kn)),e.reaction&&h(e.reaction)}drawTile(e,r,i){var l,u;if(a(this,ns)===void 0)return;const n=a(this,ns).getContext("2d"),o=this.getSources();let c=0,d=0;for(;c<a(this,Ne).height-5;){let h=0;for(;h<a(this,Ne).width-5&&d<i;){if((l=o[d])!=null&&l.enabled){const g=o[d].element,[S,y,w,b,C,D,F,L]=sR(h,c,e,r,g.videoWidth,g.videoHeight);((u=g==null?void 0:g.classList)==null?void 0:u.contains("mirror"))?(n.save(),n.scale(-1,1),n.drawImage(g,S,y,w,b,-1*C,D,-1*F,L),n.restore()):n.drawImage(g,S,y,w,b,C,D,F,L),this.drawIcons(o[d],C,D,Math.max(F,L))}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,Ne).width,a(this,Ne).height];case 2:return[Math.floor(a(this,Ne).width/2),a(this,Ne).height];case 3:case 4:return[Math.floor(a(this,Ne).width/2),Math.floor(a(this,Ne).height/2)];case 5:case 6:return[Math.floor(a(this,Ne).width/3),Math.floor(a(this,Ne).height/2)];case 7:case 8:case 9:return[Math.floor(a(this,Ne).width/3),Math.floor(a(this,Ne).height/3)];default:return[Math.floor(a(this,Ne).width/3),Math.floor(a(this,Ne).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,Fe).config)==null?void 0:e.viewType)!=="LIVESTREAM"}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(f(this,zn,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),a(this,pt))try{document.body.removeChild(a(this,pt))}catch(e){}this.removeAllSources(),f(this,ns,void 0),f(this,as,void 0),f(this,mr,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,zn))return;f(this,zn,!0),this.createCanvas(),this.setupMediaSessionEvents();const i=document.createElement("video");f(this,Ne,{height:e!=null?e:Em,width:r!=null?r:bm}),i.height=a(this,Ne).height,i.width=a(this,Ne).width,i.autoplay=!0,i.muted=!0,i.srcObject=a(this,ns).captureStream(24),f(this,as,i),a(this,as).onloadedmetadata=()=>{try{this.emit("pipStarted"),a(this,as).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,wt)[e]!==void 0&&(a(this,wt)[e].enabled=!0)}disableSource(e){a(this,wt)[e]!==void 0&&(a(this,wt)[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,wt)[e]={id:e,element:r,enabled:i,pinned:n,displayText:o?tR(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,wt)[e];i&&(a(this,wt)[e]={...i,...r})}removeSource(e){delete a(this,wt)[e]}removePinnedSource(){Object.values(a(this,wt)).forEach(r=>{r.pinned&&this.removeSource(r.id)})}removeAllSources(){f(this,wt,{})}enable(){f(this,fr,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",a(this,Fe).videoEnabled),this.updateMediaSession("MIC",a(this,Fe).audioEnabled),document.body.appendChild(a(this,pt)),f(this,mr,requestAnimationFrame(()=>this.animate())),a(this,as).onloadedmetadata=()=>{a(this,as).requestPictureInPicture().then(()=>{f(this,fr,"active")})},a(this,as).readyState===4&&a(this,as).requestPictureInPicture().then(()=>{f(this,fr,"active")})}};let Ku=Xh;ns=new WeakMap,xi=new WeakMap,pt=new WeakMap,as=new WeakMap,Ne=new WeakMap,_s=new WeakMap,mr=new WeakMap,wt=new WeakMap,Fe=new WeakMap,Jn=new WeakMap,Kn=new WeakMap,fr=new WeakMap,zn=new WeakMap;function zu(s){let t=typeof s;if(t=="object"){if(Array.isArray(s))return"array";if(s===null)return"null"}return t}function rR(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}let rr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),kd=[];for(let s=0;s<rr.length;s++)kd[rr[s].charCodeAt(0)]=s;kd["-".charCodeAt(0)]=rr.indexOf("+"),kd["_".charCodeAt(0)]=rr.indexOf("/");function iR(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=kd[s.charCodeAt(c)],n===void 0)switch(s[c]){case"=":i=0;case`
|
|
11
|
+
`: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 nR(s){let t="",e=0,r,i=0;for(let n=0;n<s.length;n++)switch(r=s[n],e){case 0:t+=rr[r>>2],i=(r&3)<<4,e=1;break;case 1:t+=rr[i|r>>4],i=(r&15)<<2,e=2;break;case 2:t+=rr[i|r>>6],t+=rr[r&63],e=0;break}return e&&(t+=rr[i],t+="=",e==1&&(t+="=")),t}var Id;(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])})(Id||(Id={}));var xe;(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"})(xe||(xe={}));function aR(){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 Yu(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 Ad=(1<<16)*(1<<16);function wm(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>=Ad&&(i=i+(r/Ad|0),r=r%Ad)}return n(-24,-18),n(-18,-12),n(-12,-6),n(-6),[t,r,i]}function Qu(s,t){if(t>>>0<=2097151)return""+(Ad*t+(s>>>0));let e=s&16777215,r=(s>>>24|t<<8)>>>0&16777215,i=t>>16&65535,n=e+r*6777216+i*6710656,o=r+i*8147497,c=i*2,d=1e7;n>=d&&(o+=Math.floor(n/d),n%=d),o>=d&&(c+=Math.floor(o/d),o%=d);function l(u,h){let g=u?String(u):"";return h?"0000000".slice(g.length)+g:g}return l(c,0)+l(o,c)+l(n,1)}function Pm(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 oR(){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 ue;function cR(){const s=new DataView(new ArrayBuffer(8));ue=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}cR();function _m(s){if(!s)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const Rm=/^-?[0-9]+$/,Md=4294967296,Od=2147483648;class Cm{constructor(t,e){this.lo=t|0,this.hi=e|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let t=this.hi*Md+(this.lo>>>0);if(!Number.isSafeInteger(t))throw new Error("cannot convert to safe number");return t}}class ht extends Cm{static from(t){if(ue)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=ue.C(t);case"number":if(t===0)return this.ZERO;t=ue.C(t);case"bigint":if(!t)return this.ZERO;if(t<ue.UMIN)throw new Error("signed value for ulong");if(t>ue.UMAX)throw new Error("ulong too large");return ue.V.setBigUint64(0,t,!0),new ht(ue.V.getInt32(0,!0),ue.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!Rm.test(t))throw new Error("string is no integer");let[e,r,i]=wm(t);if(e)throw new Error("signed value for ulong");return new ht(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 ht(t,t/Md)}throw new Error("unknown value "+typeof t)}toString(){return ue?this.toBigInt().toString():Qu(this.lo,this.hi)}toBigInt(){return _m(ue),ue.V.setInt32(0,this.lo,!0),ue.V.setInt32(4,this.hi,!0),ue.V.getBigUint64(0,!0)}}ht.ZERO=new ht(0,0);class ge extends Cm{static from(t){if(ue)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=ue.C(t);case"number":if(t===0)return this.ZERO;t=ue.C(t);case"bigint":if(!t)return this.ZERO;if(t<ue.MIN)throw new Error("signed long too small");if(t>ue.MAX)throw new Error("signed long too large");return ue.V.setBigInt64(0,t,!0),new ge(ue.V.getInt32(0,!0),ue.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!Rm.test(t))throw new Error("string is no integer");let[e,r,i]=wm(t);if(e){if(i>Od||i==Od&&r!=0)throw new Error("signed long too small")}else if(i>=Od)throw new Error("signed long too large");let n=new ge(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 ge(t,t/Md):new ge(-t,-t/Md).negate()}throw new Error("unknown value "+typeof t)}isNegative(){return(this.hi&Od)!==0}negate(){let t=~this.hi,e=this.lo;return e?e=~e+1:t+=1,new ge(e,t)}toString(){if(ue)return this.toBigInt().toString();if(this.isNegative()){let t=this.negate();return"-"+Qu(t.lo,t.hi)}return Qu(this.lo,this.hi)}toBigInt(){return _m(ue),ue.V.setInt32(0,this.lo,!0),ue.V.setInt32(4,this.hi,!0),ue.V.getBigInt64(0,!0)}}ge.ZERO=new ge(0,0);const km={readUnknownField:!0,readerFactory:s=>new lR(s)};function dR(s){return s?Object.assign(Object.assign({},km),s):km}class lR{constructor(t,e){this.varint64=aR,this.uint32=oR,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 xe.Varint:for(;this.buf[this.pos++]&128;);break;case xe.Bit64:this.pos+=4;case xe.Bit32:this.pos+=4;break;case xe.LengthDelimited:let r=this.uint32();this.pos+=r;break;case xe.StartGroup:let i;for(;(i=this.tag()[1])!==xe.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 ge(...this.varint64())}uint64(){return new ht(...this.varint64())}sint64(){let[t,e]=this.varint64(),r=-(t&1);return t=(t>>>1|(e&1)<<31)^r,e=e>>>1^r,new ge(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 ht(this.sfixed32(),this.sfixed32())}sfixed64(){return new ge(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 re(s,t){if(!s)throw new Error(t)}const uR=34028234663852886e22,hR=-34028234663852886e22,pR=4294967295,gR=2147483647,mR=-2147483648;function po(s){if(typeof s!="number")throw new Error("invalid int 32: "+typeof s);if(!Number.isInteger(s)||s>gR||s<mR)throw new Error("invalid int 32: "+s)}function Dd(s){if(typeof s!="number")throw new Error("invalid uint 32: "+typeof s);if(!Number.isInteger(s)||s>pR||s<0)throw new Error("invalid uint 32: "+s)}function Xu(s){if(typeof s!="number")throw new Error("invalid float 32: "+typeof s);if(Number.isFinite(s)&&(s>uR||s<hR))throw new Error("invalid float 32: "+s)}const Im={writeUnknownFields:!0,writerFactory:()=>new SR};function fR(s){return s?Object.assign(Object.assign({},Im),s):Im}class SR{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(Dd(t);t>127;)this.buf.push(t&127|128),t=t>>>7;return this.buf.push(t),this}int32(t){return po(t),Pm(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){Xu(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){Dd(t);let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),this.raw(e)}sfixed32(t){po(t);let e=new Uint8Array(4);return new DataView(e.buffer).setInt32(0,t,!0),this.raw(e)}sint32(t){return po(t),t=(t<<1^t>>31)>>>0,Pm(t,this.buf),this}sfixed64(t){let e=new Uint8Array(8),r=new DataView(e.buffer),i=ge.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=ht.from(t);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(e)}int64(t){let e=ge.from(t);return Yu(e.lo,e.hi,this.buf),this}sint64(t){let e=ge.from(t),r=e.hi>>31,i=e.lo<<1^r,n=(e.hi<<1|e.lo>>>31)^r;return Yu(i,n,this.buf),this}uint64(t){let e=ht.from(t);return Yu(e.lo,e.hi,this.buf),this}}const Am={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},Mm={ignoreUnknownFields:!1};function vR(s){return s?Object.assign(Object.assign({},Mm),s):Mm}function TR(s){return s?Object.assign(Object.assign({},Am),s):Am}const Om=Symbol.for("protobuf-ts/message-type");function Dm(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 A;(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"})(A||(A={}));var $s;(function(s){s[s.BIGINT=0]="BIGINT",s[s.STRING=1]="STRING",s[s.NUMBER=2]="NUMBER"})($s||($s={}));var Nd;(function(s){s[s.NO=0]="NO",s[s.PACKED=1]="PACKED",s[s.UNPACKED=2]="UNPACKED"})(Nd||(Nd={}));function yR(s){var t,e,r,i;return s.localName=(t=s.localName)!==null&&t!==void 0?t:Dm(s.name),s.jsonName=(e=s.jsonName)!==null&&e!==void 0?e:Dm(s.name),s.repeat=(r=s.repeat)!==null&&r!==void 0?r:Nd.NO,s.opt=(i=s.opt)!==null&&i!==void 0?i:s.repeat||s.oneof?!1:s.kind=="message",s}function ER(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 bR{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(!ER(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,A.INT32,i):this.scalar(t,A.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),A.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 A.UINT64:case A.FIXED64:case A.INT64:case A.SFIXED64:case A.SINT64:switch(r){case $s.BIGINT:return i=="bigint";case $s.NUMBER:return i=="number"&&!isNaN(t);default:return i=="string"}case A.BOOL:return i=="boolean";case A.STRING:return i=="string";case A.BYTES:return t instanceof Uint8Array;case A.DOUBLE:case A.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 A.INT32:case A.FIXED32:case A.SFIXED32:case A.SINT32:case A.UINT32:return this.scalars(i.slice(0,r).map(n=>parseInt(n)),e,r);case A.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,$s.STRING)}}}function vs(s,t){switch(t){case $s.BIGINT:return s.toBigInt();case $s.NUMBER:return s.toNumber();default:return s.toString()}}class wR{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=zu(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(rR(o),c.name,o);const u=l[d];for(const[h,g]of Object.entries(o)){this.assert(g!==null,c.name+" map value",null);let S;switch(c.V.kind){case"message":S=c.V.T().internalJsonRead(g,r);break;case"enum":if(S=this.enum(c.V.T(),g,c.name,r.ignoreUnknownFields),S===!1)continue;break;case"scalar":S=this.scalar(g,c.V.T,c.V.L,c.name);break}this.assert(S!==void 0,c.name+" map value",g);let y=h;c.K==A.BOOL&&(y=y=="true"?!0:y=="false"?!1:y),y=this.scalar(y,c.K,$s.STRING,c.name).toString(),u[y]=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 g;switch(c.kind){case"message":g=c.T().internalJsonRead(h,r);break;case"enum":if(g=this.enum(c.T(),h,c.name,r.ignoreUnknownFields),g===!1)continue;break;case"scalar":g=this.scalar(h,c.T,c.L,c.name);break}this.assert(g!==void 0,c.name,o),u.push(g)}}else switch(c.kind){case"message":if(o===null&&c.T().typeName!="google.protobuf.Value"){this.assert(c.oneof===void 0,c.name+" (oneof member)",null);continue}l[d]=c.T().internalJsonRead(o,r,l[d]);break;case"enum":if(o===null)continue;let u=this.enum(c.T(),o,c.name,r.ignoreUnknownFields);if(u===!1)continue;l[d]=u;break;case"scalar":if(o===null)continue;l[d]=this.scalar(o,c.T,c.L,c.name);break}}}enum(t,e,r,i){if(t[0]=="google.protobuf.NullValue"&&re(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 re(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:(re(typeof o=="number",`Unable to parse field ${this.info.typeName}#${r}, enum ${t[0]} has no value for "${e}".`),o)}re(!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 A.DOUBLE:case A.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==A.FLOAT&&Xu(o),o;case A.INT32:case A.FIXED32:case A.SFIXED32:case A.SINT32:case A.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==A.UINT32?Dd(c):po(c),c;case A.INT64:case A.SFIXED64:case A.SINT64:if(t===null)return vs(ge.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return vs(ge.from(t),r);case A.FIXED64:case A.UINT64:if(t===null)return vs(ht.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return vs(ht.from(t),r);case A.BOOL:if(t===null)return!1;if(typeof t!="boolean")break;return t;case A.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 A.BYTES:if(t===null||t==="")return new Uint8Array(0);if(typeof t!="string")break;return iR(t)}}catch(o){n=o.message}this.assert(!1,i+(n?" - "+n:""),t)}}class PR{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);re(d!==void 0),r[e.useProtoFieldName?n.name:n.jsonName]=d}return r}field(t,e,r){let i;if(t.kind=="map"){re(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);re(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);re(u!==void 0),n[d.toString()]=u}break;case"enum":const c=t.V.T();for(const[d,l]of Object.entries(e)){re(l===void 0||typeof l=="number");const u=this.enum(c,l,t.name,!1,!0,r.enumAsInteger);re(u!==void 0),n[d.toString()]=u}break}(r.emitDefaultValues||Object.keys(n).length>0)&&(i=n)}else if(t.repeat){re(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);re(l!==void 0),n.push(l)}break;case"enum":const o=t.T();for(let d=0;d<e.length;d++){re(e[d]===void 0||typeof e[d]=="number");const l=this.enum(o,e[d],t.name,t.opt,!0,r.enumAsInteger);re(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);re(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){re(i);return}if(!(e===0&&!n&&!i))return re(typeof e=="number"),re(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){re(i);return}const o=n||i;switch(t){case A.INT32:case A.SFIXED32:case A.SINT32:return e===0?o?0:void 0:(po(e),e);case A.FIXED32:case A.UINT32:return e===0?o?0:void 0:(Dd(e),e);case A.FLOAT:Xu(e);case A.DOUBLE:return e===0?o?0:void 0:(re(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e);case A.STRING:return e===""?o?"":void 0:(re(typeof e=="string"),e);case A.BOOL:return e===!1?o?!1:void 0:(re(typeof e=="boolean"),e);case A.UINT64:case A.FIXED64:re(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let c=ht.from(e);return c.isZero()&&!o?void 0:c.toString();case A.INT64:case A.SFIXED64:case A.SINT64:re(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let d=ge.from(e);return d.isZero()&&!o?void 0:d.toString();case A.BYTES:return re(e instanceof Uint8Array),e.byteLength?nR(e):o?"":void 0}}}function Zu(s,t=$s.STRING){switch(s){case A.BOOL:return!1;case A.UINT64:case A.FIXED64:return vs(ht.ZERO,t);case A.INT64:case A.SFIXED64:case A.SINT64:return vs(ge.ZERO,t);case A.DOUBLE:case A.FLOAT:return 0;case A.BYTES:return new Uint8Array(0);case A.STRING:return"";default:return 0}}class _R{constructor(t){this.info=t}prepare(){var t;if(!this.fieldNoToField){const e=(t=this.info.fields)!==null&&t!==void 0?t:[];this.fieldNoToField=new Map(e.map(r=>[r.no,r]))}}read(t,e,r,i){this.prepare();const n=i===void 0?t.len:t.pos+i;for(;t.pos<n;){const[o,c]=t.tag(),d=this.fieldNoToField.get(o);if(!d){let g=r.readUnknownField;if(g=="throw")throw new Error(`Unknown field ${o} (wire type ${c}) for ${this.info.typeName}`);let S=t.skip(c);g!==!1&&(g===!0?Id.onRead:g)(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 g=d.kind=="enum"?A.INT32:d.T,S=d.kind=="scalar"?d.L:void 0;if(u){let b=l[h];if(c==xe.LengthDelimited&&g!=A.STRING&&g!=A.BYTES){let C=t.uint32()+t.pos;for(;t.pos<C;)b.push(this.scalar(t,g,S))}else b.push(this.scalar(t,g,S))}else l[h]=this.scalar(t,g,S);break;case"message":if(u){let b=l[h],C=d.T().internalBinaryRead(t,t.uint32(),r);b.push(C)}else l[h]=d.T().internalBinaryRead(t,t.uint32(),r,l[h]);break;case"map":let[y,w]=this.mapEntry(d,t,r);l[h][y]=w;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==A.BOOL?o=e.bool().toString():o=this.scalar(e,t.K,$s.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=Zu(t.K);o=t.K==A.BOOL?d.toString():d}if(c===void 0)switch(t.V.kind){case"scalar":c=Zu(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 A.INT32:return t.int32();case A.STRING:return t.string();case A.BOOL:return t.bool();case A.DOUBLE:return t.double();case A.FLOAT:return t.float();case A.INT64:return vs(t.int64(),r);case A.UINT64:return vs(t.uint64(),r);case A.FIXED64:return vs(t.fixed64(),r);case A.FIXED32:return t.fixed32();case A.BYTES:return t.bytes();case A.UINT32:return t.uint32();case A.SFIXED32:return t.sfixed32();case A.SFIXED64:return vs(t.sfixed64(),r);case A.SINT32:return t.sint32();case A.SINT64:return vs(t.sint64(),r)}}}class RR{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"?A.INT32:n.T;if(d)if(re(Array.isArray(o)),d==Nd.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?re(n.opt):this.scalar(e,u,n.no,o,c||n.opt);break;case"message":if(d){re(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":re(typeof o=="object"&&o!==null);for(const[h,g]of Object.entries(o))this.mapEntry(e,r,n,h,g);break}}let i=r.writeUnknownFields;i!==!1&&(i===!0?Id.onWrite:i)(this.info.typeName,t,e)}mapEntry(t,e,r,i,n){t.tag(r.no,xe.LengthDelimited),t.fork();let o=i;switch(r.K){case A.INT32:case A.FIXED32:case A.UINT32:case A.SFIXED32:case A.SINT32:o=Number.parseInt(i);break;case A.BOOL:re(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,A.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,xe.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;re(e!==A.BYTES&&e!==A.STRING),t.tag(r,xe.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=xe.Varint,i,n=e===void 0,o=e===0;switch(t){case A.INT32:i="int32";break;case A.STRING:o=n||!e.length,r=xe.LengthDelimited,i="string";break;case A.BOOL:o=e===!1,i="bool";break;case A.UINT32:i="uint32";break;case A.DOUBLE:r=xe.Bit64,i="double";break;case A.FLOAT:r=xe.Bit32,i="float";break;case A.INT64:o=n||ge.from(e).isZero(),i="int64";break;case A.UINT64:o=n||ht.from(e).isZero(),i="uint64";break;case A.FIXED64:o=n||ht.from(e).isZero(),r=xe.Bit64,i="fixed64";break;case A.BYTES:o=n||!e.byteLength,r=xe.LengthDelimited,i="bytes";break;case A.FIXED32:r=xe.Bit32,i="fixed32";break;case A.SFIXED32:r=xe.Bit32,i="sfixed32";break;case A.SFIXED64:o=n||ge.from(e).isZero(),r=xe.Bit64,i="sfixed64";break;case A.SINT32:i="sint32";break;case A.SINT64:o=n||ge.from(e).isZero(),i="sint64";break}return[r,i,n||o]}}function CR(s){const t=s.messagePrototype?Object.create(s.messagePrototype):Object.defineProperty({},Om,{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]=Zu(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 kR(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"?A.INT32:r.T;if(!(r.repeat?Vm(c,n,o):Nm(c,n,o)))return!1;break;case"map":if(!(r.V.kind=="message"?Lm(r.V.T(),Vd(n),Vd(o)):Vm(r.V.kind=="enum"?A.INT32:r.V.T,Vd(n),Vd(o))))return!1;break;case"message":let d=r.T();if(!(r.repeat?Lm(d,n,o):d.equals(n,o)))return!1;break}}return!0}const Vd=Object.values;function Nm(s,t,e){if(t===e)return!0;if(s!==A.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 Vm(s,t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(!Nm(s,t[r],e[r]))return!1;return!0}function Lm(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 IR=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({}));class v{constructor(t,e,r){this.defaultCheckDepth=16,this.typeName=t,this.fields=e.map(yR),this.options=r!=null?r:{},this.messagePrototype=Object.create(null,Object.assign(Object.assign({},IR),{[Om]:{value:this}})),this.refTypeCheck=new bR(this),this.refJsonReader=new wR(this),this.refJsonWriter=new PR(this),this.refBinReader=new _R(this),this.refBinWriter=new RR(this)}create(t){let e=CR(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 kR(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=dR(e);return this.internalBinaryRead(r.readerFactory(t),t.byteLength,r)}fromJson(t,e){return this.internalJsonRead(t,vR(e))}fromJsonString(t,e){let r=JSON.parse(t);return this.fromJson(r,e)}toJson(t,e){return this.internalJsonWrite(t,TR(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=fR(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 ${zu(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 ir;(function(s){s[s.PUBLISHER=0]="PUBLISHER",s[s.SUBSCRIBER=1]="SUBSCRIBER"})(ir||(ir={}));var Bs;(function(s){s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO"})(Bs||(Bs={}));class AR 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 xm=new AR;class MR 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 OR=new MR;class DR extends v{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new DR;class NR extends v{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",ir]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const Ts=new NR;class VR 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 LR=new VR;class xR 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:()=>Ts},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8},{no:5,name:"producers",kind:"message",repeat:1,T:()=>LR}])}}const UR=new xR;class FR 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 $R=new FR;class BR extends v{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Ts},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:4,name:"producer_ids",kind:"scalar",repeat:2,T:9}])}}const Um=new BR;class HR extends v{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Ts}])}}const qR=new HR;class jR extends v{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Ts}])}}new jR;class GR 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 WR=new GR;class JR 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 KR=new JR;class zR 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 zR;class YR 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 YR;class QR extends v{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",Bs]},{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:()=>xm}])}}const go=new QR;class XR extends v{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>go},{no:3,name:"producer_track",kind:"message",T:()=>KR},{no:4,name:"error_code",kind:"scalar",opt:!0,T:9}])}}const ZR=new XR;class eC extends v{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>ZR}}])}}const Fm=new eC;class tC extends v{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>Hm},{no:2,name:"receiver",kind:"message",T:()=>Hm}])}}const $m=new tC;class sC extends v{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>xm},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>OR}])}}const Bm=new sC;class rC extends v{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>Bm},{no:2,name:"video",kind:"message",T:()=>Bm}])}}const Hm=new rC;class iC 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 nC=new iC;class aC 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 qm=new aC;class oC 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 cC=new oC;class dC 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:()=>cC},{no:9,name:"capabilities",kind:"message",T:()=>$m}])}}const lC=new dC;class uC extends v{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const hC=new uC;class pC extends v{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const gC=new pC;class mC 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 mC;class fC 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:()=>nC},{no:5,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:6,name:"simulcast",kind:"message",T:()=>qm}])}}const SC=new fC;class vC extends v{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>SC},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const TC=new vC;class yC extends v{constructor(){super("media.edge.UpdateConsumerSimulcastConfigRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"simulcast",kind:"message",T:()=>qm},{no:3,name:"producing_transport_id",kind:"scalar",T:9},{no:4,name:"mid",kind:"scalar",T:9}])}}const EC=new yC;class bC extends v{constructor(){super("media.edge.UpdateConsumersSimulcastConfigRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>EC},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const wC=new bC;class PC 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:()=>Ts},{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 _C=new PC;class RC extends v{constructor(){super("media.edge.SelectedPeersRequest",[])}}new RC;class CC extends v{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const kC=new CC;class IC 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 Ld=new IC;class AC 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 AC;class MC extends v{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Ts},{no:3,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const OC=new MC;class DC 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:()=>Ts},{no:3,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const NC=new DC;class VC extends v{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new VC;class LC extends v{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const jm=new LC;class xC 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 UC=new xC;class FC 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 $C=new FC;class BC 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 HC=new BC;class qC 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 jC=new qC;class GC 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 WC=new GC;class JC extends v{constructor(){super("media.edge.EmptyResponse",[])}}new JC;class KC 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:()=>go},{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:()=>$m}])}}const Gm=new KC;class zC 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 th=new zC;class YC 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 QC=new YC;class XC extends v{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>QC}])}}const Wm=new XC;class ZC extends v{constructor(){super("media.edge.PeerJoinResponse",[])}}new ZC;class ek extends v{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>jC},{no:2,name:"participants",kind:"message",repeat:1,T:()=>Gm},{no:3,name:"selected_peers",kind:"message",T:()=>th},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const sh=new ek;class tk extends v{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const sk=new tk;class rk extends v{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Fm}])}}new rk;class ik extends v{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Fm},{no:3,name:"description",kind:"message",T:()=>Ts}])}}const nk=new ik;class ak 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:()=>Ts}])}}const ok=new ak;class ck extends v{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>WR}])}}new ck;class dk 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 dk;class lk extends v{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new lk;class uk extends v{constructor(){super("media.edge.ProducerToggleResponse",[])}}new uk;class hk extends v{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new hk;class pk extends v{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>Ts}])}}const gk=new pk;class mk extends v{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>Ts}])}}const fk=new mk;class Sk extends v{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new Sk;class vk extends v{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new vk;class Tk extends v{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new Tk;class yk extends v{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Ek=new yk;class bk extends v{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const wk=new bk;class Pk extends v{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const _k=new Pk;class Rk extends v{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>Gm}])}}const Jm=new Rk;class Ck extends v{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const Km=new Ck;class kk extends v{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>Km},{no:3,name:"screenshare",kind:"message",T:()=>Km}])}}const Ik=new kk;class Ak extends v{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>Um},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>Ik}])}}new Ak;class Mk extends v{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>go}])}}const Ok=new Mk;class Dk extends v{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>go},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const zm=new Dk;class Nk extends v{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>go}])}}const Vk=new Nk;class Lk extends v{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const rh=new Lk;class xk extends v{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Ym=new xk;class Uk extends v{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new Uk;class Fk extends v{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new Fk;class $k extends v{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new $k;class Bk 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 Bk;class Hk extends v{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new Hk;class qk extends v{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new qk;class jk 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 ih=new jk;class Gk 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 Gk;class Wk 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 Jk=new Wk;var Pi;(function(s){s[s.BROWSER=0]="BROWSER",s[s.TRACK=1]="TRACK",s[s.COMPOSITE=2]="COMPOSITE"})(Pi||(Pi={}));var nr;(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"})(nr||(nr={}));var nh;(function(s){s[s.NONE=0]="NONE",s[s.RECORDER=1]="RECORDER",s[s.LIVESTREAMER=2]="LIVESTREAMER"})(nh||(nh={}));var ah;(function(s){s[s.PEERS=0]="PEERS",s[s.ROOMS=1]="ROOMS"})(ah||(ah={}));var xd;(function(s){s[s.HIVE=0]="HIVE",s[s.CHAT=1]="CHAT",s[s.PING=2]="PING"})(xd||(xd={}));class Kk 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 zk=new Kk;class Yk 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",nr,"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:()=>zk}])}}const Ud=new Yk;class Qk extends v{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>Ud}])}}const Nn=new Qk;class Xk 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",nr,"STAGE_TYPE_"]}])}}const Qm=new Xk;class Zk 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 eI=new Zk;class tI extends v{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>Ud}])}}const oh=new tI;class sI extends v{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const Xm=new sI;class rI 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:()=>nI},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const Zm=new rI;class iI 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",Pi]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const nI=new iI;class aI extends v{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>Zm}])}}const ef=new aI;class oI extends v{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const tf=new oI;class cI 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 cI;class dI extends v{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Ud},{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",xd,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const lI=new dI;class uI extends v{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Ud},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const hI=new uI;class pI extends v{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>Zm}])}}new pI;class gI extends v{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new gI;class mI 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 ch=new mI;class fI 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 SI=new fI;class vI 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:()=>SI}])}}const sf=new vI;class TI extends v{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>sf},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>sf}])}}const yI=new TI;class EI extends v{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const bI=new EI;class wI extends v{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>bI}])}}const PI=new wI;class _I 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:()=>ch}])}}const RI=new _I;class CI extends v{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>RI}])}}const rf=new CI;class kI 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 II=new kI;class AI extends v{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>II}])}}new AI;class MI extends v{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const OI=new MI;class DI extends v{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>OI}])}}const NI=new DI;class VI extends v{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>UI}])}}const LI=new VI;class xI 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:()=>ch}])}}const UI=new xI;class FI 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 $I=new FI;class BI 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:()=>$I}])}}const HI=new BI;class qI 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:()=>ch}])}}const nf=new qI;class jI extends v{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>nf}])}}new jI;class GI 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 WI=new GI;class JI extends v{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>YI}])}}const KI=new JI;class zI 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 YI=new zI;class QI extends v{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const af=new QI;class XI 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",ah,"BROADCAST_TYPE_"]}])}}const mo=new XI;class ZI extends v{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const eA=new ZI;class tA extends v{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const sA=new tA;class rA 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 iA=new rA;class nA extends v{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>iA}])}}const of=new nA;class aA 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 cf=new aA;var dh;(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"})(dh||(dh={}));var xr;(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"})(xr||(xr={}));class oA 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 cA=new oA;class dA 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 lA=new dA;class uA 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 hA=new uA;class pA 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 gA=new pA;class mA extends v{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>hA},{no:2,name:"private",kind:"message",T:()=>gA}])}}const fA=new mA;class SA 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 vA=new SA;class TA extends v{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",xr,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",xr,"STREAM_PERMISSION_TYPE_"]}])}}const lh=new TA;class yA extends v{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>lh},{no:2,name:"audio",kind:"message",T:()=>lh},{no:3,name:"screenshare",kind:"message",T:()=>lh}])}}const EA=new yA;class bA extends v{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>cA},{no:2,name:"plugins",kind:"message",T:()=>lA},{no:3,name:"chat",kind:"message",T:()=>fA},{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",dh,"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",nh,"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:()=>vA},{no:23,name:"media",kind:"message",T:()=>EA}])}}const uh=new bA;class wA extends v{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const PA=new wA;class _A 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 _A;class CA extends v{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>RA}])}}const kA=new CA;class IA extends v{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>uh}])}}const df=new IA;class AA extends v{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>df}])}}const MA=new AA;class OA extends v{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>df}])}}const lf=new OA;class DA 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 NA=new DA;class VA extends v{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>NA},{no:2,name:"patch",kind:"message",T:()=>uh}])}}new VA;class LA extends v{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>uh}])}}new LA;class xA 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 Ur=new xA;class UA 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 UA;class $A 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 BA=new $A;class HA extends v{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Ur},{no:2,name:"next",kind:"scalar",T:8}])}}const qA=new HA;class jA extends v{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Ur}])}}const uf=new jA;class GA 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 GA;class JA extends v{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>Ur}])}}const hh=new JA;class KA 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 zA=new KA;class YA extends v{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>Ur}])}}const ph=new YA;class QA 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 QA;class XA extends v{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>Ur}])}}new XA;class ZA 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 e0=new ZA;class t0 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 s0=new t0;class r0 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:()=>Ur}])}}const Fd=new r0;class i0 extends v{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>Ur}])}}const $d=new i0;class n0 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 a0=new n0;class o0 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 Bd=new o0;class c0 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 d0=new c0;class l0 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 l0;class u0 extends v{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}new u0;class h0 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 h0;class p0 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 p0;class g0 extends v{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new g0;class m0 extends v{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new m0;class f0 extends v{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>Ur},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const S0=new f0;class v0 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:()=>S0},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const T0=new v0;class y0 extends v{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>T0}])}}new y0;class E0 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 b0=new E0;class w0 extends v{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>b0}])}}new w0;class P0 extends v{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const _0=new P0;class R0 extends v{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const C0=new R0;class k0 extends v{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const I0=new k0;class A0 extends v{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const M0=new A0;class O0 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}])}}const D0=new O0;class N0 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}])}}const V0=new N0;class L0 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}])}}const x0=new L0;class U0 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}])}}const F0=new U0;class $0 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 gh=new $0;class B0 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:()=>gh}])}}const hf=new B0;class H0 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:()=>gh}])}}const q0=new H0;class j0 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:()=>gh}])}}const G0=new j0;class W0 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}])}}const J0=new W0;class K0 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 mh=new K0;class z0 extends v{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>mh}])}}const Y0=new z0;class Q0 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}])}}const pf=new Q0;class X0 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 Z0=new X0;class eM 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:()=>Z0}])}}const gf=new eM;class tM 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}])}}const mf=new tM;class sM 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 ff=new sM;class rM extends v{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const Sf=new rM;class iM 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 nM=new iM;class aM extends v{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>nM}])}}const fh=new aM;class oM extends v{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const cM=new oM;class dM extends v{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const lM=new dM;class uM extends v{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const vf=new uM;class hM 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:()=>gM},{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 Tf=new hM;class pM 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:()=>fM}])}}const gM=new pM;class mM 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 fM=new mM;class SM 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 vM=new SM;class TM 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 yM=new TM;class EM extends v{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>Tf}])}}const Sh=new EM;class bM extends v{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>Tf}])}}const wM=new bM;class PM 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",Pi]}])}}const yf=new PM;class _M 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=ge.from(Math.floor(e/1e3)).toBigInt(),t.nanos=e%1e3*1e6,t}toDate(t){return new Date(ge.from(t.seconds).toNumber()*1e3+Math.ceil(t.nanos/1e6))}fromDate(t){const e=this.create(),r=t.getTime();return e.seconds=ge.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}internalJsonWrite(t,e){let r=ge.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 "+zu(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=ge.from(n/1e3).toBigInt(),r.nanos=0,i[7]&&(r.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),r}}new _M;class RM 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 vh=new RM;class CM extends v{constructor(){super("common.BulkedHubMessage",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>vh}])}}new CM;class kM extends v{constructor(){super("common.CFWorkersResponse",[{no:1,name:"responses",kind:"message",repeat:1,T:()=>vh},{no:2,name:"broadcast_responses",kind:"message",repeat:1,T:()=>vh}])}}new kM;const IM=0,AM=1,MM=2,OM=3,DM=5,NM={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},VM={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,searchChannelMessages:7,pinMessage:10},LM={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},xM={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},Ef={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},UM={getUserPresets:0,updateUserPreset:1};function fo(s,t){return Object.keys(t).reduce((e,r)=>(e[r]=(s<<16)+t[r],e),{})}function bf(s,t){return Object.keys(s).reduce((e,r)=>(e[r]=t|s[r],e),{})}const U=fo(IM,NM),Ge=fo(AM,VM),G=fo(MM,LM),ar=fo(OM,xM),Fr=bf(Ef,16777216),ys=bf(Ef,50331648),Hd=fo(DM,UM);var FM=Object.defineProperty,$M=Object.getOwnPropertyDescriptor,$r=(s,t,e,r)=>{for(var i=r>1?void 0:r?$M(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&&FM(t,e,i),i},rs=(s=>(s[s.TEXT=0]="TEXT",s[s.IMAGE=1]="IMAGE",s[s.FILE=2]="FILE",s[s.CUSTOM=3]="CUSTOM",s))(rs||{});class or{constructor(t,e){m(this,Wt,void 0);m(this,Yn,void 0);f(this,Wt,e),f(this,Yn,t)}get telemetry(){return a(this,Yn).getValue("telemetry")}get logger(){return a(this,Yn).getValue("logger")}getChatMessages(){return a(this,Wt).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,Wt).sendMessagePromise(Ge.getPaginatedMessages,BA.toBinary(n));return o.payload?qA.fromBinary(o.payload):{messages:[],next:!1}}sendMessageToRoom(t,e){const r={payloadType:e,payload:t};a(this,Wt).sendMessage(Ge.sendMessageToRoom,WA.toBinary(r))}sendMessageToPeers(t,e,r){const i={payloadType:e,peerIds:r,payload:t};a(this,Wt).sendMessage(Ge.sendMessageToPeers,zA.toBinary(i))}sendMessage(t,e,r){if(r&&r.length>0){this.sendMessageToPeers(t,e,r);return}this.sendMessageToRoom(t,e)}async editMessage(t,e,r,i){const n={chatId:t,payloadType:r,payload:e};i!==void 0&&(n.pinned=i);const o=await a(this,Wt).sendMessagePromise(Ge.editMessage,e0.toBinary(n));return $d.fromBinary(o.payload).message}async deleteMessage(t){const e={chatId:t},r=await a(this,Wt).sendMessagePromise(Ge.deleteMessage,a0.toBinary(e));return{id:Bd.fromBinary(r.payload).chatId}}async searchMessages(t,e){var i,n,o,c;const r={searchTerm:t,timeStamp:(i=e.timestamp)!=null?i:Date.now(),size:(n=e.limit)!=null?n:75,from:(o=e.offset)!=null?o:0,reversed:(c=e.reversed)!=null?c:!0};try{const d=await a(this,Wt).sendMessagePromise(Ge.searchChannelMessages,d0.toBinary(r));return uf.fromBinary(d.payload).messages}catch(d){return[]}}async setPinState(t,e){const r={chatId:t,pinned:e},i=await a(this,Wt).sendMessagePromise(Ge.pinMessage,s0.toBinary(r));return Fd.fromBinary(i.payload)}on(t,e){let r,i;switch(t){case Ge.sendMessageToRoom:{r=hh.fromBinary.bind(hh),i=hh.create();break}case Ge.sendMessageToPeers:{r=ph.fromBinary.bind(ph),i=ph.create();break}case Ge.editMessage:{r=$d.fromBinary.bind($d),i=$d.create();break}case Ge.pinMessage:{r=Fd.fromBinary.bind(Fd),i=Fd.create();break}case Ge.deleteMessage:{r=Bd.fromBinary.bind(Bd),i=Bd.create();break}}if(!r){this.logger.warn(`ChatSocketHandler::Event ${t} is not recognized`);return}a(this,Wt).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}Wt=new WeakMap,Yn=new WeakMap,$r([E.trace("SocketService.getChatMessages")],or.prototype,"getChatMessages",1),$r([E.trace("SocketService.getChatMessagesPaginated")],or.prototype,"getChatMessagesPaginated",1),$r([E.trace("SocketService.sendMessageToRoom")],or.prototype,"sendMessageToRoom",1),$r([E.trace("SocketService.sendMessageToPeers")],or.prototype,"sendMessageToPeers",1),$r([E.trace("SocketService.sendMessage")],or.prototype,"sendMessage",1),$r([E.trace("SocketService.editMessage")],or.prototype,"editMessage",1),$r([E.trace("SocketService.deleteMessage")],or.prototype,"deleteMessage",1),$r([E.trace("SocketService.searchMessages")],or.prototype,"searchMessages",1);function BM(s){return s.replace(/([-_]\w)/g,t=>t[1].toUpperCase())}function Hs(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>Hs(e));const t={};return Object.keys(s).forEach(e=>{const r=vu(e)?e:BM(e);t[r]=Hs(s[e])}),t}function HM(s){return s.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function wf(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>wf(e));const t={};return Object.keys(s).forEach(e=>{const r=vu(e)?e:HM(e);t[r]=s[e]}),t}function qd(s,t={}){return s==null?{}:(Object.getOwnPropertyNames(s).forEach(e=>{if(typeof s[e]!="function"){if(typeof s[e]=="object"){qd(s[e],t[e]={});return}t[e]=s[e]}}),t)}class Pf{constructor(t){p(this,"defaults");this.defaults={baseURL:t.baseURL,headers:{common:{}},timeout:t.timeout,retry:t.retry,retryDelay:t.retryDelay}}buildURL(t,e){const{baseURL:r}=this.defaults,i=t.startsWith("http")?t:`${r}${t.startsWith("/")?t:`/${t}`}`;if(e){const n=new URLSearchParams;return Object.entries(e).forEach(([o,c])=>{n.append(o,c)}),`${i}${i.includes("?")?"&":"?"}${n.toString()}`}return i}async request(t){var h;const e=((h=t.method)==null?void 0:h.toUpperCase())||"GET",r=this.buildURL(t.url||"",t.params),i={...this.defaults.headers.common,...t.headers};e!=="GET"&&e!=="HEAD"&&t.data&&!i["Content-Type"]&&(i["Content-Type"]="application/json");const o=i["Content-Type"]==="application/json"?JSON.stringify(t.data):t.data,c={method:e,headers:i,body:e!=="GET"&&e!=="HEAD"&&t.data?o:void 0},d=t.timeout||this.defaults.timeout,l=t.retry!==void 0?t.retry:this.defaults.retry,u=t.retryDelay||this.defaults.retryDelay;try{const g=new AbortController,S=setTimeout(()=>g.abort(),d);c.signal=g.signal;const y=await fetch(r,c);clearTimeout(S);let w=null;const b=y.headers.get("content-type");b&&b.includes("application/json")?w=await y.json():w=await y.text();const C={};y.headers.forEach((F,L)=>{C[L]=F});const D={data:w,status:y.status,statusText:y.statusText,headers:C,config:t};if(!y.ok)throw D;return D}catch(g){if(g instanceof Error&&l>0)return await new Promise(S=>setTimeout(S,u)),this.defaults.baseURL===wi.apiBase.prod?this.defaults.baseURL=wi.apiBase.prodAlternate:this.defaults.baseURL===wi.apiBase.prodAlternate&&(this.defaults.baseURL=wi.apiBase.prod),this.request({...t,retry:l-1});throw g}}async get(t,e={}){return this.request({...e,method:"GET",url:t})}async post(t,e,r={}){return this.request({...r,method:"POST",url:t,data:e})}async put(t,e,r={}){return this.request({...r,method:"PUT",url:t,data:e})}}const qM=3,jM=30,GM=8e3;class WM{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,"pluginInformation");p(this,"userDetails");p(this,"roomDetails");p(this,"context");this.context=t;const{timeout:r=GM,retry:i=qM,retryDelay:n=jM,baseURL:o=wi.apiBase.prod,authToken:c,cachedUserDetails:d}=e||{};this.iceServers=d==null?void 0:d.iceServers,this.pluginInformation=d==null?void 0:d.pluginInformation,this.userDetails=d==null?void 0:d.userDetails,this.roomDetails=d==null?void 0:d.roomDetails,this.requests=new Pf({baseURL:o,timeout:r,retry:i,retryDelay:n,responseType:"json"}),this.fetchClient=new Pf({baseURL:"",timeout:r,retry:i,retryDelay:n,responseType:"json"}),this.setAuthToken(c,{bearer:!0});const l=this.requests.request.bind(this.requests);this.requests.request=async u=>{var g,S,y,w,b;const h=t.getValue("telemetry");try{h.injectContext(this.requests.defaults.headers.common);const C=await l(u);return u.url!==h.logsEndpoint&&this.logger.debug("xhr::fetch",{networkCall:{status:C.status,statusText:C.statusText,baseURL:u.baseURL||this.requests.defaults.baseURL,url:u.url,method:u.method}}),C}catch(C){throw C?(((g=C.config)==null?void 0:g.url)!==h.logsEndpoint&&this.logger.error("xhr::fetch",{error:C,networkCall:{status:C.status,statusText:C.statusText,baseURL:((S=C.config)==null?void 0:S.baseURL)||this.requests.defaults.baseURL,url:(y=C.config)==null?void 0:y.url,retries:(w=C.config)==null?void 0:w.retry,method:(b=C.config)==null?void 0:b.method,isOnline:navigator.onLine?"online":"offline"}}),new k(C.message||"Network request failed","0011")):new k("Unknown network error occurred","0011")}}}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 JM=Object.defineProperty,KM=Object.getOwnPropertyDescriptor,qs=(s,t,e,r)=>{for(var i=r>1?void 0:r?KM(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&&JM(t,e,i),i};class Es extends WM{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 getPlugins(){var n,o,c,d,l,u,h;if(this.pluginInformation)return this.pluginInformation;const{plugins:e}=(await this.requests.get("/v2/plugins/user")).data.data,r=((o=(n=this.context.getValue("flagsmith").getValue(Z.V1_PLUGINS))==null?void 0:n.toString())==null?void 0:o.split(","))||[],i=e.reduce((g,S)=>(g[r.includes(S.id)?"v1":"v2"].push({...S,name:S.name.replace("v2","")}),g),{v1:[],v2:[]});return(l=(d=(c=this.context.getValue("modules"))==null?void 0:c.devTools)==null?void 0:d.plugins)!=null&&l.length&&((h=(u=this.context.getValue("modules"))==null?void 0:u.devTools)==null||h.plugins.forEach(g=>{var y,w,b;const S={...ho,tags:[...ho.tags],baseUrl:`http://localhost:${g.port}`,name:g.name,picture:(y=g.picture)!=null?y:ho.picture,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),id:g.id,organizationId:this.organizationId,description:(w=g.description)!=null?w:ho.description,staggered:(b=g.staggered)!=null?b:ho.staggered};i.v2.push(S)})),i.v2}async getPluginDetails(e){const{plugin:r}=(await this.requests.get(`/v2/plugins/view/${e}`)).data.data;return r}async getPluginConfig(e){return(await this.fetchClient.get(`${e}/dyte-config.json`)).data}async authorizePlugin(e){const r={peerId:this.peerId},{token:i}=(await this.requests.post(`/v2/plugins/authorize/${e}`,r)).data.data;return i}async getPresignedUrls(e){const r=On(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=Hs(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=Hs((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 Hs(e)}async startRecording(e,r){return(await this.requests.post("/v2/recordings",{...wf(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 k("Cant fetch transcript s3 url","1801")}}}qs([E.trace("APIClient.getICEServers")],Es.prototype,"getICEServers",1),qs([E.trace("APIClient.getPlugins")],Es.prototype,"getPlugins",1),qs([E.trace("APIClient.startLivestreaming")],Es.prototype,"startLivestreaming",1),qs([E.trace("APIClient.stopLivestreaming")],Es.prototype,"stopLivestreaming",1),qs([E.trace("APIClient.getActiveLivestream")],Es.prototype,"getActiveLivestream",1),qs([E.trace("APIClient.getUserDetails")],Es.prototype,"getUserDetails",1),qs([E.trace("APIClient.startRecording")],Es.prototype,"startRecording",1),qs([E.trace("APIClient.stopRecording")],Es.prototype,"updateRecording",1),qs([E.trace("APIClient.getActiveRecording")],Es.prototype,"getActiveRecording",1),qs([E.trace("APIClient.getActiveTranscript")],Es.prototype,"getActiveTranscript",1);let Th;function zM(s,t){return Th=new Es(s,t),Th}function yt(){return Th}const Vn={maxInvocations:5,period:1};function Ot(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 k(`Method rate limit ${u.maxInvocations} invocations/${u.period}sec exceeded`,"0013");return o+=1,n.apply(this,d)},i}}var YM=Object.defineProperty,QM=Object.getOwnPropertyDescriptor,bs=(s,t,e,r)=>{for(var i=r>1?void 0:r?QM(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&&YM(t,e,i),i};const XM=["text","image","file","custom","poll"],jd={maxInvocations:180,period:60};let Bt=(VS=class extends $t{constructor(t,e,r,i){const n=t.getValue("logger");super(n);m(this,El);m(this,Vo);p(this,"messages");m(this,te,void 0);m(this,Ui,void 0);m(this,tt,void 0);m(this,Qn,void 0);p(this,"maxTextLimit",2e3);f(this,Qn,t),f(this,tt,e),f(this,te,r),f(this,Ui,i),this.messages=[]}get telemetry(){return a(this,Qn).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 k("Max character limit breached","0503");if(e&&e.length>0){if(!((i=a(this,te).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,te).permissions)!=null&&n.chatPrivate.text))throw this.logger.error("sendTextMessage::private_chat_permission_denied"),new k("Could not send message to private chat.","0501")}else if(!((c=(o=a(this,te).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,te).permissions)==null?void 0:d.chatPublic)!=null&&l.text))throw this.logger.error("sendTextMessage::public_chat_permission_denied"),new k("Could not send message to public chat.","0501");if(!t)throw this.logger.error("sendTextMessage::message_can_not_be_empty"),new k("Message can not be empty.","0502");let r=[];e&&e.length>0&&(e.push(a(this,te).id),r=a(this,Ui).joined.toArray().filter(u=>e.includes(u.id)).map(u=>u.userId),r.push(a(this,te).userId)),a(this,tt).sendMessage(t,rs.TEXT,e)}async sendImageMessageInternal(t,e){var i,n,o,c,d,l;if(e&&e.length>0){if(!((i=a(this,te).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,te).permissions)!=null&&n.chatPrivate.files)){this.logger.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((c=(o=a(this,te).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,te).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=yt(),{getLocation:h,putLocation:g}=await u.getPresignedUrls(t.name);await u.uploadFile(t,g);let S=[];e&&e.length>0&&(e.push(a(this,te).id),S=a(this,Ui).joined.toArray().filter(y=>e.includes(y.id)).map(y=>y.userId),S.push(a(this,te).userId)),a(this,tt).sendMessage(h,rs.IMAGE,e)}catch(u){throw new k("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,te).permissions)!=null&&r.chatPrivate.canSend)||!((i=a(this,te).permissions)!=null&&i.chatPrivate.files)){this.logger.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((o=(n=a(this,te).permissions)==null?void 0:n.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,te).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=yt(),{getLocation:u,putLocation:h}=await l.getPresignedUrls(t.name);await l.uploadFile(t,h);let g=[];e&&e.length>0&&(e.push(a(this,te).id),g=a(this,Ui).joined.toArray().filter(y=>e.includes(y.id)).map(y=>y.userId),g.push(a(this,te).userId));const S=JSON.stringify({link:u,name:t.name,size:"size"in t?t.size:0});a(this,tt).sendMessage(S,rs.FILE,e)}catch(l){throw new k("Error sending file message.","0500",this.logger)}}get rateLimits(){return jd}updateRateLimits(t,e){jd.maxInvocations=t,jd.period=e}async sendTextMessage(t,e){return this.sendTextMessageInternal(t,e)}async sendCustomMessage(t,e){var n,o,c,d,l,u,h,g,S,y,w,b,C,D,F;if(e&&e.length>0){if(!((n=a(this,te).permissions)!=null&&n.chatPrivate.canSend)||!((o=a(this,te).permissions)!=null&&o.chatPrivate.files)||!((c=a(this,te).permissions)!=null&&c.chatPrivate.text)){this.logger.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((l=(d=a(this,te).permissions)==null?void 0:d.chatPublic)!=null&&l.canSend)||!((h=(u=a(this,te).permissions)==null?void 0:u.chatPublic)!=null&&h.files)||!((S=(g=a(this,te).permissions)==null?void 0:g.chatPublic)!=null&&S.text)){this.logger.error("sendCustomMessage::permission_denied");return}const r=async L=>{try{if(typeof L=="string")return{link:L};const B=yt(),{getLocation:Q,putLocation:se}=await B.getPresignedUrls(L.name);return await B.uploadFile(L,se),{link:Q,type:L.type,name:L.name,size:L.size}}catch(B){throw new k("Error sending image message.","0500",this.logger)}},i={...t,files:await Promise.all((w=(y=t.files)!=null?y:[])==null?void 0:w.map(async L=>r(L))),images:await Promise.all((C=(b=t.images)!=null?b:[])==null?void 0:C.map(async L=>r(L))),videos:await Promise.all((F=(D=t.videos)!=null?D:[])==null?void 0:F.map(async L=>r(L)))};a(this,tt).sendMessage(JSON.stringify(i),rs.CUSTOM,e)}async sendImageMessage(t,e){return this.sendImageMessageInternal(t,e)}async sendFileMessage(t,e){return this.sendFileMessageInternal(t,e)}async sendMessage(t,e){return this.sendMessageInternal(t,e)}async editTextMessage(t,e){var r,i,n,o;if(!((i=(r=a(this,te).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(n=a(this,te).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,tt).editMessage(t,e,rs.TEXT)}async editImageMessage(t,e){var i,n,o,c;if(!((n=(i=a(this,te).permissions)==null?void 0:i.chatPublic)!=null&&n.canSend)||!((c=(o=a(this,te).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=yt(),{getLocation:l,putLocation:u}=await d.getPresignedUrls(e.name);await d.uploadFile(e,u),a(this,tt).editMessage(t,l,rs.IMAGE)}catch(d){throw new k("Error editing image message.","0500",this.logger)}}async editFileMessage(t,e){var r,i,n,o;if(!((i=(r=a(this,te).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(n=a(this,te).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=yt(),{getLocation:d,putLocation:l}=await c.getPresignedUrls(e.name);await c.uploadFile(e,l),a(this,tt).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),rs.FILE)}catch(c){throw new k("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,tt).deleteMessage(t)}getMessagesByUser(t){return this.messages.filter(e=>e.userId===t)}getMessagesByType(t){return this.messages.filter(e=>e.type===t)}async pin(t){if(!a(this,Vo,tp))throw new k("Can`t pin message without joining room","0505");try{await a(this,tt).setPinState(t,!0)}catch(e){throw new k(`No message found with id: ${t}`,"0504")}}async unpin(t){if(!a(this,Vo,tp))throw new k("Can`t unpin message without joining room","0505");try{await a(this,tt).setPinState(t,!1)}catch(e){throw new k(`No message found with id: ${t}`,"0504")}}async fetchPublicMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await a(this,tt).getChatMessagesPaginated(t,e,r==="before")).messages.map(o=>is.formatSocketPeerMessage(o))}async fetchPrivateMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after",userId:i}){return(await a(this,tt).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"userId",userId:i})).messages.map(c=>is.formatSocketPeerMessage(c))}async fetchPinnedMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await a(this,tt).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"pinned",pinned:!0})).messages.map(o=>is.formatSocketPeerMessage(o))}async getMessages(t,e,r,i=0){const n=await a(this,tt).getChatMessagesPaginated(t,e,r);return{messages:n.messages.map(o=>is.formatSocketPeerMessage(o)),next:n.next}}async searchMessages(t,e){throw new k("searchMessages is disabled! Please use `fetchPublicMessages` method instead.","0506")}get pinned(){return this.messages.filter(t=>t.pinned)}},te=new WeakMap,Ui=new WeakMap,tt=new WeakMap,Qn=new WeakMap,El=new WeakSet,ev=function(){return a(this,Qn).getValue("connectionHandler")},Vo=new WeakSet,tp=function(){return a(this,El,ev).socketJoined===!0},VS);bs([E.trace("Chat.sendTextMessage"),Ot(jd)],Bt.prototype,"sendTextMessage",1),bs([E.trace("Chat.sendImageMessage"),Ot({maxInvocations:20,period:60})],Bt.prototype,"sendImageMessage",1),bs([E.trace("Chat.sendFileMessage"),Ot({maxInvocations:20,period:60})],Bt.prototype,"sendFileMessage",1),bs([E.trace("Chat.sendMessage"),Ot({maxInvocations:180,period:60})],Bt.prototype,"sendMessage",1),bs([E.trace("Chat.editTextMessage")],Bt.prototype,"editTextMessage",1),bs([E.trace("Chat.editImageMessage")],Bt.prototype,"editImageMessage",1),bs([E.trace("Chat.editFileMessage")],Bt.prototype,"editFileMessage",1),bs([E.trace("Chat.editMessage")],Bt.prototype,"editMessage",1),bs([E.trace("Chat.deleteMessage")],Bt.prototype,"deleteMessage",1),bs([E.trace("Chat.searchMessages")],Bt.prototype,"searchMessages",1),Bt=bs([ut("0500")],Bt);var ZM=Object.defineProperty,eO=Object.getOwnPropertyDescriptor,tO=(s,t,e,r)=>{for(var i=r>1?void 0:r?eO(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&&ZM(t,e,i),i};const Br=(LS=class{constructor(s,t,e,r){p(this,"chat");p(this,"chatSocketHandler");p(this,"self");m(this,Fi,void 0);f(this,Fi,s),this.chatSocketHandler=t,this.chat=new Bt(s,t,e,r),this.self=e,this.setupEvents()}get telemetry(){return a(this,Fi).getValue("telemetry")}get logger(){return a(this,Fi).getValue("logger")}static async init(s,t,e,r){return new Br(s,t,e,r)}static formatMessage(s){return{...s,time:new Date(s.time),type:XM[s.type]}}static formatSocketPeerMessage(s){const t=s.createdAt*1e3,e={displayName:s.displayName,id:s.chatId,time:t,timeMs:s.createdAtMs,type:s.payloadType,isEdited:s.isEdited,userId:s.userId,targetUserIds:s.targetUserIds,message:"",link:"",name:"",html:"",images:[],videos:[],files:[],size:0,pinned:s.pinned};switch(e.type){case rs.TEXT:{e.message=s.payload;break}case rs.IMAGE:{e.link=s.payload;break}case rs.FILE:{const{link:r,name:i,size:n}=JSON.parse(s.payload);e.link=r,e.name=i,e.size=n;break}case rs.CUSTOM:{const{html:r,images:i,message:n,videos:o,files:c}=JSON.parse(s.payload);e.message=n,e.html=r,e.images=i,e.videos=o,e.files=c;break}}return Br.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=uf.fromBinary(s.payload).messages;this.chat.messages=t.map(e=>Br.formatSocketPeerMessage(e))}setupEvents(){a(this,Fi).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,async()=>{this.getChatMessages()}),this.chatSocketHandler.on(Ge.sendMessageToRoom,s=>{if(!s.message)return;const t=Br.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=Br.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=Br.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=Br.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})})}},Fi=new WeakMap,LS);let is=Br;tO([E.trace("ChatController.setupEvents")],is.prototype,"setupEvents",1);var sO=Object.defineProperty,rO=Object.getOwnPropertyDescriptor,iO=(s,t,e,r)=>{for(var i=r>1?void 0:r?rO(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};let yh=(xS=class extends $t{constructor(t,e,r){const i=t.getValue("logger");super(i);m(this,bl);m(this,wl);p(this,"items");m(this,Xn,void 0);m(this,Zn,void 0);m(this,Lo,void 0);f(this,Lo,t),f(this,Xn,e),f(this,Zn,r),this.items=[]}async create(t,e,r=!1,i=!1){if(!a(this,wl,sv))throw new k("Can't create polls without joining room","0705");if(!a(this,Xn).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,Zn).createPoll(t,e,r,i)}async vote(t,e){if(!a(this,Xn).permissions.polls.canVote){this.logger.error("Polls::vote::permission_denied");return}await a(this,Zn).votePoll(t,e)}},bl=new WeakSet,tv=function(){return a(this,Lo).getValue("connectionHandler")},wl=new WeakSet,sv=function(){var t;return((t=a(this,bl,tv))==null?void 0:t.socketJoined)===!0},Xn=new WeakMap,Zn=new WeakMap,Lo=new WeakMap,xS);yh=iO([ut("0700")],yh);var nO=Object.defineProperty,aO=Object.getOwnPropertyDescriptor,oO=(s,t,e,r)=>{for(var i=r>1?void 0:r?aO(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};const Ln=(US=class{constructor(s,t,e){p(this,"polls");m(this,Yr,void 0);m(this,ea,void 0);m(this,$i,void 0);this.polls=new yh(s,t,e),f(this,ea,t),f(this,Yr,s),f(this,$i,e),this.setupEvents()}get telemetry(){return a(this,Yr).getValue("telemetry")}get logger(){return a(this,Yr).getValue("logger")}static async init(s,t,e){return new Ln(s,t,e)}canViewPolls(){return a(this,ea).permissions.polls.canView}setupEvents(){const s={[ar.createPoll]:r=>{r.poll&&this.updatePoll(Ln.formatSocketServicePoll(r.poll))},[ar.updatePoll]:r=>{r.poll&&this.updatePoll(Ln.formatSocketServicePoll(r.poll))},[ar.votePoll]:r=>{r.poll&&this.updatePoll(Ln.formatSocketServicePoll(r.poll))}},t=()=>{a(this,Yr).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,Yr).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,$i).removeListeners(r)})};a(this,ea).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=>Ln.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}}},Yr=new WeakMap,ea=new WeakMap,$i=new WeakMap,US);let _f=Ln;oO([E.trace("PollController.setupEvents")],_f.prototype,"setupEvents",1);var cO=Object.defineProperty,dO=Object.getOwnPropertyDescriptor,lO=(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},Rf=(s=>(s[s.User=0]="User",s[s.Meeting=1]="Meeting",s))(Rf||{});let Eh=(FS=class extends $t{constructor(t,e,r,i,n){const o=t.getValue("logger");super(o);m(this,xo);p(this,"selfActiveTab");p(this,"broadcastTabChanges");m(this,ta,void 0);m(this,Bi,void 0);m(this,Uo,void 0);p(this,"viewType");p(this,"meetingStartedTimestamp");p(this,"meetingTitle");p(this,"sessionId");f(this,ta,t),f(this,Bi,e),this.viewType=r,f(this,Uo,i),this.meetingTitle=n,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return a(this,xo,sp).socketState}get mediaState(){return a(this,xo,sp).mediaState}get meetingId(){return a(this,ta).getValue("meetingId")}setBroadcastTabChanges(t){if(!a(this,Bi).permissions.canSpotlight)throw this.logger.error("Spotlight::setSpotlighted::permission_denied"),new k("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,Uo).broadcastMessage("spotlight",{userId:a(this,Bi).userId,currentTab:this.selfActiveTab})}},ta=new WeakMap,xo=new WeakSet,sp=function(){return a(this,ta).getValue("connectionHandler")},Bi=new WeakMap,Uo=new WeakMap,FS);Eh=lO([ut("0800")],Eh);function uO(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===`
|
|
12
|
+
`&&o?(t==="\r"&&(e[i]=e[i].slice(0,-1)),e=r[++n]=[c=""],i=0):e[i]+=c,t=c;return r}var hO=Object.defineProperty,pO=Object.getOwnPropertyDescriptor,Cf=(s,t,e,r)=>{for(var i=r>1?void 0:r?pO(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&&hO(t,e,i),i};let Hr=($S=class extends $t{constructor(t){const e=t.getValue("logger");super(e);p(this,"transcripts");m(this,Fo,void 0);f(this,Fo,t),this.transcripts=[]}get telemetry(){return a(this,Fo).getValue("telemetry")}static async init(t,e){const r=new Hr(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]]=uO(t);return{id:fi(),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(`
|
|
13
|
+
`).map(e=>Hr.parseTranscript(e,!1)).filter(Boolean):[]}async getActiveTranscript(){try{const t=yt(),{transcript:e}=await t.getActiveTranscript();this.transcripts=Hr.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)}},Fo=new WeakMap,$S);Cf([E.trace("Ai.getActiveTranscript")],Hr.prototype,"getActiveTranscript",1),Hr=Cf([ut("0000")],Hr);var gO=Object.defineProperty,mO=Object.getOwnPropertyDescriptor,fO=(s,t,e,r)=>{for(var i=r>1?void 0:r?mO(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&&gO(t,e,i),i};const kf=(BS=class{constructor(s,t,e,r,i,n){p(this,"meta");p(this,"ai");m(this,Qr,void 0);m(this,sa,void 0);p(this,"aiSocketHandler");m(this,Jt,void 0);f(this,Jt,s),this.meta=new Eh(s,t,t.config.viewType,e,n),this.ai=r,f(this,Qr,t),f(this,sa,e),this.aiSocketHandler=i,this.setupEvents()}get telemetry(){return a(this,Jt).getValue("telemetry")}get logger(){return a(this,Jt).getValue("logger")}static async init(s,t,e,r,i){const n=await Hr.init(s,t.permissions.transcriptionEnabled);return new kf(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,Rf.Meeting),this.meta.emit("activeTabUpdate",s.currentTab))}setupEvents(){a(this,Jt).getValue("peerSessionStore").on(_.TRANSPORT_STATE_UPDATE,s=>{this.meta.emit("mediaConnectionUpdate",s)}),a(this,Jt).getValue("peerSessionStore").on(_.SOCKET_STATE_UPDATE,s=>{this.meta.emit("socketConnectionUpdate",s)}),a(this,Jt).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,Jt).getValue("peerSessionStore").on(_.PRODUCER_SCORE_UPDATE,({score:s})=>{s<5&&this.meta.emit("poorConnection",{score:s})}),a(this,Qr).permissions.canSpotlight&&(this.logger.info("MetaController::Asserting Spotlight"),this.meta.selfActiveTab&&a(this,sa).broadcastMessage("spotlight",{userId:a(this,Qr).userId,currentTab:this.meta.selfActiveTab})),a(this,Jt).getValue("peerSessionStore").on(_.PEER_JOINED_INTERNAL,async s=>{a(this,Qr).permissions.canSpotlight&&this.meta.selfActiveTab&&a(this,sa).broadcastToPeers("spotlight",[s.id],{userId:a(this,Qr).userId,currentTab:this.meta.selfActiveTab})}),a(this,Jt).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,Jt).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(U.transcript,s=>{const{meetingId:t,transcript:e,isPartial:r}=s;let i;try{i=Hr.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),this.meta.emit("transcript",i);const{peerId:n,name:o,transcript:c}=i;this.logger.debug(`${t} Received transcript for peer ${n} - ${o}: ${c}`)})}},Qr=new WeakMap,sa=new WeakMap,Jt=new WeakMap,BS);let If=kf;fO([E.trace("MetaController.setupEvents")],If.prototype,"setupEvents",1);const So={},cr={executeWithLock({methodName:s,lockName:t,timeout:e}){return(r,i,n)=>{const o=n.value;return n.value=function(...d){var y,w;const l=(w=(this==null?void 0:this.peerId)||((y=d[0])==null?void 0:y.authToken))!=null?w:"",u=`${t}-${l}`,h=this==null?void 0:this.logger;if(So[u]){const b=new Error(`Unsupported concurrent calls on method: ${s}.`);throw b.name="UnsupportedConcurrentMethodExecution",h==null||h.error("Locker::UnsupportedConcurrentMethodExecution",{error:{stack:b.stack},locker:{methodName:s,lockName:u}}),b}So[u]=!0;const g=setTimeout(()=>delete So[u],e),S=o.apply(this,d);return Promise.resolve(S).then(()=>{delete So[u],clearTimeout(g)}).catch(()=>{delete So[u],clearTimeout(g)}),S},n}}};var SO=Object.defineProperty,vO=Object.getOwnPropertyDescriptor,_i=(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};class qr extends $t{constructor(e,r,i,n,o){const c=e.getValue("logger");super(c);m(this,Bo);m(this,ra);m(this,os,void 0);m(this,Pl,void 0);m(this,ae,void 0);m(this,$o,void 0);m(this,js,void 0);m(this,st,void 0);f(this,st,e),f(this,os,n),f(this,Pl,o),f(this,ae,r),f(this,$o,i),f(this,js,[]),this.setupEvents()}get telemetry(){return a(this,st).getValue("telemetry")}get status(){return a(this,st).getValue("stageStatus")}setupEvents(){const e={[_.GET_STAGE_REQUESTS]:async n=>{f(this,js,n)},[_.UPDATE_STAGE_REQUESTS]:async({add:n})=>{const o=a(this,js).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,st).getValue("peerSessionStore").onAsync(n,o)})},i=()=>{Object.entries(e).forEach(([n,o])=>{a(this,st).getValue("peerSessionStore").removeListener(n,o)})};a(this,ae).permissions.on("permissionsUpdate",n=>{const{canAcceptProductionRequests:o}=n;o!==void 0&&(a(this,ae).permissions.acceptStageRequests?(r(),a(this,os).getStageRequests()):(i(),f(this,js,[]),this.emit("stageAccessRequestUpdate",a(this,js))))}),a(this,ae).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!a(this,ae).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new k("Stage is disabled","2003");if(!a(this,ae).permissions.acceptStageRequests)throw this.logger.error("Stage::get_access_request::permission_denied"),new k("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 f(this,js,e),{stageRequests:a(this,js)}}async requestAccess(){if(!a(this,ae).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new k("Stage is disabled","2003");if(this.status!=="OFF_STAGE")throw new k(`Unable to request access you are currently ${this.status}`,"2006");if(a(this,ae).permissions.stageAccess===H.Allowed){x(this,ra,pu).call(this,"ACCEPTED_TO_JOIN_STAGE");return}a(this,os).requestAccess(),x(this,ra,pu).call(this,"REQUESTED_TO_JOIN_STAGE")}async cancelRequestAccess(){if(!a(this,ae).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new k("Stage is disabled","2003");a(this,os).cancelRequestAccess(),x(this,ra,pu).call(this,"OFF_STAGE")}grantAccess(e){if(!a(this,ae).roomJoined)throw new k("Can`t grant for participant without joining room");if(!a(this,ae).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new k("Stage is disabled","2003");if(!a(this,ae).permissions.acceptStageRequests)throw this.logger.error("Stage::grant_access::permission_denied"),new k("You do not have permission to perform this action","2001");return a(this,os).grantAccess(e)}denyAccess(e){if(!a(this,ae).roomJoined)throw new k("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!a(this,ae).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new k("Stage is disabled","2003");if(!a(this,ae).permissions.acceptStageRequests)throw this.logger.error("Stage::deny_access::permission_denied"),new k("You do not have permission to perform this action","2001");return a(this,os).denyAccess(e)}get peerId(){return a(this,st).getValue("peerId")}async join(){const e=a(this,st).getValue("viewType");if(this.status==="ON_STAGE")throw new k("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||a(this,ae).permissions.stageAccess===H.NotAllowed)throw new k(`Unable to join stage you are currently ${this.status}`,"2006");if(a(this,st).setValue("stageStatus","ON_STAGE",!1),await a(this,os).joinStage(),e===tr.Livestream){await a(this,st).getValue("selfController").joinRoom();return}a(this,st).notify("stageStatus"),a(this,ae).audioEnabled&&a(this,Bo,rp).shareMic(a(this,ae).audioTrack),a(this,ae).videoEnabled&&a(this,Bo,rp).shareWebcam(a(this,ae).videoTrack)}async leave(){if(!a(this,ae).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new k("Stage is disabled","2003");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new k(`Unable to leave stage you are currently ${this.status}`,"2006");a(this,ae).setIsPinned(!1),a(this,st).setValue("stageStatus","OFF_STAGE",!1),await a(this,os).leaveStage(a(this,ae).userId);try{await a(this,st).getValue("peerSessionStore").emitAsync(_.LEAVE_MEDIA_ROOM,"stageLeft")}catch(e){this.logger.error("Stage::leave::emitAsync::failed",{error:e})}a(this,st).notify("stageStatus")}async kick(e){if(!a(this,ae).roomJoined)throw new k("Can`t kick participant without joining room","2005");if(!a(this,ae).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new k("Stage is disabled","2003");if(!a(this,ae).permissions.acceptStageRequests)throw this.logger.error("Stage::kick::permission_denied"),new k("You do not have permissions for kick","2001");return a(this,os).kick(e)}}os=new WeakMap,Pl=new WeakMap,ae=new WeakMap,$o=new WeakMap,js=new WeakMap,st=new WeakMap,Bo=new WeakSet,rp=function(){return a(this,st).getValue("roomNodeClient")},ra=new WeakSet,pu=async function(e){this.status!==e&&a(this,st).setValue("stageStatus",e)},_i([E.trace("Stage.getStageRequests")],qr.prototype,"getAccessRequests",1),_i([E.trace("Stage.requestAccess")],qr.prototype,"requestAccess",1),_i([E.trace("Stage.cancelRequestAccess")],qr.prototype,"cancelRequestAccess",1),_i([E.trace("Stage.grantAccess")],qr.prototype,"grantAccess",1),_i([E.trace("Stage.denyAccess")],qr.prototype,"denyAccess",1),_i([cr.executeWithLock({methodName:"joinStage",lockName:"Stage.join",timeout:5e3}),E.trace("Stage.joinStage")],qr.prototype,"join",1),_i([E.trace("Stage.leaveStage")],qr.prototype,"leave",1);function TO(s){return!(s.viewType==="LIVESTREAM"||s.viewType==="CHAT")}function bh(s){switch(s){case nr.UNSPECIFIED:return"OFF_STAGE";case nr.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case nr.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case nr.OFF_STAGE:return"OFF_STAGE";case nr.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var yO=Object.defineProperty,EO=Object.getOwnPropertyDescriptor,bO=(s,t,e,r)=>{for(var i=r>1?void 0:r?EO(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&&yO(t,e,i),i};class Af{constructor(t,e,r,i,n){p(this,"stage");m(this,Xr,void 0);m(this,Rs,void 0);m(this,Zr,void 0);m(this,Ho,0);m(this,Pt,void 0);f(this,Pt,t),this.stage=new qr(t,i,n,e,r),f(this,Zr,e),f(this,Xr,i),f(this,Rs,n),this.setupEvents()}get telemetry(){return a(this,Pt).getValue("telemetry")}get logger(){return a(this,Pt).getValue("logger")}setupEvents(){a(this,Pt).subscribe("stageStatus",t=>{this.stage.emit("stageStatusUpdate",t)}),a(this,Zr).on(U.grantStageAccess,()=>{a(this,Xr).permissions.stageAccess!==H.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),a(this,Zr).on(U.peerStageStatusUpdate,t=>{t!==void 0&&(t.peerId===a(this,Xr).id?this.selfStageStatusHandler(t):this.peerStageStatusHandler(t))}),a(this,Zr).on(U.denyStageAccess,()=>{a(this,Xr).permissions.stageAccess!==H.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),a(this,Zr).on(U.getStageRequests,async t=>{var r;if(a(this,Xr).permissions.stageAccess!==H.Allowed)return;const e=(r=t==null?void 0:t.stageRequests)!=null?r:[];await a(this,Pt).getValue("peerSessionStore").emitAsync(_.GET_STAGE_REQUESTS,e),a(this,Ho)<e.length&&e.length>0&&this.stage.emit("newStageRequest",{count:e.length}),f(this,Ho,e.length),this.stage.emit("stageAccessRequestUpdate",e)})}getCurrentStageRequests(){return a(this,Rs).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,Pt).setValue("stageStatus",t)}selfStageStatusHandler(t){const e=bh(t.stageType),r=a(this,Pt).getValue("stageStatus");if(r!==e)switch(t.stageType){case 1:a(this,Pt).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,Pt).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}async peerStageStatusHandler(t){const e=a(this,Rs).joined.get(t.peerId),r=a(this,Rs).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,Pt).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:a(this,Rs).viewMode,page:a(this,Rs).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,Pt).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:a(this,Rs).viewMode,page:a(this,Rs).currentPage});break}a(this,Pt).getValue("peerSessionStore").emit(_.UPDATE_PEER_STAGE_STATUS,{id:e.id,status:e.stageStatus})}}Xr=new WeakMap,Rs=new WeakMap,Zr=new WeakMap,Ho=new WeakMap,Pt=new WeakMap,bO([E.trace("Stage.setupEvents")],Af.prototype,"setupEvents",1);var wO=Object.defineProperty,PO=Object.getOwnPropertyDescriptor,Gd=(s,t,e,r)=>{for(var i=r>1?void 0:r?PO(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 Oe={getPeer:14,getPeers:15,chatMessage:16,getRoomName:17,getDisplayTitle:18,getPluginInitiator:19,customPluginEventToParent:20,peerJoined:22,peerLeft:23,sendData:24,stageStatusUpdate:25,peerStageStatusUpdate:26};let xn=(HS=class extends Dn{constructor(t,{baseURL:e,createdAt:r,description:i,id:n,name:o,organizationId:c,picture:d,private:l,published:u,staggered:h,tags:g,type:S,updatedAt:y},w,b,C,D,F){const L=t.getValue("logger");super(L);m(this,gt,void 0);p(this,"baseURL");p(this,"createdAt");p(this,"description");p(this,"id");p(this,"name");m(this,Kt,void 0);m(this,ia,void 0);m(this,na,void 0);p(this,"organizationId");p(this,"picture");p(this,"private");p(this,"published");p(this,"staggered");p(this,"tags");p(this,"type");p(this,"updatedAt");m(this,Sr,void 0);p(this,"config");m(this,aa,void 0);p(this,"active");p(this,"iframes");p(this,"enabledBy");m(this,ei,void 0);m(this,oa,void 0);f(this,ei,t),this.baseURL=e,this.createdAt=new Date(r),this.description=i,this.id=n,this.name=o,f(this,Kt,b),this.organizationId=c,this.picture=d,this.private=l,this.published=u,this.staggered=h,this.tags=g,this.type=S,this.updatedAt=new Date(y),this.active=!1,this.iframes=new Map,f(this,gt,w),f(this,ia,C),f(this,na,D),this.enabledBy="",f(this,oa,F)}get telemetry(){return a(this,ei).getValue("telemetry")}sendIframeEvent(t){this.iframes.size&&this.iframes.forEach(e=>{const{iframe:r}=e;r&&(navigator.isReactNative?r.postMessage(JSON.stringify(t)):r.contentWindow.postMessage(t,"*"))})}async handleIframeMessage(t){var o;if(!this.active)return;const e=t,{payload:r,uuid:i,type:n}=e;switch(n){case G.customPluginEventToRoom:{a(this,gt).customPluginEventToRoom(this.id,r,i);break}case G.customPluginEventToPeers:{a(this,gt).customPluginEventToPeers(this.id,r.peerIds,r,i);break}case G.enablePluginForRoom:{a(this,gt).enablePluginForRoom(this.id,i);break}case G.enablePluginForPeers:{a(this,gt).enablePluginForPeers(this.id,r.peerIds,i);break}case G.disablePluginForRoom:{a(this,gt).disablePluginForRoom(this.id,i);break}case G.disablePluginForPeers:{a(this,gt).disablePluginForPeers(this.id,r.peerIds,i);break}case G.storeInsertKeys:{a(this,gt).storeInsertKeys(this.id,r.store,r.insertKeys,i);break}case G.storeGetKeys:{a(this,gt).storeGetKeys(this.id,r.store,r.getKeys,i);break}case G.storeDeleteKeys:{a(this,gt).storeDeleteKeys(this.id,r.store,r.deleteKeys,i);break}case G.storeDelete:{a(this,gt).storeDelete(this.id,r.store,i);break}case Oe.chatMessage:{const{messagePayload:c,peerIds:d}=r;if(!a(this,na)){this.sendIframeEvent({type:Oe.chatMessage,uuid:e.uuid,payload:{error:"Chat is disabled for this room."}});return}try{await a(this,na).sendMessage(c,d),this.sendIframeEvent({type:Oe.chatMessage,uuid:e.uuid,payload:{success:!0}})}catch(l){this.sendIframeEvent({type:Oe.chatMessage,uuid:e.uuid,payload:{error:l}})}break}case Oe.getPeer:{let c;const{peerId:d}=r,l={...a(this,Kt),id:a(this,Kt).id,isRecorder:(o=a(this,Kt).permissions)==null?void 0:o.isRecorder,isHidden:a(this,Kt).permissions.hiddenParticipant,stageStatus:a(this,Kt).stageStatus};d?(c=a(this,ia).joined.get(r.peerId),a(this,Kt).id===d&&(c=l)):c=l,this.sendIframeEvent({type:Oe.getPeer,payload:{peer:c&&qd(c)},uuid:e.uuid});break}case Oe.getPeers:{const c=a(this,ia).joined.toArray().map(d=>qd(d));this.sendIframeEvent({type:Oe.getPeers,payload:{peers:c},uuid:e.uuid});break}case Oe.getPluginInitiator:{this.sendIframeEvent({type:Oe.getPluginInitiator,payload:{enabledBy:this.enabledBy},uuid:e.uuid});break}case Oe.getDisplayTitle:{this.sendIframeEvent({type:Oe.getDisplayTitle,payload:{displayTitle:a(this,oa)},uuid:e.uuid});break}case Oe.getRoomName:{this.sendIframeEvent({type:Oe.getRoomName,payload:{roomName:a(this,ei).getValue("meetingId")},uuid:e.uuid});break}case Oe.customPluginEventToParent:{this.emit(e.payload.eventName,e.payload.data);break}}}sendData(t){this.active&&(this.logger.info("Plugin::SendData",{plugin:{id:this.id,name:this.name,data:{eventName:t.eventName}}}),this.sendIframeEvent({type:Oe.sendData,uuid:"",payload:t}))}removePluginView(t="default"){var i;const{iframe:e,listener:r}=(i=this.iframes.get(t))!=null?i:{};(e||r)&&(navigator.isReactNative?e.props.onMessage=void 0:window.removeEventListener("message",r),this.iframes.delete(t))}addPluginView(t,e="default"){var o;if(!a(this,aa))throw this.logger.error("Plugin::addPluginView::no_auth_token_set_for_plugin"),new k("No auth token set for plugin.","0602");if(!t)throw this.logger.error("Plugin::addPluginView::iframe_was_not_provided"),new k("Iframe was not provided.","0603");this.removePluginView(e);const r=t,i=new URL(this.baseURL),n={auth:a(this,aa),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:a(this,ei).getValue("apiBase"),pluginId:this.id,roomName:(o=a(this,ei).getValue("meetingId"))!=null?o:"",displayTitle:a(this,oa)};if(Object.keys(n).forEach(c=>{i.searchParams.set(c,n[c])}),r.src=i.href,r.allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",r.title=e,navigator.isReactNative)r.props.onMessage=c=>{this.handleIframeMessage(JSON.parse(c.nativeEvent.data))},this.iframes.set(e,{iframe:r});else{const c=async d=>{d.source===t.contentWindow&&await this.handleIframeMessage(d.data)};window.addEventListener("message",c),this.iframes.set(e,{iframe:r,listener:c})}}setActive(t){var e,r;if(this.active=t,t){this.emit("stateUpdate",{active:this.active,pluginId:this.id,bind:this.addPluginView.bind(this),views:(e=this.config)==null?void 0:e.views});return}this.active=!1,this.emit("stateUpdate",{active:this.active,pluginId:this.id,views:(r=this.config)==null?void 0:r.views})}async activateForSelf(){const t=yt(),e=await t.authorizePlugin(this.id);f(this,aa,e),f(this,Sr,new Date);try{const r=await t.getPluginConfig(this.baseURL);this.config=r}catch(r){this.logger.error("Plugin::activateForSelf",{error:r})}this.setActive(!0),this.emit("enabled")}deactivateForSelf(){Array.from(this.iframes.keys()).forEach(t=>{this.removePluginView(t)}),f(this,Sr,void 0),this.iframes.clear(),this.setActive(!1),this.emit("closed")}async enable(){return this.activateForSelf()}disable(){return this.deactivateForSelf()}async activate(){var t,e;this.active||(e=(t=a(this,Kt).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(a(this,gt).addPlugin(this.id,this.staggered),f(this,Sr,new Date),this.logger.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}}))}async deactivate(){var t,e;this.active&&(!((e=(t=a(this,Kt).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==a(this,Kt).id||(a(this,gt).removePlugin(this.id),this.logger.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:a(this,Sr)?new Date().getTime()-a(this,Sr).getTime():0}}),f(this,Sr,void 0)))}},gt=new WeakMap,Kt=new WeakMap,ia=new WeakMap,na=new WeakMap,Sr=new WeakMap,aa=new WeakMap,ei=new WeakMap,oa=new WeakMap,HS);Gd([Ot({maxInvocations:5,period:1})],xn.prototype,"sendData",1),Gd([E.trace("Plugin.activatePlugin")],xn.prototype,"activate",1),Gd([E.trace("Plugin.deactivatePlugin")],xn.prototype,"deactivate",1),xn=Gd([ut("0600")],xn);class Mf extends Map{constructor(e,r=void 0){const{onAddEvent:i,onDeleteEvent:n,onClearEvent:o}=e;super();m(this,$e,void 0);m(this,Hi,void 0);p(this,"onAddEvent");p(this,"onDeleteEvent");p(this,"onClearEvent");f(this,$e,new Dn(r)),this.onAddEvent=i,this.onDeleteEvent=n,this.onClearEvent=o,f(this,Hi,new Map)}emit(e,...r){return a(this,$e).emit(e,...r)}on(e,r){return a(this,$e).on(e,r)}addListener(e,r){return a(this,$e).addListener(e,r)}off(e,r){return a(this,$e).off(e,r)}once(e,r){return a(this,$e).once(e,r)}prependListener(e,r){return a(this,$e).prependListener(e,r)}prependOnceListener(e,r){return a(this,$e).prependOnceListener(e,r)}removeListener(e,r){return a(this,$e).removeListener(e,r)}removeAllListeners(e){return a(this,$e).removeAllListeners(e)}listeners(e){return a(this,$e).listeners(e)}listenerCount(e){return a(this,$e).listenerCount(e)}getMaxListeners(){return a(this,$e).getMaxListeners()}setMaxListeners(e){return a(this,$e).setMaxListeners(e)}eventNames(){return a(this,$e).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,Hi).set(e,o),r.on("*",o),i&&a(this,$e).emit(this.onAddEvent,r),n}delete(e,r=!0,i=!1){const n=this.get(e);if(!n)return!1;n.removeListener("*",a(this,Hi).get(e));const o=super.delete(e);return i&&n.removeAllListeners(),r&&a(this,$e).emit(this.onDeleteEvent,n),o}clear(e=!0,r=!1){this.forEach(n=>{n.removeListener("*",a(this,Hi).get(n.id)),r&&n.removeAllListeners()});const i=super.clear();return e&&a(this,$e).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}$e=new WeakMap,Hi=new WeakMap;class Of extends Mf{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 _O=Object.defineProperty,RO=Object.getOwnPropertyDescriptor,CO=(s,t,e,r)=>{for(var i=r>1?void 0:r?RO(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 wh=class{constructor(s){p(this,"all");p(this,"active");this.all=new Of(s),this.active=new Of(s)}};wh=CO([ut("0600")],wh);var kO=Object.defineProperty,IO=Object.getOwnPropertyDescriptor,Wd=(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&&kO(t,e,i),i};const Df=(qS=class{constructor(s,t,e,r){p(this,"plugins");m(this,cs,void 0);m(this,ca,void 0);m(this,Cs,void 0);f(this,cs,t),f(this,ca,e),f(this,Cs,s),this.plugins=r,this.setupEvents()}get telemetry(){return a(this,Cs).getValue("telemetry")}get logger(){return a(this,Cs).getValue("logger")}static async init(s,t,e,r,i,n,o,c){const d=s.getValue("logger"),l=new wh(d);return t.forEach(u=>{const h=new xn(s,u,e,n,o,i,c);l.all.add(h)}),new Df(s,e,r,l)}async getRoomPlugins(){var t;const{plugins:s}=await a(this,cs).getActivePlugins();(t=this.plugins.active)==null||t.toArray().forEach(e=>{this.disablePlugin({id:e.id})}),await Promise.all(s.map(e=>this.enablePlugin({id:e.pluginId,enabledBy:e.enabledBy})))}async enablePlugin({id:s,enabledBy:t}){const e=this.plugins.all.get(s);e&&(await e.activateForSelf(),e.enabledBy=t)}async disablePlugin({id:s}){const t=this.plugins.all.get(s);t&&t.deactivateForSelf()}sendIframeEvent(s,t,e,r){const i=this.plugins.all.get(t);i&&i.sendIframeEvent({type:s,uuid:e,payload:r})}broadcastIframeEvent(s,t){this.plugins.active.forEach(e=>{this.sendIframeEvent(s,e.id,"",t)})}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,Cs).getValue("peerSessionStore").onAsync(_.SOCKET_SERVICE_ROOM_JOINED,async()=>{await this.getRoomPlugins(),this.logger.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to fetch plugins.")}),a(this,cs).on(G.addPlugin,async s=>{var e;const t=s.pluginId;(e=this.plugins.all.get(t))!=null&&e.active||await this.enablePlugin({id:t,enabledBy:s.enabledBy})}),a(this,cs).on(G.removePlugin,async s=>{var e;const t=s.pluginId;(e=this.plugins.all.get(t))!=null&&e.active&&await this.disablePlugin({id:t})}),[G.enablePluginForPeers,G.enablePluginForRoom].forEach(s=>{a(this,cs).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{enabledBy:t.enabledBy})})}),[G.disablePluginForPeers,G.disablePluginForRoom].forEach(s=>{a(this,cs).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{disabledBy:t.disabledBy})})}),[G.customPluginEventToPeers,G.customPluginEventToRoom].forEach(s=>{a(this,cs).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{data:JSON.parse(new TextDecoder().decode(t.pluginData))})})}),[G.storeInsertKeys,G.storeGetKeys,G.storeDeleteKeys].forEach(s=>{a(this,cs).on(s,async(t,e)=>{var i;const r=(i=t.storeItems)==null?void 0:i.map(n=>{var o;return{timestamp:n.timestamp,peerId:n.peerId,payload:JSON.parse((o=n.payload)!=null&&o.length?new TextDecoder().decode(n.payload):"{}"),key:n.storeKey}});this.sendIframeEvent(s,t.pluginId,e,{storeName:t.storeName,storeItems:r})})}),a(this,cs).on(G.storeDelete,async(s,t)=>{this.sendIframeEvent(G.storeDelete,s.pluginId,t,{storeName:s.storeName})}),a(this,ca).on(Ge.sendMessageToPeers,s=>{const t=is==null?void 0:is.formatSocketPeerMessage(s.message);this.broadcastIframeEvent(Oe.chatMessage,{message:t})}),a(this,ca).on(Ge.sendMessageToRoom,s=>{const t=is==null?void 0:is.formatSocketPeerMessage(s.message);this.broadcastIframeEvent(Oe.chatMessage,{message:t})}),a(this,Cs).getValue("peerSessionStore").on(_.PEER_JOINED_INTERNAL,s=>{const t=qd(s);this.broadcastIframeEvent(Oe.peerJoined,t)}),a(this,Cs).getValue("peerSessionStore").on(_.PEER_CLOSED,s=>{this.broadcastIframeEvent(Oe.peerLeft,s)}),a(this,Cs).getValue("peerSessionStore").on(_.UPDATE_PEER_STAGE_STATUS,s=>{this.broadcastIframeEvent(Oe.peerStageStatusUpdate,s)}),a(this,Cs).subscribe("stageStatus",s=>{this.broadcastIframeEvent(Oe.stageStatusUpdate,s)})}},cs=new WeakMap,ca=new WeakMap,Cs=new WeakMap,qS);let vo=Df;Wd([E.trace("PluginController.getRoomPlugins")],vo.prototype,"getRoomPlugins",1),Wd([E.trace("PluginController.enableForSelf")],vo.prototype,"enablePlugin",1),Wd([E.trace("PluginController.disableForSelf")],vo.prototype,"disablePlugin",1),Wd([E.trace("PluginController.setupEvents")],vo.prototype,"setupEvents",1);class AO{constructor(t){p(this,"mediaJoined");p(this,"socketJoined");p(this,"socketJoinAttempted");p(this,"mediaJoinAttempted");p(this,"socketState");p(this,"mediaState");m(this,qo,void 0);this.mediaJoined=!1,this.socketJoined=!1,this.socketJoinAttempted=!1,this.mediaJoinAttempted=!1,this.socketState={state:void 0,reconnected:!1,reconnectionAttempt:void 0},this.mediaState={recv:void 0,send:void 0},f(this,qo,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&&(a(this,qo).getValue("peerSessionStore").emit(_.SOCKET_STATE_UPDATE,r),this.socketState=r)}}qo=new WeakMap;var MO=Object.defineProperty,OO=Object.getOwnPropertyDescriptor,To=(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};let Ri=(jS=class extends $t{constructor(t,e){const r=t.getValue("logger");super(r);m(this,ua);m(this,da,void 0);m(this,la,void 0);p(this,"recordingPeerIds",[]);p(this,"recordings",[]);f(this,la,t),f(this,da,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,la).getValue("telemetry")}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}async start(t){if(!a(this,da).permissions.canRecord)throw this.logger.error("Recording::start::permission_denied"),new k("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 k(`Cant start recording, recordingState irregular: ${this.recordingState}`,"1005");try{const e=yt(),{recording:r={}}=a(this,la).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::stop::recording_failed_to_start",{error:e}),new k("Error while starting recording","1000",this.logger)}}async stop(t){await x(this,ua,gu).call(this,"stop",["RECORDING","PAUSED"],t)}async pause(t){await x(this,ua,gu).call(this,"pause",["RECORDING"],t)}async resume(t){await x(this,ua,gu).call(this,"resume",["PAUSED"],t)}},da=new WeakMap,la=new WeakMap,ua=new WeakSet,gu=async function(t,e,r){if(!a(this,da).permissions.canRecord)throw this.logger.error("Recording::stop::permission_denied"),new k("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 k("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 yt().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 k("Error while stopping recording","1000",this.logger)}})},jS);To([E.trace("Recording.start")],Ri.prototype,"start",1),To([E.trace("Recording.stop")],Ri.prototype,"stop",1),To([E.trace("Recording.stop")],Ri.prototype,"pause",1),To([E.trace("Recording.stop")],Ri.prototype,"resume",1),Ri=To([ut("1000")],Ri);var DO=Object.defineProperty,NO=Object.getOwnPropertyDescriptor,VO=(s,t,e,r)=>{for(var i=r>1?void 0:r?NO(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&&DO(t,e,i),i};class Nf{constructor(t,e,r){p(this,"recording");p(this,"room");m(this,qi,void 0);f(this,qi,t),this.recording=new Ri(t,e),this.room=r,this.setupEvents()}get telemetry(){return a(this,qi).getValue("telemetry")}get logger(){return a(this,qi).getValue("logger")}getRecordingTypeFromProtoType(t){let e;switch(t){case Pi.BROWSER:e="BROWSER";break;case Pi.COMPOSITE:e="COMPOSITE";break;case Pi.TRACK:e="TRACK";break;default:e="BROWSER"}return e}setupEvents(){a(this,qi).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(U.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(U.recordingPaused,t=>{const e=[...this.recording.recordings];e.forEach(r=>{r.id===t.recordingId&&(r.state="PAUSED")}),this.recording.updateRecordings(e)}),this.room.on(U.recordingStopped,t=>{const e=[...this.recording.recordings.filter(r=>r.id!==t.recordingId)];this.recording.updateRecordings(e)})}}qi=new WeakMap,VO([E.trace("RecordingController.setupEvents")],Nf.prototype,"setupEvents",1);class LO{constructor(t){m(this,ji,void 0);f(this,ji,t)}hasFeature(t){var e;return(e=a(this,ji).getValue("flagsmith").hasFeature(t))!=null?e:!1}getFeatureValue(t){return a(this,ji).getValue("flagsmith").getValue(t)}getAllFeatures(){return a(this,ji).getValue("flagsmith").getAllFlags()}}ji=new WeakMap;class Ph{constructor(t,e,r){p(this,"logger");p(this,"features");p(this,"browserSpecs");p(this,"callStats");this.logger=t,this.features=e,this.browserSpecs=we,this.callStats=r}static init(t){return new Ph(t.getValue("logger"),new LO(t),t.getValue("callstats"))}}class _h{constructor(t){p(this,"internals");this.internals=t}static async init(t){const e=Ph.init(t);return new _h(e)}}var xO=Object.defineProperty,UO=Object.getOwnPropertyDescriptor,Ht=(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};class Dt extends Dn{constructor(e,r,i=Kd,n=!0){const o=e.getValue("logger");super(o);m(this,Ke,void 0);m(this,Ee,void 0);m(this,fe,void 0);m(this,vr,void 0);m(this,ds,void 0);m(this,jo,void 0);m(this,Ve,void 0);p(this,"audioUpdateInProgress");p(this,"videoUpdateInProgress");f(this,Ve,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,f(this,Ke,new Hf(e,r)),f(this,Ee,new pD(e,a(this,Ke),void 0,i)),f(this,fe,new yD(e,a(this,Ke),void 0,i)),f(this,ds,new SD(a(this,Ve),a(this,Ke))),f(this,vr,new mD(e,a(this,Ke))),f(this,jo,n),a(this,Ee).on("trackMuted",this.onAudioTrackMuted.bind(this)),a(this,Ee).on("trackChanged",this.onAudioTrackChanged.bind(this)),a(this,fe).on("trackChanged",this.onVideoTrackChanged.bind(this)),a(this,fe).on("trackEnded",this.onVideoTrackEnded.bind(this)),a(this,ds).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}get telemetry(){return a(this,Ve).getValue("telemetry")}set context(e){f(this,Ve,e)}async onVisibilityChange(){a(this,Ve).getValue("callstats").tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?a(this,Ve).getValue("callstats").browserBackgrounded():(a(this,Ve).getValue("callstats").browserForegrounded(),await this.setupSpeaker())}async repopulateAvailableDevices(){return!0}async setupStreams({audio:e,video:r}){var o;e?a(this,Ve).getValue("callstats").audioOn():a(this,Ve).getValue("callstats").audioOff(),r?a(this,Ve).getValue("callstats").videoOn():a(this,Ve).getValue("callstats").videoOff();let i,n;if(e&&r)try{const c=await a(this,Ke).getAudioAndVideoTrack(a(this,Ee).userSelectedDevice,a(this,fe).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,Ke).getAudioTrack(!1,a(this,Ee).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!n&&r)try{n=await a(this,Ke).getVideoTrack(a(this,fe).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get video track",{error:c})}e&&!i&&a(this,Ve).getValue("callstats").audioOff(),r&&!n&&a(this,Ve).getValue("callstats").videoOff(),await a(this,Ee).setMediaTrack(i),await a(this,fe).setMediaTrack(n);try{await this.setupSpeaker()}catch(c){}if(n){const c=await this.getDeviceById(n.getSettings().deviceId);a(this,Ve).getValue("callstats").selectedDevice("VIDEO",c)}if(i){const c=await this.getDeviceById(i.getSettings().deviceId);a(this,Ve).getValue("callstats").selectedDevice("AUDIO",c)}(o=a(this,vr).currentDevice)!=null&&o.deviceId&&a(this,Ve).getValue("callstats").selectedDevice("SPEAKER",a(this,vr).currentDevice),a(this,Ke).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})}getCurrentDevices(){return{audio:a(this,Ee).currentDevice,video:a(this,fe).currentDevice,speaker:a(this,vr).currentDevice}}get permissions(){return a(this,Ke).permissions}getAllDevices(){return a(this,Ke).getAvailableDevices()}getDeviceById(e,r){return a(this,Ke).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return a(this,Ee).mediaTrack}get audioTrack(){return a(this,Ee).transformedMediaTrack}get audioEnabled(){return a(this,Ee).trackEnabled}async enableAudio(e){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{e?await a(this,Ee).enableTrack(!1,e):await a(this,Ee).unmuteTrack()}catch(r){}finally{this.audioUpdateInProgress=!1}}}disableAudio(){a(this,Ee).mediaTrack&&!a(this,Ee).isCustomTrack?a(this,Ee).muteTrack():a(this,Ee).disableTrack()}getAudioDevices(e){return a(this,Ke).getAudioInputDevices(e)}async setAudioDevice(e,{saveDevicePreference:r}){await a(this,Ee).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Ve).getValue("callstats").selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async setupSpeaker(){const{speaker:e}=this.getCurrentDevices();await a(this,vr).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,vr).setupSpeaker(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Ve).getValue("callstats").selectedDevice("SPEAKER",e),this.emit("DEVICE_CHANGE",{device:e})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return a(this,fe).mediaTrack}get videoTrack(){return a(this,fe).transformedMediaTrack}get videoEnabled(){return a(this,fe).trackEnabled}async enableVideo(e){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{e?await a(this,fe).enableTrack(!1,e):await a(this,fe).unmuteTrack()}catch(r){}finally{this.videoUpdateInProgress=!1}}}disableVideo(){a(this,fe).disableTrack()}getVideoDevices(e){return a(this,Ke).getVideoInputDevices(e)}async setVideoDevice(e,{saveDevicePreference:r}){await a(this,fe).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Ve).getValue("callstats").selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async updateVideoConstraints(e){await a(this,fe).updateConstraints(e)}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:a(this,ds).audioMediaTrack,video:a(this,ds).videoMediaTrack}}get screenShareEnabled(){return a(this,ds).trackEnabled}async enableScreenShare(){await a(this,ds).enableScreenShare()}async disableScreenShare(){a(this,ds).disableScreenShare()}async updateScreenshareConstraints(e){await a(this,ds).updateConstraints(e)}getSpeakerDevices(e){return a(this,Ke).getAudioOutputDevices(e)}addAudioMiddleware(e){return a(this,Ee).addMiddleware(e)}removeAudioMiddleware(e){return a(this,Ee).removeMiddleware(e)}removeAllAudioMiddlewares(){return a(this,Ee).removeAllMiddlewares()}addVideoMiddleware(e){return a(this,fe).addMiddleware(e)}removeVideoMiddleware(e){return a(this,fe).removeMiddleware(e)}removeAllVideoMiddlewares(){return a(this,fe).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return a(this,fe).setVideoMiddlewareGlobalConfig(e)}destruct(){a(this,Ee).disableTrack(),a(this,fe).disableTrack(),a(this,fe).terminateMiddlewareWebWorker(),a(this,ds).disableScreenShare(),a(this,Ke).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&&!Kd(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,Ee).disableTrack()}removeVideoTrack(){a(this,fe).disableTrack(),a(this,fe).terminateMiddlewareWebWorker()}async removeDocumentEventListeners(){document.removeEventListener("visibilitychange",this.onVisibilityChange)}}Ke=new WeakMap,Ee=new WeakMap,fe=new WeakMap,vr=new WeakMap,ds=new WeakMap,jo=new WeakMap,Ve=new WeakMap,Ht([E.trace("MediaHandler.setupStreams")],Dt.prototype,"setupStreams",1),Ht([E.trace("MediaHandler.enableAudio")],Dt.prototype,"enableAudio",1),Ht([E.trace("MediaHandler.disableAudio")],Dt.prototype,"disableAudio",1),Ht([E.trace("MediaHandler.setAudioDevice")],Dt.prototype,"setAudioDevice",1),Ht([E.trace("MediaHandler.enableVideo")],Dt.prototype,"enableVideo",1),Ht([E.trace("MediaHandler.disableVideo")],Dt.prototype,"disableVideo",1),Ht([E.trace("MediaHandler.setVideoDevice")],Dt.prototype,"setVideoDevice",1),Ht([E.trace("MediaHandler.updateVideoConstraints")],Dt.prototype,"updateVideoConstraints",1),Ht([E.trace("MediaHandler.enableScreenShare")],Dt.prototype,"enableScreenShare",1),Ht([E.trace("MediaHandler.disableScreenShare")],Dt.prototype,"disableScreenShare",1),Ht([E.trace("MediaHandler.updateScreenshareConstraints")],Dt.prototype,"updateScreenshareConstraints",1),Ht([E.trace("MediaHandler.destruct")],Dt.prototype,"destruct",1),Ht([E.trace("MediaHandler.onDeviceChange")],Dt.prototype,"onDeviceChange",1);function Jd(s,t,e){switch(!0){case we.isChromiumBased():switch(t){case"NotAllowedError":return e.includes("by system")?"SYSTEM_DENIED":s==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case we.isSafari():switch(t){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case we.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 FO=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function Kd(s){var e,r;const t=(e=s.label)==null?void 0:e.toLowerCase();return((r=we._bowser)==null?void 0:r.getOSName())==="macOS"&&t.includes("iphone")?!0:FO.some(i=>t==null?void 0:t.includes(i))}async function $O(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 BO=s=>(t,e)=>(s.set(t,e),e),Vf=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,Lf=536870912,xf=Lf*2,HO=(s,t)=>e=>{const r=t.get(e);let i=r===void 0?e.size:r<xf?r+1:0;if(!e.has(i))return s(e,i);if(e.size<Lf){for(;e.has(i);)i=Math.floor(Math.random()*xf);return s(e,i)}if(e.size>Vf)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()*Vf);return s(e,i)},Uf=new WeakMap,qO=BO(Uf),zd=HO(qO,Uf),jO=s=>s.method!==void 0&&s.method==="call",GO=s=>s.error===null&&typeof s.id=="number",Yd=((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(jO(l)){const{params:{timerId:u,timerType:h}}=l;if(h==="interval"){const g=t.get(u);if(typeof g=="number"){const S=r.get(g);if(S===void 0||S.timerId!==u||S.timerType!==h)throw new Error("The timer is in an undefined state.")}else if(typeof g!="undefined")g();else throw new Error("The timer is in an undefined state.")}else if(h==="timeout"){const g=e.get(u);if(typeof g=="number"){const S=r.get(g);if(S===void 0||S.timerId!==u||S.timerType!==h)throw new Error("The timer is in an undefined state.")}else if(typeof g!="undefined")g(),e.delete(u);else throw new Error("The timer is in an undefined state.")}}else if(GO(l)){const{id:u}=l,h=r.get(u);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:g,timerType:S}=h;r.delete(u),S==="interval"?t.delete(g):e.delete(g)}else{const{error:{message:u}}=l;throw new Error(u)}}),{clearInterval:l=>{const u=zd(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=zd(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=zd(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=zd(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})}}))})();`),Ff=s=>Yd().clearInterval(s),WO=s=>Yd().clearTimeout(s),$f=(s,t)=>Yd().setInterval(s,t),Bf=Object.freeze(Object.defineProperty({__proto__:null,clearInterval:Ff,clearTimeout:WO,setInterval:$f,setTimeout:(s,t)=>Yd().setTimeout(s,t)},Symbol.toStringTag,{value:"Module"}));class JO{constructor(t){m(this,Gi,void 0);m(this,Go,void 0);f(this,Go,t)}get logger(){return a(this,Go).getValue("logger")}terminateMiddlewareWebWorker(){if(a(this,Gi))try{Ff(a(this,Gi)),f(this,Gi,void 0)}catch(t){this.logger.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}async getTransformedVideoTrack(t,e,r){if(!(t!=null&&t.length))return e;const i=document.createElement("canvas"),n=await Promise.all(t==null?void 0:t.map(g=>g({canvas:i,WorkerTimers:Bf})));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 g=0;g<n.length;g+=1)typeof n[g]=="function"&&await n[g](i,d)}catch(g){this.logger.error("getTransformedVideoTrack::middleware_execution_failed",{error:g})}};try{o.play()}catch(g){}o.addEventListener("play",()=>{i.width=o.width||e.getSettings().width,i.height=o.width||e.getSettings().height,f(this,Gi,$f(l,50))},!1);const h=i.captureStream().getVideoTracks()[0];return Object.defineProperty(h,"originalSettings",{value:e.getSettings()}),h}}Gi=new WeakMap,Go=new WeakMap;const KO={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}}},zO=[[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}]]],YO=(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=zO,n=i.map(([h])=>h).sort((h,g)=>h-g);let o=Number.MAX_VALUE,c=0;return n.forEach((h,g)=>{Math.abs(h-r)<o&&(o=Math.abs(h-r),c=g)}),i[c][1]};var me=(s=>(s.WEBCAM="webcam",s.WEBCAM_BACKUP="webcam_backup",s.MIC="mic",s.SCREENSHARE_VIDEO="screenshare_video",s.SCREENSHARE_AUDIO="screenshare_audio",s))(me||{});const QO=jw(),Un=Hs(QO.config.media);function XO(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 ZO{constructor(t,e){m(this,Wi,void 0);m(this,ti,void 0);p(this,"getScreenShareConstraints",()=>{var l,u,h,g,S,y,w,b,C,D,F;const t=(l=a(this,Wi))==null?void 0:l.screenshare,e=(h=(u=t==null?void 0:t.width)==null?void 0:u.max)!=null?h:1920,r=(S=(g=t==null?void 0:t.height)==null?void 0:g.max)!=null?S:1080,i=(w=(y=t==null?void 0:t.frameRate)==null?void 0:y.max)!=null?w:5;let n=(C=(b=t==null?void 0:t.frameRate)==null?void 0:b.ideal)!=null?C:5;const o=t==null?void 0:t.displaySurface,c=t==null?void 0:t.selfBrowserSurface;a(this,ti).getValue("flagsmith").getValue(Z.VAL_MIN_FRAMERATE)&&(n=parseInt((D=a(this,ti).getValue("flagsmith").getValue(Z.VAL_MIN_FRAMERATE))==null?void 0:D.toString(),10));let d={width:{max:e},height:{max:r},frameRate:{ideal:n,max:i}};if(a(this,ti).getValue("flagsmith").hasFeature(Z.SCREENSHARE_CONSTRAINTS)){const L=(F=a(this,ti).getValue("flagsmith").getValue(Z.SCREENSHARE_CONSTRAINTS))==null?void 0:F.toString();d=JSON.parse(L)}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,Wi))==null?void 0:n.audio,i=r!=null&&r.enableStereo?2:1;return we.isFirefox()||we.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,Wi))==null?void 0:o.video,i=kP(KO);let n=i.vga;if(typeof r=="string"){const l=i[r];l&&(n=l)}else r!==void 0&&(n.height.ideal=r.height.ideal,n.width.ideal=r.width.ideal,n.frameRate.ideal=(d=(c=r.frameRate)==null?void 0:c.ideal)!=null?d:30);return e.video=n,typeof e.video=="boolean"||(t?e.video.deviceId={exact:t}:e.video.facingMode="user"),e});f(this,ti,t),f(this,Wi,e)}getUpdatedVideoConstraints(t){return t}}Wi=new WeakMap,ti=new WeakMap;class Rh extends Error{constructor(e,r,i){super(r);p(this,"constraints");p(this,"name");this.name=e,this.constraints=i}}class eD{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 tD=Object.defineProperty,sD=Object.getOwnPropertyDescriptor,ws=(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 qt=(GS=class extends eD{constructor(t,e){super();m(this,ha,void 0);m(this,ls,void 0);m(this,Be,void 0);f(this,Be,t),f(this,ls,new ZO(t,e)),f(this,ha,new AbortController)}get telemetry(){return a(this,Be).getValue("telemetry")}get logger(){return a(this,Be).getValue("logger")}get constraintsBuilder(){return a(this,ls)}async destruct(){var t;(t=a(this,ha))==null||t.abort()}handlePermissionErrors(t,e){const r=Jd(t,e.name,e.message);return this.permissions[t]=r,a(this,Be).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(D=>D.deviceId===t));let u;t&&l?u=t:c&&((r=c[0])!=null&&r.deviceId)&&(u=(i=c[0])==null?void 0:i.deviceId);const h=!!(d!=null&&d.find(D=>D.deviceId===e));let g;e&&h?g=e:d&&((n=d[0])!=null&&n.deviceId)&&(g=(o=d[0])==null?void 0:o.deviceId);const S={audio:a(this,ls).getAudioConstraints(u).audio,video:a(this,ls).getVideoConstraints(g).video};this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(S)});const y=await navigator.mediaDevices.getUserMedia(S);this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(S)});const w=y.getAudioTracks()[0];let b=y.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",a(this,Be).getValue("flagsmith").hasFeature(Z.OBS_QUALITY)&&b.label.includes("OBS Virtual")){const F=(await this.getVideoInputDevices()).find(L=>L.label.includes("OBS Virtual"));b=await this.getVideoTrack(F.deviceId)}return a(this,Be).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),a(this,Be).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:w,videoTrack:b}}catch(c){throw this.logger.error("WebMediaInterface.getAudioAndVideoTrack",{error:c}),new k("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,Be).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new k("No audio devices available","1606");const i=!!(r!=null&&r.find(l=>l.deviceId===e));let n;e&&i?n=e:(c=r[0])!=null&&c.deviceId&&(n=(d=r[0])==null?void 0:d.deviceId);const o=async l=>{let u;try{r=r.filter(g=>g.deviceId!==l),u=a(this,ls).getAudioConstraints(l),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(u)});const[h]=(await navigator.mediaDevices.getUserMedia(u)).getAudioTracks();return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(u)}),h}catch(h){const g=Jd("audio",h.name,h.message),S=new Rh(h.name,h.message,u);if(g==="COULD_NOT_START"){const y=r.shift();if(!y)throw S;this.logger.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(u),error:h});const w=a(this,ls).getAudioConstraints(y.deviceId);return this.logger.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(w)}),o(y.deviceId)}throw S}};try{const l=await o(n);return l.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",a(this,Be).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),l}catch(l){throw l.constraints&&this.handlePermissionErrors("audio",l),new k(l.message,"1601")}}async getVideoTrack(t){var l,u,h;const e=a(this,Be).getValue("flagsmith").hasFeature(Z.OBS_QUALITY),r=(l=await this.getCurrentDeviceLabel(t))==null?void 0:l.includes("OBS Virtual"),i=e&&r,n=await this.getVideoInputDevices();if(!(n!=null&&n.length))throw this.permissions.video="NO_DEVICES_AVAILABLE",a(this,Be).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new k("No video devices available","1607");const o=!!(n!=null&&n.find(g=>g.deviceId===t));let c;t&&o?c=t:(u=n[0])!=null&&u.deviceId&&(c=(h=n[0])==null?void 0:h.deviceId);const d=async g=>{try{let S=g;const{video:y}=S;i&&typeof y!="boolean"&&(S={video:{deviceId:y.deviceId}}),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(S)});const[w]=(await navigator.mediaDevices.getUserMedia(S)).getVideoTracks();if(i&&typeof y!="boolean"&&typeof y.width=="object"){const{width:b,height:C}=w.getSettings(),{ideal:D}=y.width;w.applyConstraints({width:{ideal:D},height:{ideal:Math.floor(C*D/b)},frameRate:y.frameRate})}return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(S)}),w}catch(S){const y=Jd("video",S.name,S.message),w=new Rh(S.name,S.message,g);if(y==="COULD_NOT_START"){const b=n.shift();if(!b)throw w;this.logger.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(g),error:S});const C=a(this,ls).getVideoConstraints(b.deviceId);return this.logger.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(C)}),d({video:C.video})}throw w}};try{const g=a(this,ls).getVideoConstraints(c),S=await d(g);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",a(this,Be).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),S}catch(g){throw g.constraints&&this.handlePermissionErrors("video",g),new k(g.message,"1602")}}async getScreenShareTracks(){const t=async e=>{try{this.logger.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),a(this,Be).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=Jd("video",r.name,r.message),n=new Rh(r.name,r.message,e),o={video:!0};if(D_(e,o)||!a(this,Be).getValue("flagsmith").hasFeature(Z.SCREEENSHARE_CONSTRAINTS_RETRY))throw n;if(i==="COULD_NOT_START")return t(o);throw n}};try{const e=a(this,ls).getScreenShareConstraints(),r=await t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",a(this,Be).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 k(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 Kd(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 g=r(i),S=r(n);if(g&&!S)return-1;if(!g&&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 k("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 k("Failed to get device","1609")}}async onDeviceChange(t){if(we.supportsDeviceChangeEvent()){let e=await this.getAvailableDevices();navigator.mediaDevices.addEventListener("devicechange",async r=>{var l,u;const i=h=>`${h.kind}-${h.label}-${h.deviceId}-${h.groupId}`,n=new Set(e.map(h=>i(h))),o=await this.getAvailableDevices(),c=new Set(o.map(h=>i(h))),d={added:o.filter(h=>!n.has(i(h))),removed:e.filter(h=>!c.has(i(h))),devices:o};if(e=o,(l=d.added)!=null&&l.length||(u=d.removed)!=null&&u.length){this.logger.info("repopulated_full_device_list",{devices:JSON.stringify(o)});const h=[...d.added,...d.removed];h.some(g=>g.kind==="audioinput")&&a(this,Be).getValue("callstats").devices("AUDIO",o==null?void 0:o.filter(g=>g.kind==="audioinput")),h.some(g=>g.kind==="videoinput")&&a(this,Be).getValue("callstats").devices("VIDEO",o==null?void 0:o.filter(g=>g.kind==="videoinput")),h.some(g=>g.kind==="audiooutput")&&a(this,Be).getValue("callstats").devices("SPEAKER",o==null?void 0:o.filter(g=>g.kind==="audiooutput")),t(r,d,!1)}},{signal:a(this,ha).signal})}}},ha=new WeakMap,ls=new WeakMap,Be=new WeakMap,GS);ws([E.trace("WebMediaInterface.destruct")],qt.prototype,"destruct",1),ws([E.trace("WebMediaInterface.handlePermissionErrors")],qt.prototype,"handlePermissionErrors",1),ws([E.trace("WebMediaInterface.getAudioAndVideoTrack")],qt.prototype,"getAudioAndVideoTrack",1),ws([E.trace("WebMediaInterface.getAudioTrack")],qt.prototype,"getAudioTrack",1),ws([E.trace("WebMediaInterface.getVideoTrack")],qt.prototype,"getVideoTrack",1),ws([E.trace("WebMediaInterface.getScreenShareTracks")],qt.prototype,"getScreenShareTracks",1),ws([E.trace("WebMediaInterface.getAvailableDevices")],qt.prototype,"getAvailableDevices",1),ws([E.trace("WebMediaInterface.getAvailableDevicesByKind")],qt.prototype,"getAvailableDevicesByKind",1),ws([E.trace("WebMediaInterface.getDevice")],qt.prototype,"getDevice",1),ws([E.trace("WebMediaInterface.onDeviceChange")],qt.prototype,"onDeviceChange",1),qt=ws([ut("1600")],qt);const Hf=qt,Ci={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}},rD=(s=0)=>new Promise(t=>setTimeout(t,s)),iD=(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):rD().then(d))}return d().then(l=>(i.disconnect(),l),l=>{throw i.disconnect(),l})},nD=typeof AudioContext!="undefined"?AudioContext:null;class Ch{constructor(t){p(this,"_AudioContext");p(this,"audioContext");p(this,"_audioContextRefContainers");const e={AudioContext:nD,...t};Object.defineProperties(this,{_AudioContext:{value:e.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:Ch}})}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 qf=new Ch,aD=3,oD=250;function cD(s){const t={},e=qf.getOrCreate(t);let r=aD;function i(){return r-=1,iD(e,s.srcObject,oD).then(n=>n?r>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{qf.release(t)})}async function jf(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 cD(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,lD=Object.getOwnPropertyDescriptor,Gf=(s,t,e,r)=>{for(var i=r>1?void 0:r?lD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&dD(t,e,i),i};let Qd=class extends Dn{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=>Ci.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>Ci.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 k("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 k("No device received!","1603");this.userSelectedDevice=t.deviceId,e&&this.setUserPreferredDevice(t.deviceId),await this.onSetDevice(t)}async addMiddleware(t){if(we.isWebKitBased()&&!Dw.hasFeature(Z.ALLOW_SAFARI_MEDIA_MIDDLEWARES))return{success:!1,message:"Middlewares are not supported in this WebKit engine based browser."};if(this.middlewares.includes(t))return{success:!1,message:"This middleware has been applied, already. Skipping."};try{return this.middlewares.push(t),this.trackEnabled&&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))}};Gf([E.trace("BaseMediaHandler.unmuteTrack")],Qd.prototype,"unmuteTrack",1),Qd=Gf([ut("1600")],Qd);const Wf=Qd;var uD=Object.defineProperty,hD=Object.getOwnPropertyDescriptor,kh=(s,t,e,r)=>{for(var i=r>1?void 0:r?hD(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&&uD(t,e,i),i};const Ih="[Realtimekit]nonSilentDeviceLabels";class Xd extends Wf{async onSetDevice(t){if(!t)throw this.logger.warn("AudioMediaHandler.setDevice No device received"),new k("No device received!","1603");if(t.kind!=="audioinput")throw this.logger.warn("AudioMediaHandler.setDevice Received non audio device"),new k("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 k(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 $O(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(Ci.getItem(Ih,this.logger));if(o!=null&&o.devices.some(l=>l.label===r.label))return r;if(!await jf(this.logger,r)){const l=(d=o==null?void 0:o.devices.concat({label:r.label}))!=null?d:[{label:r.label}];return Ci.setItem(Ih,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 jf(this.logger,r)){const h=(u=o==null?void 0:o.devices.concat({label:r.label}))!=null?u:[{label:r.label}];return Ci.setItem(Ih,JSON.stringify({devices:h}),this.logger),this.logger.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return this.logger.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1}),r}}kh([E.trace("AudioMediaHandler.setTransformedTrack")],Xd.prototype,"setTransformedTrack",1),kh([E.trace("AudioMediaHandler.onTrackEnded")],Xd.prototype,"onTrackEnded",1),kh([E.trace("AudioMediaHandler.conditionallyChangeTrack")],Xd.prototype,"conditionallyChangeTrack",1);const pD=Xd;class gD{constructor(t,e){m(this,Ji,void 0);p(this,"currentDevice");p(this,"userPreferredDeviceKey","Realtimekit::speaker::UserDeviceID");p(this,"logger");p(this,"setUserPreferredDevice",t=>Ci.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>Ci.getItem(this.userPreferredDeviceKey,this.logger));f(this,Ji,e),this.logger=t.getValue("logger")}async setPreferredSpeaker(){const t=this.getUserPreferredDevice(),e=await a(this,Ji).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,Ji)instanceof Hf))return;let r=t;if(t||([r]=(await a(this,Ji).getAvailableDevicesByKind("audiooutput")).filter(d=>!Kd(d))),!r)throw new k("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){}})}}Ji=new WeakMap;const mD=gD;class fD extends Dn{constructor(e,r){const i=e.getValue("logger");super(i);p(this,"mediaInterface");p(this,"audioMediaTrack");p(this,"videoMediaTrack");m(this,Wo,void 0);f(this,Wo,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,Wo).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 k("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new k("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)),we.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")}}Wo=new WeakMap;const SD=fD;var vD=Object.defineProperty,TD=Object.getOwnPropertyDescriptor,Zd=(s,t,e,r)=>{for(var i=r>1?void 0:r?TD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&vD(t,e,i),i};class yo extends Wf{constructor(e,r,i,n){super(e,r,i,n);m(this,pa,void 0);m(this,Jo,{disablePerFrameCanvasRendering:!1});f(this,pa,new JO(e))}async onSetDevice(e){if(!e)throw this.logger.warn("VideoMediaHandler.setDevice No device received"),new k("No device received!","1603");if(e.kind!=="videoinput")throw this.logger.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new k("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 k("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,pa).getTransformedVideoTrack(this.middlewares,this.mediaTrack,a(this,Jo)),this.emit("trackChanged")}catch(i){this.logger.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}}async setVideoMiddlewareGlobalConfig(e){f(this,Jo,e)}async updateConstraints(e){if(!this._mediaTrack)throw new k("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new k("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,pa).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}}pa=new WeakMap,Jo=new WeakMap,Zd([E.trace("VideoMediaHandler.setTransformedTrack")],yo.prototype,"setTransformedTrack",1),Zd([E.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],yo.prototype,"setVideoMiddlewareGlobalConfig",1),Zd([E.trace("VideoMediaHandler.onTrackEnded")],yo.prototype,"onTrackEnded",1),Zd([E.trace("VideoMediaHandler.conditionallyChangeTrack")],yo.prototype,"conditionallyChangeTrack",1);const yD=yo,Jf=Hs(Fu()),ma=class{constructor(t){m(this,_t,void 0);m(this,Ki,void 0);m(this,Ko,void 0);m(this,ga,void 0);if(!t)throw new k("Could not load preset.","0904");f(this,_t,t.config),f(this,Ko,t.name),f(this,Ki,t.ui||Hs(Fu().ui)),f(this,ga,t.permissions.plugins.config)}static fromResponse(t){return new ma(t)}static default(){return new ma(Jf)}static init(t,e=!0){return!t||e?new ma(Jf):new ma(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,Ki).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return a(this,_t).viewType}get livestreamViewerQualities(){return a(this,_t).livestreamViewerQualities||[]}get maxVideoStreams(){return a(this,_t).maxVideoStreams}get maxScreenShareCount(){return a(this,_t).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(a(this,ga)).filter(t=>a(this,ga)[t].disabled)}get designTokens(){return a(this,Ki).designTokens}get configDiff(){return a(this,Ki).configDiff}get isSimulcastEnabled(){var t,e,r,i;return(i=(r=(e=(t=a(this,_t))==null?void 0:t.media)==null?void 0:e.video)==null?void 0:r.simulcast)!=null?i:!1}get mediaConstraints(){var t,e,r,i,n,o,c,d,l,u,h,g,S,y,w,b,C,D,F,L,B,Q,se,nt;return{audio:{enableStereo:(i=(r=(e=(t=a(this,_t))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?i:Un.audio.enableStereo,enableHighBitrate:(d=(c=(o=(n=a(this,_t))==null?void 0:n.media)==null?void 0:o.audio)==null?void 0:c.enableHighBitrate)!=null?d:Un.audio.enableHighBitrate},video:{quality:(g=(h=(u=(l=a(this,_t))==null?void 0:l.media)==null?void 0:u.video)==null?void 0:h.quality)!=null?g:Un.video.quality,frameRate:(b=(w=(y=(S=a(this,_t))==null?void 0:S.media)==null?void 0:y.video)==null?void 0:w.frameRate)!=null?b:Un.video.frameRate},screenshare:{quality:(L=(F=(D=(C=a(this,_t))==null?void 0:C.media)==null?void 0:D.screenshare)==null?void 0:F.quality)!=null?L:Un.screenshare.quality,frameRate:(nt=(se=(Q=(B=a(this,_t))==null?void 0:B.media)==null?void 0:Q.screenshare)==null?void 0:se.frameRate)!=null?nt:Un.screenshare.frameRate}}}get name(){return a(this,Ko)}};let Ah=ma;_t=new WeakMap,Ki=new WeakMap,Ko=new WeakMap,ga=new WeakMap;var ED=Object.defineProperty,bD=Object.getOwnPropertyDescriptor,Kf=(s,t,e,r)=>{for(var i=r>1?void 0:r?bD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ED(t,e,i),i};class Mh extends $t{constructor(e,r){const i=e.getValue("logger");super(i);m(this,fa,void 0);p(this,"state","IDLE");p(this,"playbackUrl");p(this,"ingestionCredentials");p(this,"viewerCount");m(this,zo,void 0);f(this,fa,r),f(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,fa).permissions.canLivestream)throw this.logger.error("Livestream::start::permission_denied"),new k("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const r=yt(),{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 k("Error while starting livestream","1900",this.logger)}}async stop(){if(!a(this,fa).permissions.canLivestream)throw this.logger.error("Livestream::stop::permission_denied"),new k("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 k("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),await yt().stopLivestreaming()}catch(e){throw this.logger.error("Livestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new k("Error while stopping livestream","1900",this.logger)}}}fa=new WeakMap,zo=new WeakMap,Kf([E.trace("livestream.start")],Mh.prototype,"start",1),Kf([E.trace("livestream.stop")],Mh.prototype,"stop",1);var wD=Object.defineProperty,PD=Object.getOwnPropertyDescriptor,_D=(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&&wD(t,e,i),i};class zf{constructor(t,e,r){p(this,"livestream");m(this,Sa,void 0);m(this,va,void 0);m(this,Tr,void 0);m(this,Gs,void 0);f(this,Gs,t),f(this,va,e),this.livestream=new Mh(t,e),f(this,Tr,r),this.setupEvents()}get logger(){return a(this,Gs).getValue("logger")}get telemetry(){return a(this,Gs).getValue("telemetry")}async fetchInitialLivestreamingState(){const t=yt(),{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,Tr).on(U.startedLivestream,async t=>{this.livestream.playbackUrl=t.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{a(this,va).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}}),a(this,Tr).on(U.livestreamingInvoked,async t=>{if(t.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{a(this,va).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}}),a(this,Tr).on(U.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),a(this,Tr).on(U.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),a(this,Tr).on(U.roomPeerCount,t=>{this.livestream.viewerCount=t.count,this.livestream.emit("viewerCountUpdate",t.count)}),a(this,Gs).getValue("peerSessionStore").on(_.PEER_JOINED_INTERNAL,async t=>{var e;((e=t.flags)==null?void 0:e.hiddenParticipant)===!0&&t.recorderType==="LIVESTREAMER"&&(f(this,Sa,t.id),this.livestream.setLivestreamState("LIVESTREAMING"))}),a(this,Gs).getValue("peerSessionStore").on(_.PEER_CLOSED,t=>{t.id===a(this,Sa)&&(f(this,Sa,void 0),this.livestream.setLivestreamState("IDLE"))}),a(this,Gs).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,Gs).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,async()=>{try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Error: LivestreamController.fetchLivestream")}})}}Sa=new WeakMap,va=new WeakMap,Tr=new WeakMap,Gs=new WeakMap,_D([E.trace("LivestreamController.setupEvents")],zf.prototype,"setupEvents",1);var RD=Object.defineProperty,CD=Object.getOwnPropertyDescriptor,Eo=(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&&RD(t,e,i),i};class Fn{constructor({name:t,socketHandler:e,meetingId:r}){m(this,_l);p(this,"name","");m(this,mt,{});m(this,si,"");m(this,ri,void 0);p(this,"rateLimitConfig",{maxInvocations:5,period:1});p(this,"bulkRateLimitConfig",{maxInvocations:5,period:1});p(this,"listeners",{});this.name=t,f(this,ri,e),f(this,si,r)}async set(t,e,r=!0,i=!1){a(this,mt)[t]=e,r&&this.remoteSet(t,e),i&&(this.listeners[t]&&this.listeners[t].forEach(n=>n({[t]:a(this,mt)[t]})),this.listeners["*"]&&this.listeners["*"].forEach(n=>n({[t]:a(this,mt)[t]})))}remoteSet(t,e){a(this,ri).storeInsertKeys(a(this,si),this.name,[{key:t,payload:e}])}async bulkSet(t){t.forEach(({key:e,payload:r})=>{a(this,mt)[e]=r}),a(this,ri).storeInsertKeys(a(this,si),this.name,t)}async update(t,e,r=!0){x(this,_l,rv).call(this,t,e,r)}async delete(t,e=!0,r=!1){if(a(this,mt)[t]&&delete a(this,mt)[t],e)return a(this,ri).storeDeleteKeys(a(this,si),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,mt)[e]&&delete a(this,mt)[e]}),a(this,ri).storeDeleteKeys(a(this,si),this.name,t)}get(t){if(a(this,mt)[t])return a(this,mt)[t]}getAll(){return a(this,mt)}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get bulkRateLimits(){return this.bulkRateLimitConfig}updateBulkRateLimits(t,e){this.bulkRateLimitConfig.maxInvocations=t,this.bulkRateLimitConfig.period=e}subscribe(t,e){if(this.listeners[t]){this.listeners[t].push(e);return}this.listeners[t]=[e]}unsubscribe(t,e){var r;if(e){this.listeners[t]=((r=this.listeners[t])==null?void 0:r.filter(i=>i!==e))||[];return}this.listeners[t]&&delete this.listeners[t]}populate(t){f(this,mt,t)}}mt=new WeakMap,si=new WeakMap,ri=new WeakMap,_l=new WeakSet,rv=function(t,e,r=!0){let i;const n=a(this,mt)[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)},Eo([Ot(Vn,"rateLimitConfig")],Fn.prototype,"remoteSet",1),Eo([Ot(Vn,"bulkRateLimitConfig")],Fn.prototype,"bulkSet",1),Eo([Ot(Vn,"rateLimitConfig")],Fn.prototype,"update",1),Eo([Ot(Vn,"rateLimitConfig")],Fn.prototype,"delete",1),Eo([Ot(Vn,"bulkRateLimitConfig")],Fn.prototype,"bulkDelete",1);class kD{constructor(t,e){m(this,Yo);m(this,Rl);p(this,"stores",new Map);m(this,zi,void 0);m(this,Yi,"");m(this,Qo,void 0);m(this,ii,new Map);f(this,zi,e),f(this,Yi,t.getValue("meetingId")),f(this,Qo,t),x(this,Rl,iv).call(this)}create(t){const e=new Fn({name:t,socketHandler:a(this,zi),meetingId:a(this,Yi)});return a(this,zi).storeGetKeys(a(this,Yi),t,[]),new Promise((i,n)=>{const o=setTimeout(()=>n(Error("Failed")),3e3);a(this,ii).set(t,{rejectTimeout:o,resolve:i,store:e})})}}zi=new WeakMap,Yi=new WeakMap,Yo=new WeakSet,ip=function(){return a(this,Qo).getValue("peerId")},Qo=new WeakMap,ii=new WeakMap,Rl=new WeakSet,iv=function(){[G.storeInsertKeys,G.storeGetKeys,G.storeDeleteKeys].forEach(t=>{a(this,zi).on(t,async e=>{var n,o;if(e.pluginId!==a(this,Yi))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===G.storeGetKeys){const c=a(this,ii).get(e.storeName),d=this.stores.get(e.storeName)||(c==null?void 0:c.store);a(this,ii).get(e.storeName)&&(this.stores.set(e.storeName,c.store),c.resolve(d),clearTimeout(c.rejectTimeout),a(this,ii).delete(e.storeName)),r.forEach(l=>{d.set(l.key,l.payload,!1,!1)});return}const i=this.stores.get(e.storeName)||((o=a(this,ii).get(e.storeName))==null?void 0:o.store);i!==void 0&&(t===G.storeInsertKeys&&r.forEach(({key:c,peerId:d,payload:l})=>{d!==a(this,Yo,ip)&&i.set(c,l,!1,!0)}),t===G.storeDeleteKeys&&r.forEach(({key:c,peerId:d})=>{d!==a(this,Yo,ip)&&i.delete(c,!1,!0)}))})})};function ki(s){var t,e,r,i,n,o,c,d,l,u,h,g,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=(g=s.screenShareTracks)==null?void 0:g.video)==null?void 0:S.id}}}}:{}}var ID=Object.defineProperty,AD=Object.getOwnPropertyDescriptor,$n=(s,t,e,r)=>{for(var i=r>1?void 0:r?AD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ID(t,e,i),i};const MD=.8,OD=1.2;let dr=(WS=class extends $t{constructor(t,e,r,i){const n=t.getValue("logger");super(n);m(this,Qi);m(this,ni);m(this,Xi);m(this,Cl);m(this,Zi);m(this,Zo);m(this,Il);m(this,Al);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,Ta,void 0);p(this,"supportsRemoteControl",!1);m(this,ya,void 0);p(this,"presetName");m(this,zt,void 0);m(this,yr,void 0);m(this,Xo,void 0);m(this,ai,new Map);m(this,Er,1);m(this,kl,ju(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>OD&&a(this,Er)===1?(f(this,Er,0),a(this,zt).getValue("peerSessionStore").emit(_.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,Er)})):d<MD&&a(this,Er)===0&&(f(this,Er,1),a(this,zt).getValue("peerSessionStore").emit(_.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,Er)}))},2e3));f(this,zt,t);const{id:o,userId:c,displayName:d,device:l,picture:u,isHost:h,flags:g,clientSpecificId:S,stageStatus:y,customParticipantId:w,audioMuted:b,audioTrack:C,videoEnabled:D=!1,videoTrack:F,producers:L,metadata:B}=e;this.id=o,this.userId=c,this.name=d,this.device=l,this.picture=u,this.isHost=h,this.flags=g,this.manualProducerConfig=B_,f(this,ya,y!=null?y:"ON_STAGE"),this.customParticipantId=w!=null?w:S,this.audioEnabled=!b,this.audioTrack=C,this.videoEnabled=D,this.videoTrack=F,this.screenShareTracks={audio:void 0,video:void 0},this.producers=L!=null?L:[],this.presetName=B==null?void 0:B.preset_name,f(this,Ta,!1),f(this,yr,r),f(this,Xo,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),x(this,Zo,np).call(this)}get clientSpecificId(){return this.customParticipantId}get stageStatus(){return a(this,ya)}get telemetry(){return a(this,zt).getValue("telemetry")}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(this.logger.info("Participant::setVideoEnabled::videoUpdate",{...ki(this)}),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(this.logger.info("Participant::setAudioEnabled::audioUpdate",{...ki(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",x(this,Zo,np)),a(this,ni,Ya)&&(this.on("audioUpdate",x(this,Il,av)),this.on("screenShareUpdate",x(this,Al,ov)))}async pin(){if(!a(this,Xi,Zc))throw new k("Can`t pin participant without joining room","1205");if(!a(this,yr).permissions.pinParticipant)throw new k("You do not have permission to pin participants.","1201");return a(this,Qi,Xc).pinPeer(this.id)}async unpin(){if(!a(this,Xi,Zc))throw new k("Can`t unpin participant without joining room","1205");if(!a(this,yr).permissions.pinParticipant)throw new k("You do not have permission to unpin participants.","1201");return a(this,Qi,Xc).pinPeer(null)}setIsPinned(t,e=!0){var i;f(this,Ta,t);const r=t?"pinned":"unpinned";(i=a(this,Zi,ed))==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,Zc))throw new k("Can`t disable participant audio without joining room","1205");if(a(this,yr).permissions.canDisableParticipantAudio)return a(this,Qi,Xc).disableAudio(t);throw this.logger.error("Participant::unauthorized_disable_audio",{participant:{id:t}}),new k("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,Cl,nv))throw new k("Can`t kick participant without joining room","1205");if(a(this,yr).permissions.kickParticipant){await a(this,zt).getValue("peerSessionStore").emitAsync(_.KICK_PEER,{peerId:t});return}throw this.logger.error("Participant::unauthorized_kick",{participant:{id:t}}),new k("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,Zc))throw new k("Can`t disable participant video without joining room","1205");if(a(this,yr).permissions.canDisableParticipantVideo)return a(this,Qi,Xc).disableVideo(t);throw this.logger.error("Participant::unauthorized_disable_video",{participant:{id:t}}),new k("Unauthorized: User does not have permission to disable participant video.","1201")}async getPermissions(){return a(this,Xo).getUserPermissions(this.userId)}setStageStatus(t){f(this,ya,t),this.emit("stageStatusUpdate",this)}get isPinned(){return a(this,Ta)}registerVideoElement(t){var r,i,n,o;if(!t)return;let e;(i=(r=a(this,ai).get(t))==null?void 0:r.observer)==null||i.disconnect(),"ResizeObserver"in window&&(e=new ResizeObserver(()=>a(this,kl).call(this,t)),e.observe(t)),a(this,ai).set(t,{observer:e}),this.updateVideo(t),(o=a(this,Zi,ed))==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,ed))==null||e.removeSource(this.id);return}t.srcObject=void 0,(i=(r=a(this,ai).get(t))==null?void 0:r.observer)==null||i.disconnect(),a(this,ai).delete(t),(n=a(this,Zi,ed))==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"}},Ta=new WeakMap,ya=new WeakMap,zt=new WeakMap,Qi=new WeakSet,Xc=function(){return a(this,zt).getValue("roomNodeClient")},ni=new WeakSet,Ya=function(){return a(this,zt).getValue("audioPlayback")},Xi=new WeakSet,Zc=function(){return a(this,zt).getValue("connectionHandler").mediaJoined},Cl=new WeakSet,nv=function(){return a(this,zt).getValue("connectionHandler").socketJoined},yr=new WeakMap,Xo=new WeakMap,ai=new WeakMap,Zi=new WeakSet,ed=function(){return a(this,zt).getValue("pip")},Er=new WeakMap,kl=new WeakMap,Zo=new WeakSet,np=function(){Array.from(a(this,ai).keys()).forEach(this.updateVideo)},Il=new WeakSet,av=function(){var t,e;this.audioEnabled&&this.audioTrack?(t=a(this,ni,Ya))==null||t.addParticipantTrack(this.id,this.audioTrack):(e=a(this,ni,Ya))==null||e.removeParticipantTrack(this.id)},Al=new WeakSet,ov=function(){var t,e;this.screenShareEnabled&&this.screenShareTracks.audio?(t=a(this,ni,Ya))==null||t.addParticipantTrack(`screenshare-${this.id}`,this.screenShareTracks.audio):(e=a(this,ni,Ya))==null||e.removeParticipantTrack(`screenshare-${this.id}`)},WS);$n([E.trace("Participant.disableAudio")],dr.prototype,"disableAudio",1),$n([E.trace("Participant.kick")],dr.prototype,"kick",1),$n([E.trace("Participant.disableVideo")],dr.prototype,"disableVideo",1),$n([E.trace("Participant.getPermissions")],dr.prototype,"getPermissions",1),$n([E.trace("Participant.setStageStatus")],dr.prototype,"setStageStatus",1),dr=$n([ut("1200")],dr);class bo extends Mf{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 DD extends Dn{constructor(e){super(e);m(this,oi,void 0);f(this,oi,new Map)}__set(e,r){return a(this,oi).set(e,r)}__clear(){return a(this,oi).clear()}get(e){return a(this,oi).get(e)}toArray(){return Array.from(a(this,oi).values())}}oi=new WeakMap;class ND{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 VD{constructor(){p(this,"_activeSpeakerPeers");p(this,"_compulsoryPeers");this._activeSpeakerPeers=new ND,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 Yf=new VD;var LD=Object.defineProperty,xD=Object.getOwnPropertyDescriptor,jt=(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&&LD(t,e,i),i};const UD=["ACTIVE_GRID","PAGINATED","MANUAL"];let Et=(JS=class extends $t{constructor(t,e,r){const i=t.getValue("logger");super(i);m(this,ec);m(this,en);m(this,Ea);p(this,"waitlisted");p(this,"joined");p(this,"active");p(this,"videoSubscribed");p(this,"audioSubscribed");p(this,"pinned");p(this,"all");m(this,Re,void 0);m(this,tn,void 0);m(this,Vt,void 0);p(this,"rateLimitConfig",{maxInvocations:5,period:1});p(this,"viewMode");p(this,"currentPage");p(this,"lastActiveSpeaker");p(this,"selectedPeers",Yf);f(this,Re,t),f(this,tn,e),f(this,Vt,r),this.waitlisted=new bo(i),this.joined=new bo(i),this.videoSubscribed=new bo(i),this.audioSubscribed=new bo(i),this.active=this.videoSubscribed,this.pinned=new bo(i),this.all=new DD(i),this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return a(this,Re).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get telemetry(){return a(this,Re).getValue("telemetry")}setupEvents(){a(this,Re).getValue("peerSessionStore").on(_.E2EE_ACTIVE_CONSUMER,({peerId:e})=>{var r;((r=a(this,Re).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,Re).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,Re))==null?void 0:t.getValue("maxPreferredStreams")}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new k("0 <= Max active participants count limit <= 24","1203");a(this,Re).setValue("maxPreferredStreams",t),a(this,Ea,mu)&&a(this,Re).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,td))throw new k("Can`t accept waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;return a(this,Vt).acceptWaitingRoomRequest([e])}async acceptAllWaitingRoomRequest(t){const e=t.map(r=>{var i,n;return(n=(i=this.waitlisted.get(r))==null?void 0:i.userId)!=null?n:r});return a(this,Vt).acceptWaitingRoomRequest(e)}async rejectWaitingRoomRequest(t){var r,i;if(!a(this,en,td))throw new k("Can`t reject waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;a(this,Vt).rejectWaitingRoomRequest([e])}async setViewMode(t){if(this.logger.info("Participants::set_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),!(r=>UD.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 k(`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,Re).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="ACTIVE_GRID"?(this.currentPage=0,a(this,Re).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="MANUAL"&&(this.currentPage=0,a(this,Re).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 k("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,Re).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 k("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,Re).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 k(`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,Re).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,Ea,mu))throw new k("Can`t disable all audio without joining room","1205");if(a(this,tn).permissions.canAllowParticipantAudio)return a(this,ec,ap).muteAll(t);throw this.logger.error("Participants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new k("Unauthorized: User does not have permission to disable peer audio.","1201")}async disableAllVideo(){if(this.logger.info("Participants::disable_all_video"),!a(this,Ea,mu))throw new k("Can`t disable all video without joining room","1205");if(a(this,tn).permissions.canAllowParticipantVideo)return a(this,ec,ap).muteAllVideo();throw this.logger.error("Participants::unauthorized_disable_all_video"),new k("Unauthorized: User does not have permission to disable peer video.","1201")}async disableAudio(t){this.joined.get(t).disableAudio()}async disableVideo(t){this.joined.get(t).disableVideo()}async kick(t){await a(this,Re).getValue("peerSessionStore").emitAsync(_.KICK_PEER,{peerId:t})}async kickAll(){if(this.logger.info("Participants::kick_all"),a(this,Re).getValue("viewType")!=="LIVESTREAM"&&!a(this,en,td))throw new k("Can`t kick all without joining room","1205");if(!a(this,tn).permissions.kickParticipant)throw this.logger.error("Participants::unauthorized_kick_all"),new k("Unauthorized: User does not have permission to kick peers.","1201");const e=a(this,Re).getValue("flagsmith").hasFeature(Z.PROPAGATE_KICK_ALL);a(this,Vt).kickAll(e)}async broadcastMessage(t,e,r){if(this.logger.info("Participants::broadcastMessage"),!a(this,en,td))throw new k("Can`t broadcast message without joining room","1205");if(!(t!=null&&t.trim()))throw new k("`type` must be a non-empty string.","1209");if(r)if("meetingIds"in r)await a(this,Vt).broadcastToMeetings(t,r.meetingIds,e);else{let i=[];"participantIds"in r?i=r.participantIds:i=this.joined.toArray().filter(n=>{var o;return(o=r.presetNames)==null?void 0:o.includes(n.presetName)}).map(n=>n.id),await a(this,Vt).broadcastToPeers(t,i,e)}else await a(this,Vt).broadcastMessage(t,e)}async getAllJoinedPeers(t,e,r){return(await a(this,Vt).getRoomPeers(t,e,r)).peers.map(lr.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 k("Cannot update permissions, no valid userIDs found","1204");a(this,Vt).updatePermissions(i,e)}async getParticipantsInMeetingPreJoin(){return a(this,Vt).getRoomPeersNonPaginated()}},Re=new WeakMap,ec=new WeakSet,ap=function(){return a(this,Re).getValue("roomNodeClient")},en=new WeakSet,td=function(){var t;return((t=a(this,Re).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},Ea=new WeakSet,mu=function(){var t;return((t=a(this,Re).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},tn=new WeakMap,Vt=new WeakMap,JS);jt([E.trace("Participants.setViewMode")],Et.prototype,"setViewMode",1),jt([E.trace("Participants.setPage")],Et.prototype,"setPage",1),jt([E.trace("Participants.disableAllAudio")],Et.prototype,"disableAllAudio",1),jt([E.trace("Participants.disableAllVideo")],Et.prototype,"disableAllVideo",1),jt([E.trace("Participants.disablePeerAudio")],Et.prototype,"disableAudio",1),jt([E.trace("Participants.disablePeerVideo")],Et.prototype,"disableVideo",1),jt([E.trace("Participants.kickPeer")],Et.prototype,"kick",1),jt([E.trace("Participants.kickAll")],Et.prototype,"kickAll",1),jt([E.trace("Participants.broadcastMessage"),Ot(Vn,"rateLimitConfig")],Et.prototype,"broadcastMessage",1),jt([E.trace("Participants.getAllJoinedPeers"),Ot({maxInvocations:10,period:60})],Et.prototype,"getAllJoinedPeers",1),jt([E.trace("Participant.updatePermissions"),Ot({maxInvocations:1e3,period:60})],Et.prototype,"updatePermissions",1),jt([E.trace("Participants.getParticipantsInMeetingPreJoin")],Et.prototype,"getParticipantsInMeetingPreJoin",1),Et=jt([ut("1200")],Et);var FD=Object.defineProperty,$D=Object.getOwnPropertyDescriptor,Ii=(s,t,e,r)=>{for(var i=r>1?void 0:r?$D(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&FD(t,e,i),i};const Qf=(KS=class{constructor(s,t,e){p(this,"participants");p(this,"self");p(this,"selectedPeers",Yf);p(this,"maxSpatialLayerUpdates",new Map);p(this,"consumerPeerMap");p(this,"events");p(this,"roomSocketHandler");p(this,"context");p(this,"videoPeerConsumerMap",new Map);m(this,us,{mode:"ACTIVE_GRID",page:0});m(this,ks,!1);m(this,ba,!1);p(this,"updateConsumerSpatialLayers",ju(()=>{const s={},t=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(t.entries()).forEach(([e,r])=>{s[r]===void 0&&(s[r]={layer:r,consumerIds:[]}),s[r].consumerIds.push(e)}),Object.keys(s).forEach(e=>{const r=s[e];this.logger.log(`Switching max spatial layer to ${r.layer}`,{consumerIds:r.consumerIds}),this.roomNodeClient.switchConsumersToLayer(r.consumerIds,r.layer)})},2e3));p(this,"updateConsumers",async(s,t)=>{this.logger.info(`updateConsumers: Starting consumer updates - AddProducers: ${s.length}, RemoveProducers: ${t.length}, ConsumersSyncing: ${a(this,ks)}`);try{s.length!==0&&(this.logger.info(`updateConsumers: Creating consumers for ${s.length} producers: [${s.map(e=>e.producerId).join(", ")}]`),await this.roomNodeClient.createConsumers(s),this.logger.info("updateConsumers: Successfully created consumers."))}catch(e){this.logger.error("updateConsumers: Error creating consumers",{error:e})}try{t.length!==0&&(this.logger.info(`updateConsumers: Closing consumers for ${t.length} producers: [${t.map(e=>e.producerId).join(", ")}]`),await this.roomNodeClient.closeConsumers(t),this.logger.info("updateConsumers: Successfully closed consumers."))}catch(e){this.logger.error("updateConsumers: Error closing consumers",{error:e})}this.logger.info("updateConsumers: Completed consumer updates.")});this.context=s,this.roomSocketHandler=e,this.participants=new Et(s,t,this.roomSocketHandler),this.self=t,this.consumerPeerMap=new Map,this.events=ys,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(U.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),this.context.getValue("peerSessionStore").on(_.SOCKET_PEERS,async s=>{const t=this.context.getValue("flagsmith").hasFeature(Z.DEBUG_SOCKET_JOIN);if(t){const e=s&&(s==null?void 0:s.length)<20?{peers:JSON.stringify(s.map(r=>r.peerId))}:void 0;this.logger.info("Processing socket peers",e)}s==null||s.forEach(e=>{e.waitlisted||this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(e))}),t&&this.logger.info("Processed socket peers")}),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.logger.info("events.peerJoinedBroadcast",{peers:s.peerId}),this.onParticipantMediaJoined(s.peerId,s.producerStates,s.capabilities)}),this.roomSocketHandler.on(this.events.selfJoinComplete,({participants:s,selectedPeers:t,roomState:e})=>{if(this.context.getValue("flagsmith").hasFeature(Z.DEBUG_SOCKET_JOIN)){const n=s&&(s==null?void 0:s.length)<20?{peers:JSON.stringify(s.map(o=>o.peerId))}:void 0;this.logger.info("events.selfJoinComplete",n)}s.forEach(({peerId:n,producerStates:o,capabilities:c})=>this.onParticipantMediaJoined(n,o,c));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.context.getValue("flagsmith").hasFeature(Z.DISABLE_LAYER_SWITCH)||(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,ks)}, 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,ks)}, 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 dr(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,us).mode!==s&&(a(this,us).mode=s),e&&a(this,us).page!==e&&(a(this,us).page=e);const{mode:r,page:i}=a(this,us);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,us))==null?void 0:e.mode)==="PAGINATED"&&!a(this,ks)?200:0;this.logger.info(`scheduleSyncConsumers():: Source: ${s}, ViewMode: ${(r=a(this,us))==null?void 0:r.mode}, ConsumersSyncing: ${a(this,ks)}, Delay: ${t}, Page: ${(i=a(this,us))==null?void 0:i.page}`),setTimeout(()=>this.syncConsumers(),t)}async syncConsumers(){var o,c,d,l,u;if(((d=(c=(o=this.context.getValue("connectionHandler"))==null?void 0:o.mediaState)==null?void 0:c.recv)==null?void 0:d.state)!=="connected"){this.logger.info("syncConsumers: Connection not ready, exiting.");return}if(a(this,ks)){f(this,ba,!0),this.logger.info("syncConsumers: Sync in progress, marking resyncRequired=true and exiting.");return}this.logger.info("syncConsumers: Starting sync operation."),f(this,ks,!0),f(this,ba,!1);let s=[];this.participants.videoSubscribed.forEach(h=>{var y,w;const g=this.participants.joined.get(h.id),S=(w=(y=h.producers)==null?void 0:y.filter(b=>b.kind==="video"))!=null?w:[];g&&(S!=null&&S.length)&&S.forEach(b=>{var F,L,B,Q;const C=((L=(F=g.manualProducerConfig)==null?void 0:F.video)!=null?L:!0)&&b.kind==="video"&&!b.screenShare,D=((Q=(B=g.manualProducerConfig)==null?void 0:B.screenshareVideo)!=null?Q:!0)&&b.kind==="video"&&b.screenShare;(C||D)&&(b.pause||s.push(b))})}),this.participants.audioSubscribed.forEach(h=>{var y,w;const g=this.participants.joined.get(h.id),S=(w=(y=h.producers)==null?void 0:y.filter(b=>b.kind==="audio"))!=null?w:[];g&&(S!=null&&S.length)&&S.forEach(b=>{var F,L,B,Q;const C=((L=(F=g.manualProducerConfig)==null?void 0:F.audio)!=null?L:!0)&&b.kind==="audio"&&!b.screenShare,D=((Q=(B=g.manualProducerConfig)==null?void 0:B.screenshareAudio)!=null?Q:!0)&&b.kind==="audio"&&b.screenShare;(C||D)&&s.push(b)})}),s=$_(s,h=>h.producerId);const t=new Map;s.forEach(h=>{t.set(h.producerId,h)});const e=(l=this.roomNodeClient)==null?void 0:l.getConsumers(),r=s.filter(h=>!(e!=null&&e.has(h.producerId))),i=[];let n=Array.from((u=e==null?void 0:e.values())!=null?u:[]).map(h=>h.peerId);n=F_(n),n==null||n.forEach(h=>{var S;const g=this.participants.joined.get(h);if(!g){this.logger.warn(`Peer with ${h} doesn't exist in joined list but producers of it are being consumed.`);return}(S=g.producers)!=null&&S.length&&g.producers.forEach(y=>{const w=y.consumer&&e.has(y.consumer.id);!t.has(y.producerId)&&(e.has(y.producerId)||w)&&i.push(y)})}),this.logger.info(`syncConsumers: Computed changes - AddProducers: ${r.length} [${r.map(h=>h.producerId).join(", ")}], RemoveProducers: ${i.length} [${i.map(h=>h.producerId).join(", ")}]`.substring(0,5e3));try{r.length>0||i.length>0?(this.logger.info(`syncConsumers: Calling updateConsumers with changes. Adding ${r.length} and removing ${i.length}.`),await this.updateConsumers(r,i),this.logger.info("syncConsumers: updateConsumers completed successfully.")):this.logger.info("syncConsumers: No changes needed, skipping updateConsumers.")}catch(h){this.logger.error("syncConsumers: updateConsumers failed with error.",{error:h})}finally{this.logger.info("syncConsumers: Setting consumersSyncing=false and completing sync."),f(this,ks,!1)}a(this,ba)&&(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=Qf.formatSocketPeerMessage(s);return new dr(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,e){if(!this.mediaJoined||s===this.self.id)return;const r=this.participants.joined.get(s);if(!r){this.logger.warn(`Received media.peerJoinedBroadcast for non-existent peer ${s}`);return}this.logger.info("PEER_INFO:::SOCKET_ON_MEDIA_JOIN",{participant:{id:r.id,maskedName:[...(r==null?void 0:r.name)||""].map((i,n)=>n%2?"*":i).join("")}}),this.logger.info(`onParticipantMediaJoined: peer ${s} has joined media room. Processing.`),t.forEach(i=>{i.kind===Bs.AUDIO&&!i.screenShare?r.setAudioEnabled(!i.pause):i.kind===Bs.VIDEO&&!i.screenShare&&(r.setVideoEnabled(!i.pause),this.updatePipSource(r.id,!i.pause)),r.producers.push({...i,producingTransportId:i.producingTransportId,kind:i.kind===Bs.AUDIO?"audio":"video",producingPeerId:s,mimeType:i.mimeType})}),this.roomNodeClient.handlePeerCapabilities(s,e),this.context.getValue("flagsmith").hasFeature(Z.FORCE_VIDEO_CODEC)||this.roomNodeClient.shareWebcam(this.self.videoTrack),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(U.joinRoom,({peer:s})=>{if(!s.waitlisted){const t=this.context.getValue("flagsmith").hasFeature(Z.DEBUG_SOCKET_JOIN);t&&this.logger.info("Processing socket join",{peers:s.peerId}),this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(s)),t&&this.logger.info("Processed socket join",{peers:s.peerId})}}),this.roomSocketHandler.on(U.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,()=>{this.participants.joined.clear(),this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear(),this.participants.pinned.clear(),this.participants.currentPage=0,this.participants.viewMode="ACTIVE_GRID",this.participants.emit("viewModeChanged",{viewMode:"ACTIVE_GRID",currentPage:this.participants.currentPage,pageCount:this.participants.pageCount})}),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,({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,async({viewMode:s,page:t,createAllConsumers:e}={viewMode:"ACTIVE_GRID",page:0,createAllConsumers:!1})=>{this.logger.info(`UPDATE_ACTIVE event received - viewMode: ${a(this,us).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){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.handlePeerLeaving(s),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 g;const t=this.processMedia(s),{peerId:e,kind:r,appData:i,track:n,remotelyPaused:o,producerId:c,rtpReceiver:d,localId:l}=t;if(!e)return;this.logger.info("ParticipantController::processConsumerResumed",{consumer:{id:s,peerId:e,kind:r,appData:i,remotelyPaused:o,producerId:c}});const u=this.participants.joined.get(e);if(!u)return;const h=u.producers.find(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),(g=this.context)==null||g.getValue("callstats").consumerSharedMediaState(s,{screen:!0});return}r==="video"?(u.videoTrack=n,u.setVideoEnabled(!0),this.updatePipSource(u.id,!0),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!0})):r==="audio"&&(u.audioTrack=n,u.setAudioEnabled(u.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:u.audioEnabled}))}processConsumerPaused(s){this.logger.info(`ParticipantController::processConsumerPaused called for consumerId: ${s}`);const{peerId:t,kind:e,track:r,appData:i,remotelyPaused:n,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(s);if(!t)return;this.logger.info("ParticipantController::processConsumerPaused",{consumer:{id:s,peerId:t,kind:e,appData:i,remotelyPaused:n,producerId:o}});const l=this.participants.joined.get(t);if(!l)return;const u=l.producers.find(h=>h.producerId===o);u&&(u.consumer={id:s,peerId:t,kind:e,appData:i,paused:n,producerId:o,rtpReceiver:c,localId:d}),r&&i.e2ee&&this.context.getValue("peerSessionStore").emit(_.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||this.context.getValue("flagsmith").hasFeature(Z.SCREEENSHARE_ERR_HACK))&&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})}static formatSocketPeerMessage(s){var e,r,i,n,o,c;if(!s)return;const t=bh(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})}},us=new WeakMap,ks=new WeakMap,ba=new WeakMap,KS);let lr=Qf;Ii([E.trace("ParticipantController.setupEvents")],lr.prototype,"setupEvents",1),Ii([E.trace("ParticipantController.setupEvents")],lr.prototype,"setupEventsGlobal",1),Ii([E.trace("ParticipantController.processMedia")],lr.prototype,"processMedia",1),Ii([E.trace("ParticipantController.processConsumerClosed")],lr.prototype,"processConsumerClosed",1),Ii([E.trace("ParticipantController.processConsumerResumed")],lr.prototype,"processConsumerResumed",1),Ii([E.trace("ParticipantController.processConsumerPaused")],lr.prototype,"processConsumerPaused",1),Ii([E.trace("ParticipantController.processNewConsumer")],lr.prototype,"processNewConsumer",1);const Te=Hs(Fu().permissions),_a=class extends $t{constructor(e,r,i,n=!1){const o=e.getValue("logger");super(o);m(this,Rt);m(this,q,void 0);m(this,wa,void 0);m(this,Pa,void 0);m(this,Ml,e=>{var l,u,h;const{chat:r,connectedMeetings:i,plugins:n,polls:o,media:c,...d}=e;if(r&&(r.private&&Lr(a(this,q).chat.private,r.private),r.public&&Lr(a(this,q).chat.public,r.public),this.emit("chatUpdate")),i&&Lr(a(this,q).connectedMeetings,i),c){const g=y=>{switch(y){case xr.NONE:return H.Allowed;case xr.ALLOWED:return H.Allowed;case xr.NOT_ALLOWED:return H.NotAllowed;case xr.CAN_REQUEST:return H.CanRequest;default:return}},S={audio:void 0,video:void 0,screenshare:void 0};(l=c.audio)!=null&&l.canProduce&&(S.audio={canProduce:g(c.audio.canProduce)}),(u=c.video)!=null&&u.canProduce&&(S.video={canProduce:g(c.video.canProduce)}),(h=c.screenshare)!=null&&h.canProduce&&(S.screenshare={canProduce:g(c.screenshare.canProduce)}),Lr(a(this,q).media,S)}n&&(Lr(a(this,q).plugins,n),this.emit("pluginsUpdate")),o&&(Lr(a(this,q).polls,o),this.emit("pollsUpdate")),Object.keys(d).length!==0&&Lr(a(this,q),d),this.emit("permissionsUpdate",e)});if(!r)throw this.logger.error("PermissionPreset::load_preset_permissions_failed"),new k("Could not load preset permissions.","0904");f(this,Pa,e),f(this,wa,i),f(this,q,r),n&&this.setupEvents()}setupEvents(){a(this,Pa).getValue("peerSessionStore").on(_.UPDATE_PERMISSIONS,a(this,Ml))}static fromResponse(e,r,i){return new _a(i,e,r,!0)}static default(e,r){return new _a(e,Te,r)}static init(e,r,i){let n;return i?n=new _a(e,i,r,!0):n=new _a(e,Te,r),n}get mediaRoomType(){return"CF"}get stageEnabled(){var e;return((e=a(this,q))==null?void 0:e.stageEnabled)||a(this,wa)===tr.Webinar||a(this,wa)===tr.Livestream}get acceptStageRequests(){var e,r;return this.stageEnabled?((e=a(this,q))==null?void 0:e.acceptStageRequests)||((r=a(this,q))==null?void 0:r.canAcceptProductionRequests):!1}get stageAccess(){var e,r,i;return((e=a(this,q))==null?void 0:e.stageAccess)===H.NotAllowed?H.NotAllowed:((r=a(this,q))==null?void 0:r.stageAccess)===H.CanRequest?H.CanRequest:((i=a(this,q))==null?void 0:i.stageAccess)===H.Allowed||a(this,q).media.audio.canProduce===H.Allowed||a(this,q).media.video.canProduce===H.Allowed||a(this,q).media.screenshare.canProduce===H.Allowed?H.Allowed:a(this,q).media.audio.canProduce===H.CanRequest||a(this,q).media.video.canProduce===H.CanRequest||a(this,q).media.screenshare.canProduce===H.CanRequest?H.CanRequest:H.NotAllowed}get acceptWaitingRequests(){var e,r;return(r=(e=a(this,q))==null?void 0:e.acceptWaitingRequests)!=null?r:Te.acceptWaitingRequests}get requestProduceVideo(){var e,r,i;return((i=(r=(e=a(this,q))==null?void 0:e.media)==null?void 0:r.video)==null?void 0:i.canProduce)===H.CanRequest}get requestProduceAudio(){var e,r,i;return((i=(r=(e=a(this,q))==null?void 0:e.media)==null?void 0:r.audio)==null?void 0:i.canProduce)===H.CanRequest}get requestProduceScreenshare(){var e,r,i;return((i=(r=(e=a(this,q))==null?void 0:e.media)==null?void 0:r.screenshare)==null?void 0:i.canProduce)===H.CanRequest}get canAllowParticipantAudio(){var e,r;return(r=(e=a(this,q))==null?void 0:e.disableParticipantAudio)!=null?r:Te.disableParticipantAudio}get canAllowParticipantScreensharing(){var e,r;return(r=(e=a(this,q))==null?void 0:e.canAcceptProductionRequests)!=null?r:Te.canAcceptProductionRequests}get canAllowParticipantVideo(){var e,r;return(r=(e=a(this,q))==null?void 0:e.disableParticipantVideo)!=null?r:Te.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var e,r;return(r=(e=a(this,q))==null?void 0:e.kickParticipant)!=null?r:Te.kickParticipant}get pinParticipant(){var e,r;return(r=(e=a(this,q))==null?void 0:e.pinParticipant)!=null?r:Te.pinParticipant}get canRecord(){var e,r;return(r=(e=a(this,q))==null?void 0:e.canRecord)!=null?r:Te.canRecord}get waitingRoomType(){var e,r;return(r=(e=a(this,q))==null?void 0:e.waitingRoomType)!=null?r:Te.waitingRoomType}get waitingRoomBehaviour(){var e,r;return(r=(e=a(this,q))==null?void 0:e.waitingRoomType)!=null?r:Te.waitingRoomType}get plugins(){var e,r;return(r=(e=a(this,q))==null?void 0:e.plugins)!=null?r:Te.plugins}get polls(){var e,r;return(r=(e=a(this,q))==null?void 0:e.polls)!=null?r:Te.polls}get produceVideo(){return this.canProduceVideo}get requestProduce(){return a(this,q).media.audio.canProduce===H.CanRequest||a(this,q).media.video.canProduce===H.CanRequest||a(this,q).media.screenshare.canProduce===H.CanRequest}get canProduceVideo(){var r;const e=(r=a(this,q).media.video.canProduce)!=null?r:Te.media.video.canProduce;return this.stageEnabled&&(a(this,Rt,Zt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Rt,Zt)==="ON_STAGE")&&e===H.CanRequest?H.Allowed:this.stageEnabled&&(a(this,Rt,Zt)==="OFF_STAGE"||a(this,Rt,Zt)==="REQUESTED_TO_JOIN_STAGE")&&e===H.Allowed?H.NotAllowed:e}get produceScreenshare(){return this.canProduceScreenshare}get canProduceScreenshare(){var r;const e=(r=a(this,q).media.screenshare.canProduce)!=null?r:Te.media.screenshare.canProduce;return this.stageEnabled&&(a(this,Rt,Zt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Rt,Zt)==="ON_STAGE")&&e===H.CanRequest?H.Allowed:this.stageEnabled&&(a(this,Rt,Zt)==="OFF_STAGE"||a(this,Rt,Zt)==="REQUESTED_TO_JOIN_STAGE")&&e===H.Allowed?H.NotAllowed:e}get produceAudio(){return this.canProduceAudio}get canProduceAudio(){var r;const e=(r=a(this,q).media.audio.canProduce)!=null?r:Te.media.audio.canProduce;return this.stageEnabled&&(a(this,Rt,Zt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Rt,Zt)==="ON_STAGE")&&e===H.CanRequest?H.Allowed:this.stageEnabled&&(a(this,Rt,Zt)==="OFF_STAGE"||a(this,Rt,Zt)==="REQUESTED_TO_JOIN_STAGE")&&e===H.Allowed?H.NotAllowed:e}get chatPublic(){var e,r,i;return(i=(r=(e=a(this,q))==null?void 0:e.chat)==null?void 0:r.public)!=null?i:Te.chat.public}get chatPrivate(){var e,r,i;return(i=(r=(e=a(this,q))==null?void 0:e.chat)==null?void 0:r.private)!=null?i:Te.chat.private}get connectedMeetings(){var e,r;return(r=(e=a(this,q))==null?void 0:e.connectedMeetings)!=null?r:Te==null?void 0:Te.connectedMeetings}get hiddenParticipant(){var e,r;return(r=(e=a(this,q))==null?void 0:e.hiddenParticipant)!=null?r:Te.hiddenParticipant}get showParticipantList(){var e;return(e=a(this,q).showParticipantList)!=null?e:Te.showParticipantList}get canChangeParticipantRole(){var e,r;return(r=(e=a(this,q))==null?void 0:e.canChangeParticipantPermissions)!=null?r:Te.canChangeParticipantPermissions}get canChangeParticipantPermissions(){var e,r;return(r=(e=a(this,q))==null?void 0:e.canChangeParticipantPermissions)!=null?r:Te.canChangeParticipantPermissions}get canChangeTheme(){return!1}get canPresent(){return a(this,q).media.audio.canProduce===H.Allowed||a(this,q).media.video.canProduce===H.Allowed||a(this,q).media.screenshare.canProduce===H.Allowed}get acceptPresentRequests(){return this.acceptStageRequests}get canEditDisplayName(){var e;return(e=a(this,q).canEditDisplayName)!=null?e:!1}get maxScreenShareCount(){return 1}get isRecorder(){return a(this,q).isRecorder}get canSpotlight(){return a(this,q).canSpotlight}get canLivestream(){return a(this,q).canLivestream}get transcriptionEnabled(){return a(this,q).transcriptionEnabled}};let Oh=_a;q=new WeakMap,wa=new WeakMap,Pa=new WeakMap,Ml=new WeakMap,Rt=new WeakSet,Zt=function(){return a(this,Pa).getValue("stageStatus")};class Xf extends $t{constructor(e,r){super(r);p(this,"localMediaHandler");m(this,Yt,void 0);f(this,Yt,e)}async updatePermission(){var d,l;const e=(u,h)=>{this.mediaPermissions[u]=h;const g={message:this.mediaPermissions[u],kind:u};h==="DENIED"?a(this,Yt).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_ERROR,g):a(this,Yt).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,g)};if(we.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,Yt))==null||i.getValue("callstats").mediaPermission("AUDIO",e),(n=a(this,Yt))==null||n.getValue("callstats").mediaPermission("SPEAKER",e);break}case"video":{(o=a(this,Yt))==null||o.getValue("callstats").mediaPermission("VIDEO",e);break}case"screenshare":{(c=a(this,Yt))==null||c.getValue("callstats").mediaPermission("SCREENSHARE",e);break}}}get peerId(){var e;return(e=a(this,Yt))==null?void 0:e.getValue("peerId")}async init(e={},r=!1,i=null){var n,o,c,d,l,u,h;if(we.init(),i&&f(this,Yt,i),!this.localMediaHandler)try{let g=!0;if((n=i==null?void 0:i.getValue("defaults"))!=null&&n.mediaHandler)g=!1,this.localMediaHandler=i.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:S}=navigator;this.localMediaHandler=await S.init(e)}else this.localMediaHandler=new Dt(i,e.constraints,(o=i==null?void 0:i.getValue("defaults"))==null?void 0:o.isNonPreferredDevice,(c=i==null?void 0:i.getValue("defaults"))==null?void 0:c.autoSwitchAudioDevice);if(i==null||i.getValue("peerSessionStore").on(_.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:y,message:w,constraints:b}=S;this.populateMediaPermissionsInCallstats({message:w,kind:y}),y==="audio"?(this.logger.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):y==="video"&&(this.logger.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),this.logger.error("SelfController::mediaPermissionError",{error:{message:w},constraints:b,mediaPermissionsErrors:{kind:y,message:w}}),this.emit("mediaPermissionError",S),this.emit("mediaPermissionUpdate",{message:w,kind:y})}),g){this.logger.info(`Setting up SelfMedia streams using media handler. audio:${(d=e==null?void 0:e.audio)!=null?d:!0} video:${(l=e==null?void 0:e.video)!=null?l:!0}`);const 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(g){this.logger.error("Self::init::Failed To Setup Streams",{error:{name:g.name,message:g.message}})}}set context(e){f(this,Yt,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})}}Yt=new WeakMap;var BD=Object.defineProperty,HD=Object.getOwnPropertyDescriptor,bt=(s,t,e,r)=>{for(var i=r>1?void 0:r?HD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&BD(t,e,i),i};let Ze=(zS=class extends Xf{constructor(t,e,r,i,n){var c;const o=t.getValue("logger");super(t,o);m(this,br);m(this,ze);m(this,ka);m(this,He);m(this,tc);p(this,"name");p(this,"picture");p(this,"customParticipantId");p(this,"waitlistStatus");m(this,Ra,void 0);m(this,Ct,void 0);m(this,Ca,void 0);p(this,"role");p(this,"userId");p(this,"organizationId");p(this,"supportsRemoteControl",!1);p(this,"device");m(this,We,void 0);p(this,"hidden",!1);p(this,"presetName");p(this,"roomState","init");m(this,Ia,new Set);m(this,Aa,new Set);f(this,We,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=(c=e.customParticipantId)!=null?c:e.clientSpecificId,this.waitlistStatus="none",f(this,Ct,r),f(this,Ra,i),this.hidden=!1,f(this,Ca,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=we.isElectron(),this.device=we.getDeviceInfo(),this.presetName=n,this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),x(this,tc,op).call(this)}get telemetry(){return a(this,We).getValue("telemetry")}get stageStatus(){return a(this,We).getValue("stageStatus")}get producers(){var t,e;return Array.from((e=(t=a(this,ze,dt).getProducers())==null?void 0:t.values())!=null?e:[])}get id(){return this.peerId}get peerId(){return a(this,We).getValue("peerId")}static async __init__(t,e,r,i,n,o=!1){var g,S,y,w,b,C;let c=(S=(g=t.getValue("defaults"))==null?void 0:g.audio)!=null?S:!0,d=(w=(y=t.getValue("defaults"))==null?void 0:y.video)!=null?w:!0;r.canProduceAudio!=="ALLOWED"&&(c=!1),r.canProduceVideo!=="ALLOWED"&&(d=!1);const l=new Ze(t,e,r,i,n),u=XO(i.mediaConstraints);Lr(u,(b=t.getValue("defaults"))==null?void 0:b.mediaConfiguration);const h=(C=t.getValue("defaults"))==null?void 0:C.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,Ct).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",x(this,tc,op));const t=a(this,ka,fu);t&&t.onError(e=>{this.emit("autoplayError",e)}),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::AUDIO_TRACK_CHANGE",{...ki(this)}),a(this,He,Xe)&&this.audioEnabled)try{await a(this,ze,dt).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",{...ki(this)}),a(this,He,Xe)&&this.rawVideoTrack===void 0)this.logger.info("Self::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&a(this,He,Xe))try{const e=await a(this,ze,dt).shareWebcam(this.videoTrack);e&&e.id!==this.videoTrack.id&&a(this,We).getValue("flagsmith").hasFeature(Z.EXP_RESHARE)&&await a(this,ze,dt).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,ka,fu))==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,He,Xe)){this.logger.error("Self.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{await a(this,ze,dt).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",{...ki(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",{...ki(this)})}),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{var e;(e=a(this,We))==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,He,Xe)&&await a(this,ze,dt).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(e=a(this,We))==null||e.getValue("callstats").videoOff()}),a(this,Ct).on("permissionsUpdate",e=>{var r,i,n;(r=e==null?void 0:e.media)!=null&&r.audio&&a(this,Ct).canProduceAudio!==H.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,Ct).canProduceVideo!==H.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,Ct).canProduceScreenshare!==H.Allowed&&(this.disableScreenShare(),this.logger.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return a(this,Ct)}get config(){return a(this,Ra)}get roomJoined(){var t;return a(this,Ra).viewType===tr.Livestream&&this.stageStatus!=="ON_STAGE"?((t=a(this,We).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:a(this,He,Xe)}setName(t){if(!t)throw new k("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!==H.NotAllowed&&!(a(this,Ct).canProduceAudio===H.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if((e=a(this,We))==null||e.getValue("callstats").audioOn(),await this.localMediaHandler.enableAudio(t),a(this,He,Xe)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{await a(this,ze,dt).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,Ct).canProduceVideo!==H.NotAllowed&&!(a(this,Ct).canProduceVideo===H.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if((e=a(this,We))==null||e.getValue("callstats").videoOn(),await this.localMediaHandler.enableVideo(t),a(this,He,Xe)&&this.stageStatus==="ON_STAGE")try{await a(this,ze,dt).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",{...ki(this)})}}async updateVideoConstraints(t){if(!this.localMediaHandler.updateVideoConstraints)throw new k("Unsupported","1102");await this.localMediaHandler.updateVideoConstraints(t)}async enableScreenShare(){if(!a(this,He,Xe))throw new k("Can`t enable screenshare without joining room","1105");if(a(this,Ct).canProduceScreenshare!==H.NotAllowed&&!(a(this,Ct).canProduceScreenshare===H.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,ze,dt).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 k("Unsupported","1102");await this.localMediaHandler.updateScreenshareConstraints(t)}async disableAudio(){var t;this.audioEnabled&&(this.localMediaHandler.disableAudio(),a(this,He,Xe)&&a(this,ze,dt).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),(t=a(this,We))==null||t.getValue("callstats").audioOff())}async disableVideo(){var t;this.videoEnabled&&(await this.localMediaHandler.disableVideo(),a(this,He,Xe)&&await a(this,ze,dt).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(t=a(this,We))==null||t.getValue("callstats").videoOff())}async disableScreenShare(){this.screenShareEnabled&&(await this.localMediaHandler.disableScreenShare(),a(this,He,Xe)&&await a(this,ze,dt).disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var i;f(this,Ca,t);const r=t?"pinned":"unpinned";(i=a(this,br,Rn))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}get isPinned(){return a(this,Ca)}async pin(){if(!a(this,He,Xe))throw new k("Can`t pin participants without joining room","1105");return this.show(),a(this,ze,dt).pinPeer(this.id)}async unpin(){if(!a(this,He,Xe))throw new k("Can`t unpin participants without joining room","1105");return a(this,ze,dt).pinPeer(null)}async hide(){if(!a(this,He,Xe))throw new k("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})}show(){if(!a(this,He,Xe))throw new k("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 k("No device selected","1104");const e=this.getCurrentDevices();if(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]}),a(this,We).getValue("flagsmith").hasFeature(Z.SKIP_SETTING_IN_USE_DEVICE)))throw new k("Cannot set device currently in use","1106");switch(t.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(t,{saveDevicePreference:!0})}catch(o){a(this,He,Xe)&&await a(this,ze,dt).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,He,Xe)&&await a(this,ze,dt).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,ka,fu))==null?void 0:t.play()}registerVideoElement(t,e=!1){var r,i;t&&(e?a(this,Ia).add(t):a(this,Aa).add(t),this.updateVideo(t),e||(i=a(this,br,Rn))==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,br,Rn).removeSource(this.id);return}t.srcObject=void 0,e?a(this,Ia).delete(t):(a(this,Aa).delete(t),a(this,br,Rn).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,br,Rn))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(n=a(this,br,Rn))==null||n.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},Ra=new WeakMap,Ct=new WeakMap,Ca=new WeakMap,We=new WeakMap,br=new WeakSet,Rn=function(){return a(this,We).getValue("pip")},ze=new WeakSet,dt=function(){return a(this,We).getValue("roomNodeClient")},ka=new WeakSet,fu=function(){return a(this,We).getValue("audioPlayback")},He=new WeakSet,Xe=function(){var t;return((t=a(this,We).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Ia=new WeakMap,Aa=new WeakMap,tc=new WeakSet,op=function(){Array.from(a(this,Aa)).forEach(t=>this.updateVideo(t,!1)),Array.from(a(this,Ia)).forEach(t=>this.updateVideo(t,!0))},zS);bt([E.trace("Self.cleanupEvents")],Ze.prototype,"cleanupEvents",1),bt([E.trace("Self.setupEvents")],Ze.prototype,"setupEvents",1),bt([E.trace("Self.setupTracks")],Ze.prototype,"setupTracks",1),bt([E.trace("Self.destructMediaHandler")],Ze.prototype,"destructMediaHandler",1),bt([E.trace("Self.removeDocumentEventListeners")],Ze.prototype,"removeDocumentEventListeners",1),bt([cr.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"Self.toggleAudio",timeout:3e3}),E.trace("Self.enableAudio")],Ze.prototype,"enableAudio",1),bt([cr.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"Self.toggleVideo",timeout:3e3}),E.trace("Self.enableVideo")],Ze.prototype,"enableVideo",1),bt([E.trace("Self.updateVideoConstraints")],Ze.prototype,"updateVideoConstraints",1),bt([E.trace("Self.enableScreenShare"),cr.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3})],Ze.prototype,"enableScreenShare",1),bt([E.trace("Self.updateScreenshareConstraints")],Ze.prototype,"updateScreenshareConstraints",1),bt([cr.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"Self.toggleAudio",timeout:3e3}),E.trace("Self.disableAudio")],Ze.prototype,"disableAudio",1),bt([cr.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"Self.toggleVideo",timeout:3e3}),E.trace("Self.disableVideo")],Ze.prototype,"disableVideo",1),bt([cr.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3}),E.trace("Self.disableScreenShare")],Ze.prototype,"disableScreenShare",1),bt([E.trace("Self.setDevice")],Ze.prototype,"setDevice",1),Ze=bt([ut("1100")],Ze);class Dh extends Error{constructor(t){super(t!=null?t:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Dh)}}class Nh extends Error{constructor(t){super(t!=null?t:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Nh)}}class Vh{constructor(t,e=!1){p(this,"pendingTasks",new Map);p(this,"nextTaskId",0);p(this,"stopping",!1);m(this,sc,void 0);this.log=e,f(this,sc,{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 Dh);this.stopping=!1}remove(t){const e=Array.from(this.pendingTasks.values())[t];e&&e.reject(new Nh)}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,sc).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)}}}sc=new WeakMap;function qD(s,t){const e=new Error(t);return e.name=s,e}class wo extends Error{constructor(t){super(t),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,wo):this.stack=new Error(t).stack}}class Nt extends Error{constructor(t){super(t),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Nt):this.stack=new Error(t).stack}}class Ai extends Error{constructor(t){super(t),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Nt):this.stack=new Error(t).stack}}const Zf=s=>new Promise(t=>setTimeout(t,s));async function eS(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 Zf(o*(c+1)):i==="exponential"&&await Zf(o*(c+Math.max(0,c-1)));else break}c+=1}return r(d)})}function jD(s){return s.map(t=>({channels:t.channels,clockRate:t.clockRate,mimeType:t.mimeType,sdpFmtpLine:t.sdpFmtpLine}))}function GD(s){return s.map(t=>({uri:t.uri}))}function el(s){return{codecs:jD(s.codecs),headerExtensions:GD(s.headerExtensions?s.headerExtensions:[])}}function WD(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:el(t),video:el(e)};return{sender:{audio:el(r),video:el(i)},receiver:n}}class JD{constructor(t){m(this,rt,void 0);p(this,"events");f(this,rt,t),this.events=ys}async joinRoom(t,e,r,i=!1){const n={roomUuid:t,displayName:e,prejoined:i,capabilities:r};return(await a(this,rt).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:lC.toBinary(n),timeout:5e3})).payload}async connectTransport(t){const e=(await a(this,rt).sendMessagePromise(this.events.createWebRTCTransport,UR.toBinary(t))).payload,{transportId:r,description:i,producerIds:n}=Um.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,rt).sendMessagePromise(this.events.produce,_C.toBinary(t))).payload,r=ok.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,rt).sendMessagePromise(this.events.consume,TC.toBinary(t))).payload,{consumerIdsMap:{map:r},description:i}=nk.fromBinary(e);return{consumerStateMap:r,sessionDescription:i}}async closeProducer(t){const e=(await a(this,rt).sendMessagePromise(this.events.closeProducer,OC.toBinary(t))).payload,{description:r}=gk.fromBinary(e);return r}async closeConsumer(t){return(await a(this,rt).sendMessagePromise(this.events.closeConsumer,NC.toBinary(t))).payload}async updateConsumersSimulcastConfig(t){return(await a(this,rt).sendMessagePromise(this.events.updateConsumersSimulcastConfig,wC.toBinary(t))).payload}async hostControlForPeer(t,e){const r={audio:e==="audio",screeShare:!1,video:e==="video",participantId:t},i=(await a(this,rt).sendMessagePromise(this.events.hostControlPeer,$C.toBinary(r))).payload;if(!i)return!1;const{status:n}=Ek.fromBinary(i);return n==="success"}async hostControlForAll(t){const e={audio:t==="audio",screenShare:!1,video:t==="video"},r=(await a(this,rt).sendMessagePromise(this.events.hostControlAllPeers,HC.toBinary(e))).payload;if(!r)return!1;const{status:i}=wk.fromBinary(r);return i==="success"}async kickAll(){const t={propagateKickAcrossRooms:!1};a(this,rt).sendMessagePromise(U.kickAll,jm.toBinary(t))}async kickPeer(t){a(this,rt).sendMessagePromise(U.kick,af.toBinary(t))}async changeDisplayName(t){const e=(await a(this,rt).sendMessagePromise(this.events.changeDisplayName,UC.toBinary(t))).payload;if(!e)return!1;const{status:r}=_k.fromBinary(e);return r==="success"}async notifySelfJoinComplete(){const t={},e=(await a(this,rt).sendMessagePromise(this.events.selfJoinComplete,hC.toBinary(t))).payload;return sh.fromBinary(e)}async audioActivity(t){a(this,rt).sendMessage(this.events.audioActivity,$R.toBinary(t))}}rt=new WeakMap;var Bn=(s=>(s.NEW="new",s.CONNECTING="connecting",s.RECONNECTING="reconnecting",s.DISCONNECTED="disconnected",s.CONNECTED="connected",s.FAILED="failed",s.CLOSED="closed",s))(Bn||{});class tl extends lt.EventEmitter{constructor(e){super();m(this,rc,void 0);f(this,rc,e),this.setMaxListeners(1/0)}get logger(){return a(this,rc).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)}})}}rc=new WeakMap;class Lh extends tl{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(`${this.name}::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:async i=>{this.logger.info(`${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"});const e=await this.pc.createOffer();return await this.pc.setLocalDescription(e),this.logger.info(`connect offer: ${JSON.stringify(e)}`),{offerSdp:e,callback:async i=>{this.logger.debug(`${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(`stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(i)}]`),await this.pc.setLocalDescription(i),{offerSdp:i,callback:async o=>{this.logger.debug(`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}})}),this.pc.addEventListener("datachannel",e=>{this.logger.info("data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{this.logger.info("data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{this.logger.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{this.logger.error("data channel error: ",{rtcChannel:{label:e.channel.label}})}}),this.addCustomEventListeners()}addCustomEventListeners(){}}class xh extends Lh{static createFactory(t){return()=>new xh(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 g;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=((g=h.sdpFmtpLine)==null?void 0:g.split(";"))||[];S.push(...u.parameters);const y=Array.from(new Set(S).values());h.sdpFmtpLine=y.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
|
|
14
|
+
`}this.midTransceiverMap.set(n.mid,n);const c=async d=>(this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),await this.pc.setRemoteDescription(d),n.mid);return this.logger.debug(`send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(o,void 0,2)}]`),{offerSdp:o,callback:c,sender:n.sender,mid:n.mid}}addCustomEventListeners(){this.pc.addEventListener("datachannel",t=>{const{channel:e}=t;e.onmessage=r=>{this.safeEmit("datachannel",t.channel,String.fromCharCode(...new Uint8Array(r.data)))}})}}var tS={},sl={},KD={get exports(){return sl},set exports(s){sl=s}},sS=KD.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(sS).forEach(function(s){var t=sS[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=sl,n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);s.parse=function(c){var d={},l=[],u=d;return c.split(/(\r\n|\r|\n)/).filter(n).forEach(function(h){var g=h[0],S=h.slice(2);g==="m"&&(l.push({rtp:[],fmtp:[]}),u=l[l.length-1]);for(var y=0;y<(i[g]||[]).length;y+=1){var w=i[g][y];if(w.reg.test(S))return r(w,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}})})}}(tS);var Uh=sl,zD=/%[sdv%]/g,YD=function(s){var t=1,e=arguments,r=e.length;return s.replace(zD,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""}})},Po=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 YD.apply(null,i)},QD=["v","o","s","i","u","e","p","c","b","t","r","z","a"],XD=["i","c","b","a"],ZD=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||QD,r=t.innerOrder||XD,i=[];return e.forEach(function(n){Uh[n].forEach(function(o){o.name in s&&s[o.name]!=null?i.push(Po(n,o,s)):o.push in s&&s[o.push]!=null&&s[o.push].forEach(function(c){i.push(Po(n,o,c))})})}),s.media.forEach(function(n){i.push(Po("m",Uh.m[0],n)),r.forEach(function(o){Uh[o].forEach(function(c){c.name in n&&n[c.name]!=null?i.push(Po(o,c,n)):c.push in n&&n[c.push]!=null&&n[c.push].forEach(function(d){i.push(Po(o,c,d))})})})}),i.join(`\r
|
|
15
15
|
`)+`\r
|
|
16
|
-
`},Mi=oS,a1=n1,il=a1,Oi=Mi.parse;Mi.parseParams,Mi.parseFmtpConfig,Mi.parsePayloads,Mi.parseRemoteCandidates,Mi.parseImageAttributes,Mi.parseSimulcastStreamList;class nl extends Fh{constructor(e,r){super(e);p(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new nl(e,r)}get name(){return"Firefox60"}async send({track:e,encodings:r,codecOptions:i,screenShare:n}){this._assertSendDirection();const o=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},c=this.pc.addTransceiver(e,{direction:"sendonly",streams:[n?this._sendScreenShareStream:this._sendWebStream],...o});if(!this.supportsSendEncodings&&r){r.reverse();const h=c.sender.getParameters();h.encodings=r,await c.sender.setParameters(h)}const d=(h,g)=>{var F;const S=Oi(h),y=S.media[S.media.length-1],w=y.rtp.filter(L=>g.some(B=>B.name===L.codec)),b=y.fmtp.filter(L=>w.some(B=>B.payload===L.payload)),C=(F=y.rtcpFb)==null?void 0:F.filter(L=>w.some(B=>B.payload===L.payload)),D=w.map(L=>L.payload);return S.media[S.media.length-1].rtp=w,S.media[S.media.length-1].fmtp=b,S.media[S.media.length-1].rtcpFb=C,S.media[S.media.length-1].payloads=D.join(" "),il(S)},l=await this.pc.createOffer();if(l.sdp=d(l.sdp,i),this.logger.debug(`send() | calling pc.setLocalDescription() [offer:${JSON.stringify(l)}]`),await this.pc.setLocalDescription(l),e==="audio"||e.kind==="audio"){const{enableDtx:h,enableStereo:g}=this,S=this.enableHighBitrate?g?128e3:64e3:g?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${g?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${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)}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:r}=e;r.onmessage=async i=>{const n=await i.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(n)))}})}}class Hh extends Fh{static createFactory(t){return()=>new Hh(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 g;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=((g=h.sdpFmtpLine)==null?void 0:g.split(";"))||[];S.push(...u.parameters);const y=[...new Set(S).values()];h.sdpFmtpLine=y.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,g=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=${g}`)}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}}addCustomEventListeners(){this.pc.ondatachannel=t=>{const{channel:e}=t;e.onmessage=async r=>{const i=String.fromCharCode(...new Uint8Array(r.data));this.safeEmit("datachannel",t.channel,i)}}}}function o1(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}class c1 extends sl{constructor(e,r){var i;super(e);m(this,Js);m(this,nc);m(this,Nl);m(this,Vl);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,ic,void 0);m(this,sn,void 0);m(this,Ws,void 0);m(this,Dl,void 0);this.id=r.id,this.localId=r.localId,f(this,ic,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,f(this,Ws,!1),this.producerId=r.producerId,this.track=r.track,f(this,sn,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,x(this,Nl,mv).call(this),f(this,Dl,e)}get closed(){return a(this,Ws)}get kind(){return this.track.kind}get paused(){return a(this,sn)}close(e,r){a(this,Ws)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,a(this,Js,mi)),f(this,Ws,!0),r&&(x(this,Vl,fv).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(a(this,Ws))throw new Nt("closed");return a(this,ic).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",a(this,Js,mi)),a(this,Ws)){this.logger.error("consumer::pause() | Consumer closed",a(this,Js,mi));return}f(this,sn,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",a(this,Js,mi)),a(this,Ws)){this.logger.error("Consumer::resume() | Consumer closed",a(this,Js,mi));return}f(this,sn,!1),this.track.enabled=!0,this.safeEmit("resume")}}ic=new WeakMap,sn=new WeakMap,Ws=new WeakMap,Dl=new WeakMap,Js=new WeakSet,mi=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},nc=new WeakSet,pp=function(){this.logger.debug('Consumer::track "ended" event',a(this,Js,mi)),this.safeEmit("trackended")},Nl=new WeakSet,mv=function(){this.track.addEventListener("ended",x(this,nc,pp).bind(this))},Vl=new WeakSet,fv=function(){try{this.track.removeEventListener("ended",x(this,nc,pp)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...a(this,Js,mi),error:e})}};class d1 extends sl{constructor(e,r){var i,n;super(e);m(this,Xt);p(this,"id");p(this,"localId");m(this,Ms,void 0);p(this,"kind");p(this,"appData");p(this,"rtpSender");m(this,Ma,void 0);m(this,Oa,void 0);m(this,rn,void 0);m(this,gs,!1);m(this,nt,void 0);m(this,ci,void 0);m(this,Da,void 0);m(this,Ll,void 0);this.id=r.id,this.localId=r.localId,f(this,nt,r.track),this.kind=(i=r.track)==null?void 0:i.kind,f(this,ci,r.disableTrackOnPause?!((n=r.track)!=null&&n.enabled):!1),f(this,Da,void 0),f(this,Ma,r.stopTracks),f(this,Oa,r.disableTrackOnPause),f(this,rn,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),f(this,Ms,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),f(this,Ll,e)}get closed(){return a(this,gs)}get track(){return a(this,nt)}get paused(){return a(this,ci)}get maxSpatialLayer(){return a(this,Da)}async close(e){if(a(this,gs))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,a(this,Xt,Fs)),f(this,gs,!0),this._destroyTrack(),e===ol){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await a(this,Ms).stopSending(this.localId),{answer:n}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(n)}async getStats(){if(a(this,gs))throw new Nt("closed");return a(this,Ms).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",a(this,Xt,Fs)),a(this,gs)&&this.logger.error("Producer::pause() | Producer closed",a(this,Xt,Fs)),f(this,ci,!0),a(this,nt)&&a(this,Oa)&&(a(this,nt).enabled=!1),a(this,rn)&&a(this,Ms).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",a(this,Xt,Fs)),a(this,gs)){this.logger.error("Producer::resume() | Producer closed",a(this,Xt,Fs));return}f(this,ci,!1),a(this,nt)&&a(this,Oa)&&(a(this,nt).enabled=!0),a(this,rn)&&a(this,Ms).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,Xt,Fs)),a(this,gs)){if(e&&a(this,Ma))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...a(this,Xt,Fs),error:r})}throw new Nt("closed")}else if(e&&e.readyState==="ended")throw new Nt("track ended");if(e===a(this,nt)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,a(this,Xt,Fs));return}(!a(this,rn)||!a(this,ci))&&await a(this,Ms).replaceTrack(this.localId,e),this._destroyTrack(),f(this,nt,e),this._handleTrack()}async setMaxSpatialLayer(e){if(a(this,gs))throw new Nt("closed");if(this.kind!=="video")throw new bo("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await a(this,Ms).setMaxSpatialLayer(this.localId,e),f(this,Da,e)}async setRtpEncodingParameters(e){if(a(this,gs))throw new Nt("closed");if(typeof e!="object")throw new TypeError("invalid params");await a(this,Ms).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,a(this,Xt,Fs)),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,Ma)&&a(this,nt).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...a(this,Xt,Fs),error:r})}}}Ms=new WeakMap,Ma=new WeakMap,Oa=new WeakMap,rn=new WeakMap,gs=new WeakMap,nt=new WeakMap,ci=new WeakMap,Da=new WeakMap,Ll=new WeakMap,Xt=new WeakSet,Fs=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function dS(s){return typeof s=="object"&&!Array.isArray(s)&&s!==null}function qh(s){return Math.random().toString(36).substring(2,2+s)}const al=1;function lS(s){const t=s;return delete t.payload._bolt,t}function l1(s){return s.payload&&dS(s.payload)}function u1(s){var t,e;return l1(s)&&(e=(t=s.payload._bolt)==null?void 0:t.id)!=null?e:""}const Na=class extends dt.EventEmitter{constructor(e,r,i,n){super();p(this,"channel");p(this,"queue");p(this,"serverProtocolVersion");m(this,di,new Map);m(this,xl,void 0);m(this,nn,void 0);p(this,"respond",(e,r,i=!1)=>{let n;i?n=Na.createErrorResponse(e,r):n=Na.createResponse(e,r),this.channel.send(JSON.stringify(n))});p(this,"notify",e=>{const r=Na.createNotification(e);this.channel.send(JSON.stringify(r))});p(this,"request",async e=>{const r=Na.createRequest(e),i=new Promise((n,o)=>{const{id:d}=r.payload._bolt,l={id:d,method:r.type,resolve:u=>{this.queue.delete(d)&&(clearTimeout(l.timer),n(u))},timer:setTimeout(()=>{this.queue.delete(d)&&o(new Error(`request timeout for message id: ${d}`))},2e4),cancel:u=>{this.queue.delete(d)&&(clearTimeout(l.timer),o(u))}};this.queue.set(d,l)});return this.channel.send(JSON.stringify(r)),i});p(this,"send",e=>{const r=JSON.stringify(e),i=16384;if(r.length>i){const n=i-200,o=Math.ceil(r.length/n),c=[];for(let l=0;l<o;l+=1){const u=l*n,h=(l+1)*n;c.push(r.slice(u,h))}const d=fi();for(let l=0;l<o;l+=1){const u=c[l],g=JSON.stringify({id:d,count:o,chunkIndex:l,chunk:u});a(this,nn).debug(`Sending message chunk over dc: ${g}`),this.channel.send(g)}}else a(this,nn).debug(`Sending message over dc: ${r}`),this.channel.send(r)});p(this,"processMessage",e=>{var i;a(this,di).has(e.id)||a(this,di).set(e.id,[]);const r=a(this,di).get(e.id);if(r[e.chunkIndex]=e,(r==null?void 0:r.length)===e.count&&!r.some(n=>n===void 0)){const n=a(this,di).get(e.id),o=n==null?void 0:n.reduce((d,l)=>d+l.chunk,"");a(this,di).delete(e.id);const c=JSON.parse(o);if(!c.payload||!dS(c.payload))throw new Error("corrupted incoming message over dc",{cause:{code:"CORRUPT_DC_MESSAGE",values:c}});if(this.processBoltHandshake(c))return;if(this.serverProtocolVersion=(i=c.payload._bolt)==null?void 0:i.version,!this.processResponseMsg(c))return c}});p(this,"processResponseMsg",e=>{const{id:r}=e.payload._bolt,i=this.queue.get(r);return i?(a(this,nn).debug(`resolving pending request with id: ${r}, complete response: ${JSON.stringify(e)}`),e.type==="error"?i.cancel(lS(e)):i.resolve(lS(e)),!0):!1});p(this,"processBoltHandshake",e=>{var r,i;return e.type==="_bolt"||e.type==="handshake"?(this.respond((i=(r=e.payload._bolt)==null?void 0:r.id)!=null?i:qh(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1});this.label=i,this.transportId=n,f(this,xl,e),f(this,nn,e.getValue("logger")),this.channel=r,this.queue=new Map}};let Di=Na;di=new WeakMap,xl=new WeakMap,nn=new WeakMap,p(Di,"createRequest",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:{...e.payload,_bolt:{id:qh(8),type:"REQUEST",version:al}}}}),p(Di,"createResponse",(e,r)=>{var i;if((i=r.payload)!=null&&i._bolt)throw new Error("rpc fields are internal values");return{type:r.type,payload:{...r.payload,_bolt:{id:e,type:"RESPONSE",version:al}}}}),p(Di,"createNotification",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:{...e.payload,bolt:{id:qh(8),type:"NOTIFY",version:al}}}}),p(Di,"createErrorResponse",(e,r)=>({type:"error",payload:{error:r.message,_bolt:{id:e,type:"RESPONSE",version:al}}}));const ol="transport closed",Va=class extends sl{constructor(e,{id:r,direction:i,handlerFactory:n,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:u,config:h}){var w,b,C;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,"datachannels");p(this,"connected",!1);p(this,"eventsDCReadyPromise");p(this,"eventsDCReadyPromiseResolver");p(this,"eventsDCFailureTimer");p(this,"transportConnectionPromise");p(this,"consumerTrackEvents");p(this,"unknownTracksMap");p(this,"appData");m(this,an,void 0);f(this,an,e);const g=e.getValue("logger");g.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.datachannels=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new Uh(g,!0),this.handler=n(),this.handler.enableHighBitrate=(w=h==null?void 0:h.enableHighBitrate)!=null?w:!1,this.handler.enableStereo=(b=h==null?void 0:h.enableStereo)!=null?b:!1,this.handler.enableDtx=(C=h==null?void 0:h.enableDtx)!=null?C:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:o,iceTransportPolicy:c,additionalSettings:l,proprietaryConstraints:d}),this.appData=u||{};const y=3e4;this.transportConnectionPromise=new Promise(D=>{const F=setTimeout(()=>{g.error("ICE connection timeout - possible firewall blocking WebRTC or TURN unreachable",{transport:{id:this.id,type:this.direction}}),D(!1)},y);this.once("connected",()=>{clearTimeout(F),D(!0)}),this.once("disconnect",()=>{clearTimeout(F),D(!1)}),this.once("close",()=>{clearTimeout(F),D(!1)})}),this.eventsDCReadyPromise=new Promise(D=>{this.eventsDCReadyPromiseResolver=D}),this.handler.on("@connectionstatechange",D=>{D!==this.connectionState&&(this.logger.debug(`connection state changed to ${D}`),this.connectionState=D,D==="connected"&&(this.connected=!0,this.emit("connected")),D==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(D==="failed"||D==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",D))}),this.handler.on("@icecandidate",({candidate:D})=>{this.closed||this.safeEmit("icecandidate",D)}),this.handler.on("dc_open",D=>{let F=this.datachannels.get(D.label);F||(F||(F=new Di(a(this,an),D,D.label,this.serverId),this.datachannels.set(D.label,F)),this.eventsDCFailureTimer=setTimeout(()=>{D.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",D.label))},5e3))}),this.handler.on("datachannel",(D,F)=>{D.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const L=this.datachannels.get(D.label);if(!L){this.logger.error("unregistered datachannel for message",{rtcChannel:{label:D.label,message:F}});return}try{const B=JSON.parse(F);this.logger.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:B.id,count:B.count,chunkIndex:B.chunkIndex,chunk:B.chunk,transprtId:this.serverId}});const W=L.processMessage(B);if(!W)return;this.logger.debug(`datachannel message with id:${B.id} on transport:${this.serverId}complete - ${JSON.stringify(W)}`),this.emit(`datachannel:${D.label}`,L.label,W)}catch(B){this.logger.error("error parsing message",{error:B})}})}get closed(){return this.connectionState==="closed"}setServerId(e){this.serverId=e}getDatachannel(e){return this.datachannels.get(e)}get isEventsDCReady(){return this.eventsDCReadyPromise}close(){this.closed||(this.logger.debug("Transport close called"),this.connectionState="closed",this.awaitQueue.stop(),this.awaitQueue=void 0,this.connected=!1,this.handler.close(),Array.from(this.producers.values()).forEach(e=>{e.close(ol).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(ol)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new Nt("closed");return this.handler.getTransportStats()}async connect(e){try{if(await this.awaitQueue.push(async()=>{const{offerSdp:r,callback:i}=await this.handler.connect(),{transportId:n,answer:o}=await e(r);this.setServerId(n),await i(o)}),!await this.transportConnectionPromise)throw new Error("ice connection failed")}catch(r){throw this.logger.error("transport failed to connect:",{error:r}),r}}async restartIce(){if(this.logger.debug("restartIce()"),this.closed)throw new Nt("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new bo("not a sending Transport");if(r.readyState==="ended")throw new Nt("track ended");if(i&&typeof i!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!await this.transportConnectionPromise)throw new Ai("transport not connected");return!0}async produce(e,r){if(!await this.canProduce(e))throw new Error("Cannot produce");const{track:n,encodings:o,codecOptions:c,stopTracks:d=!0,disableTrackOnPause:l=!0,zeroRtpOnPause:u=!1,appData:h={}}=e;this.logger.debug(`produce() [track:${n.id}]`);const{producerId:g,localId:S,rtpSender:y}=await this.awaitQueue.push(async()=>{const{offerSdp:w,callback:b,sender:C,mid:D}=await this.handler.send({track:n,encodings:o,codecOptions:c,screenShare:h==null?void 0:h.screenShare}),{answer:F,producerId:L}=await r({offer:w,kind:n.kind,paused:l?!n.enabled||Object.hasOwn(n,"fakeTracks"):!1,appData:{...h||{},mid:D},codecOptions:c,producingTransportId:this.serverId}),B=await b(F);return{producerId:L,localId:B,rtpSender:C}},"Transport.produce");return this.createProducerObject({id:g,localId:S,track:n,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:u,appData:h,handler:this.handler,rtpSender:y})}async createProducerObject(e){const r=new d1(a(this,an),e);return this.producers.set(r.id,r),r.once("close",()=>{this.producers.delete(r.id)}),this.emit("newproducer",r),r}async closeProducer(e){await this.awaitQueue.push(e.close.bind(e),"Transport.closeProducer")}async canConsume(){if(this.closed)throw new Nt("closed");if(this.direction!=="recv")throw new bo("not a receiving transport");if(!await this.transportConnectionPromise)throw new Ai("transport not connected");return!0}async consume(e,r,i){return this.awaitQueue.push(async()=>{const n={},{consumerStates:o,sessionDescription:c,failedProducers:d}=await r(e);o.forEach((u,h)=>{n[h]=this.createConsumerObjectAndWaitForTrack({...u,producerId:h})}),c&&(this.logger.info("Session description found, sending negotiation request"),await i(c));const l=[];return await Promise.all(Object.entries(n).map(([u,h])=>h.then(g=>l.push(g)).catch(()=>{this.logger.error(`Failed to create consumer object, producer: ${u}`,{error:{message:"This should not happen"},transport:{serverId:this.serverId}})}))),{consumers:l,failedProducers:d}},"Transport.consume",{producersLength:e.length})}static parseCodecAndFmtpMappings(e,r){const i=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:il(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:il(i)}}async closeConsumers(e,r){try{const i=e.map(l=>l.transceiver.mid),n=Va.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=Va.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("Created offer for closing consumers",{sdp:c.sdp}),c=Va.setCodecAndFmtpMappings(c,i,n),c=Va.setHeaderExtensionMappings(c,o),this.logger.info("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("Received answer in close consumers",{sdp:d.sdp}),await this.setRemoteDescription(d),this.logger.info("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("Received offer from SFU",{sdp:e.sdp}),await this.setRemoteDescription(e);const r=await this.handler.pc.createAnswer();this.logger.info("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=il(i),this.logger.info("Setting munged SDP",{sdp:r.sdp}),await this.setLocalDescription(r),this.logger.info("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))}sendErrorOverDC(e,r,i){const n=this.getDatachannel(e);if(!n)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});n.respond(r,i,!0)}sendResponseOverDC(e,r,i){const n=this.getDatachannel(e);if(!n)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});n.respond(r,i)}async createConsumerObjectAndWaitForTrack(e){const{consumerId:r,producerId:i,producingPeerId:n,producingTransportId:o,streamId:c,paused:d,screenShare:l,appData:u,kind:h,mimeType:g}=e,S=`${c}:${h}`,y={...e,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(w,b)=>{const C=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${S} producingPeerId: ${n}`),this.consumerTrackEvents.delete(S),y.isTimedout=!0,b(y)},5e3),D=(L,B)=>{try{if(L.readyState==="ended")clearTimeout(C),b(y);else{const W=L;W.enabled=!0,this.handler.midTransceiverMap.set(B.mid,B);const ae=new c1(a(this,an),{id:r,localId:B.mid,transceiver:B,track:W,paused:d,producerId:i,producingPeerId:n,producingTransportId:o,handler:this.handler,appData:{...u,screenShare:l,peerId:n},rtpReceiver:B.receiver,mimeType:g});this.consumers.set(r,ae),ae.once("close",()=>{this.consumers.delete(ae.id),this.handler.midTransceiverMap.delete(B.mid)}),this.logger.info("consumer created for ",{consumer:{id:r,kind:h,appData:{screenShare:l},peerId:n,producerId:i}}),this.emit("newconsumer",ae),clearTimeout(C),w(ae)}}catch(W){this.logger.warn("error while creating consumer:",W),clearTimeout(C),b(y)}},F=this.unknownTracksMap.get(S);F?(this.logger.info(`track event already received [trackId: ${F.track.id}] [mid: ${F.transceiver.mid}]`),this.unknownTracksMap.delete(S),D(F.track,F.transceiver)):(this.logger.info(`Registering onTrack handler for key ${S} [producingPeerId: ${n}]`),this.consumerTrackEvents.set(S,D))})}async setRemoteDescription(e){await this.handler.pc.setRemoteDescription(e)}async setLocalDescription(e){this.logger.debug(`${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),await this.handler.pc.setLocalDescription(e)}async sendDataChannelMessage(e,r){const i=this.getDatachannel(e);if(!i)throw zD("DC_NOT_READY",`${e} datachannel not ready`);const n=(await i.request(r)).payload;return this.logger.info(`sendDataChannelMessage::response ${JSON.stringify(n)}`),n}};let jh=Va;an=new WeakMap;function h1(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=_p.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 p1{constructor(t,{handlerName:e,handlerFactory:r}={}){p(this,"handlerFactory");m(this,br,void 0);m(this,on,void 0);const i=t.getValue("logger");if(i.debug("constructor()"),f(this,br,t),f(this,on,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,on).debug(`Device::constructor() | handler given: ${e}`);else if(e=h1(a(this,on)),e)a(this,on).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=$h.createFactory(a(this,br));break;case"Safari12":this.handlerFactory=Hh.createFactory(a(this,br));break;case"Firefox60":this.handlerFactory=nl.createFactory(a(this,br),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=nl.createFactory(a(this,br),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=fi();return new jh(a(this,br),{id:e,...t,handlerFactory:this.handlerFactory})}}br=new WeakMap,on=new WeakMap;const g1=2e3;class m1 extends dt.EventEmitter{constructor(e,r){super();m(this,Fa);m(this,dc);m(this,Ul);m(this,lc);m(this,Fl);m(this,$l);m(this,Bl);m(this,Hl);m(this,ql);m(this,uc);m(this,hc);p(this,"context");m(this,La,void 0);m(this,ft,void 0);m(this,St,void 0);m(this,ac,void 0);m(this,oc,void 0);m(this,cn,void 0);m(this,xa,void 0);m(this,cc,void 0);m(this,Ua,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});m(this,dn,void 0);m(this,Ks,"all");this.context=e,f(this,cn,r),f(this,La,new p1(e)),f(this,xa,new ZD(r)),f(this,cc,ws),a(this,Fa,Tu).mediaState={send:{state:Bn.NEW},recv:{state:Bn.NEW}},(On(this.context,"forceRelay")||this.context.getValue("flagsmith").hasFeature(Z.FORCE_RELAY))&&f(this,Ks,"relay"),this.logger.info(`ICE Transport Policy initially set to ${a(this,Ks)}`),x(this,dc,gp).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return a(this,cn)}get socketHandler(){return a(this,xa)}get sendTransport(){return a(this,ft)}get recvTransport(){return a(this,St)}get events(){return a(this,cc)}set sendTransportConnectedCallback(e){f(this,ac,e)}set recvTransportConnectedCallback(e){f(this,oc,e)}async setupTransports(e){await x(this,Ul,Sv).call(this,e);let r,i;e.send&&(r=x(this,lc,mp).call(this,a(this,ft)).then(n=>{try{a(this,ac).call(this,n)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=x(this,lc,mp).call(this,a(this,St)).then(n=>{try{a(this,oc).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,ft);this.logger.info("Closing send transport",{transport:{id:n,serverId:o,type:c}}),a(this,ft).close(),a(this,ft).removeAllListeners(),f(this,ft,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,St);this.logger.info("Closing recv transport",{transport:{id:n,serverId:o,type:c}}),(r=a(this,St))==null||r.close(),(i=a(this,St))==null||i.removeAllListeners(),f(this,St,void 0)}x(this,dc,gp).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}La=new WeakMap,ft=new WeakMap,St=new WeakMap,ac=new WeakMap,oc=new WeakMap,cn=new WeakMap,xa=new WeakMap,cc=new WeakMap,Ua=new WeakMap,dn=new WeakMap,Ks=new WeakMap,Fa=new WeakSet,Tu=function(){return this.context.getValue("connectionHandler")},dc=new WeakSet,gp=function(){f(this,dn,{send:void 0,recv:void 0})},Ul=new WeakSet,Sv=async function(e){var o,c,d,l,u,h,g,S;(On(this.context,"forceRelay")||this.context.getValue("flagsmith").hasFeature(Z.FORCE_RELAY))&&f(this,Ks,"relay"),this.logger.info(`ICE Transport Policy set to ${a(this,Ks)}`);const n=await ht().getICEServers().catch(y=>(this.logger.warn(`failed to get iceservers from server: ${y.message}`),[]));if(e.send){const y=this.context.getValue("flagsmith").hasFeature(Z.DISABLE_OPUS_DTX_CF);x(this,$l,Tv).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(o=this.context.getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(l=(d=(c=this.context.getValue("defaults").mediaConfiguration)==null?void 0:c.audio)==null?void 0:d.enableHighBitrate)!=null?l:!1,enableStereo:(g=(h=(u=this.context.getValue("defaults").mediaConfiguration)==null?void 0:u.audio)==null?void 0:h.enableStereo)!=null?g:!1,enableDtx:!!y},iceTransportPolicy:a(this,Ks)})}e.recv&&x(this,Bl,yv).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(S=this.context.getValue("modules").e2ee)==null?void 0:S.enabled},iceTransportPolicy:a(this,Ks)})},lc=new WeakSet,mp=async function(e){const{id:r,serverId:i,direction:n}=e;x(this,Hl,Ev).call(this,e);try{return await aS(async(c,d)=>{c>0&&this.logger.debug(`Retrying transport connect, count: ${c}`,{transport:{id:r,serverId:i,type:n}});try{if(e.closed)throw new Ai("Cannot reconnect closed transport");await x(this,Fl,vv).call(this,e)}catch(l){if(l instanceof Ai){d(l);return}throw this.logger.error("Failed to connect transport, retrying",{transport:e,error:l}),l}},{delayTime:100,strategy:"exponential",maxRetryCount:15}),e}catch(o){throw this.logger.error(`Failed to connect send transport after retry: ${e.id}`,{error:o,transport:{id:r,serverId:i,type:n}}),e.close(),e.removeAllListeners(),o}},Fl=new WeakSet,vv=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!a(this,cn).isConnected)throw new Ai("Socket is not connected");if(e.connectionState==="closed")throw new Ai("Transport is closed");try{await e.connect(n=>x(this,ql,wv).call(this,i,n)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(n){throw a(this,Ua).transportFailureCount[i]+=1,n.message==="ice connection failed"?new Ai(n.message):n}},$l=new WeakSet,Tv=function(e){var r,i;if(a(this,ft)&&a(this,ft).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=a(this,ft))==null?void 0:r.id,serverId:(i=a(this,ft))==null?void 0:i.serverId,type:"send"}});return}f(this,ft,a(this,La).createTransport({...e,direction:"send"})),this.context.getValue("callstats").configureSendTransport(a(this,ft))},Bl=new WeakSet,yv=function(e){var r,i;if(a(this,St)&&a(this,St).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=a(this,St))==null?void 0:r.id,serverId:(i=a(this,St))==null?void 0:i.serverId,type:"recv"}});return}f(this,St,a(this,La).createTransport({...e,direction:"recv"})),this.context.getValue("callstats").configureRecvTransport(a(this,St))},Hl=new WeakSet,Ev=function(e){const{direction:r,id:i}=e;e.on("connectionstatechange",async n=>{x(this,hc,Sp).call(this,{state:n,direction:r}),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,dn)[r];c!==void 0&&(clearTimeout(c),a(this,dn)[r]=void 0)};switch(n){case"connected":o(),a(this,Ua).lastConnectionTime=performance.now();break;case"disconnected":a(this,dn)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await x(this,uc,fp).call(this,e.direction)},g1);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 x(this,uc,fp).call(this,e.direction);break}}),e.on("icecandidate",async n=>{this.logger.debug("Sending iceCandidate:",{iceCandidate:n})}),e.on("datachannel:events",async(n,o)=>{var c,d;this.logger.debug("Got data channel message on event:",{rtcChannel:{label:n,message:o}});try{switch(o.type){case"handshake":{const l={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,u1(o),l);break}case"hub-disconnect":{this.logger.debug(`media hub disconnected, full_reconnect: ${(c=o.payload)==null?void 0:c.full_reconnect}`),((d=o.payload)==null?void 0:d.full_reconnect)===!0&&this.handleErrors("rejoin");break}case"error":break;default:break}}catch(l){this.logger.error(`Unable to handle the incoming datachannel message on channel ${n}`)}}),e.on("dc_error",()=>{e.direction==="recv"&&(this.logger.warn("Events datachannel did not open in 5s",{country:E.location.country}),this.handleErrors("reconnectRecvTransport"))})},ql=new WeakSet,wv=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?ir.SUBSCRIBER:ir.PUBLISHER},producers:[]};return a(this,xa).connectTransport(c)}catch(n){throw this.logger.error(`Error in ${e} transport connection:`,{error:n,country:E.location.country}),n}},uc=new WeakSet,fp=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),this.context.getValue("flagsmith").hasFeature(Z.CF_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED)&&a(this,cn).isConnected&&a(this,Ua).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),f(this,Ks,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:a(this,ft)}),this.context.getValue("peerSessionStore").emit(_.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:a(this,St)}),this.context.getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}x(this,hc,Sp).call(this,{state:Bn.CONNECTED,direction:e})},hc=new WeakSet,Sp=function(e){const{state:r,direction:i}=e;a(this,Fa,Tu).mediaState[i]={state:r},this.context.getValue("peerSessionStore").emit(_.TRANSPORT_STATE_UPDATE,{transport:i,...a(this,Fa,Tu).mediaState[i]})};class f1{constructor(t,e,r,i,n){m(this,jl,void 0);m(this,ms,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=n,f(this,jl,t),f(this,ms,t.getValue("logger"))}async create(t){if(!t||t&&t.length===0)throw new Error("List of producers is required");const e=new Map,r=[];t.forEach(d=>{const{producingPeerId:l,producerId:u,producingTransportId:h}=d,g={simulcast:{preferredRid:"f",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}};e.set(u,l),r.push({producingPeerId:l,producerId:u,producingTransportId:h,...g})});const i=await this.socketHandler.consume({requests:r,consumingTransportId:this.recvTransport.serverId}),n=new Map;t.forEach(d=>n.set(d.producerId,d));const o=new Map,c=[];return Object.entries(i.consumerStateMap).forEach(([d,l])=>{const u=n.get(d);if(!u)return;if(l.errorCode){a(this,ms).warn(`Consumer request failed for producer ${d}`,{error:{message:l.errorCode}}),c.push({...u,errorCode:l.errorCode});return}let h={};try{h=JSON.parse(l.producerState.appData)}catch(g){}o.set(d,{consumerId:l.consumerId,producingTransportId:u.producingTransportId,producingPeerId:u.producingPeerId,kind:u.kind,paused:u.pause,streamId:l.producerTrack.streamId,trackId:l.producerTrack.trackId,screenShare:u.screenShare,mimeType:u.mimeType,appData:h})}),{consumerStates:o,sessionDescription:i.sessionDescription,failedProducers:c}}async negotiate(t){try{a(this,ms).info("Negotiating socket consumer",{transport:this.recvTransport}),a(this,ms).debug(`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:ir.SUBSCRIBER}};return a(this,ms).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,zR.toBinary(r)),a(this,ms).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){a(this,ms).error("Failed to renegotiate",{error:e});return}}async close(t){if(!t.length)return{};const e=async(r,i)=>{const n=r.map(l=>l.localId);a(this,ms).info(`Closing consumers: ${JSON.stringify(n)}`);const o={description:{sdp:i.sdp,type:i.type,target:ir.SUBSCRIBER},consumerIds:n,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=wk.fromBinary(c).description;return{sdp:d.sdp,type:d.type}};return await this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(t,e),"ConsumerStrategy.close",{consumersLength:t.length}),{}}async switchConsumersToLayer(t,e){const r={requests:[],consumingTransportId:this.recvTransport.serverId},i=t.filter(n=>n&&n.id);i.forEach(({id:n,producingTransportId:o,localId:c})=>{r.requests.push({producerId:n,producingTransportId:o,mid:c,simulcast:{preferredRid:e===0?"q":"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}})}),await this.socketHandler.updateConsumersSimulcastConfig(r),a(this,ms).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:n})=>n)})}}jl=new WeakMap,ms=new WeakMap;class Gh{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,g;const c=Gh.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:ir.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(h=i.screenShare)!=null?h:!1,mimeType:`${e}/${(g=n[0])==null?void 0:g.name}`,producingTransportId:o},{answer:l,producerId:u}=await this.socketHandler.produce(d);return{answer:l,producerId:u}}}class S1 extends m1{constructor(e,r){super(e,r);m(this,gc);m(this,Wl);m(this,Jl);m(this,Kl);m(this,zl);m(this,ln,void 0);m(this,li,void 0);m(this,$a,void 0);m(this,pc,void 0);m(this,zs,void 0);m(this,Gl,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});m(this,Pr,[]);m(this,Ba,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{f(this,pc,new Gh(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{a(this,$a).clear(),f(this,zs,new f1(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return a(this,ln)}get consumers(){return a(this,li)}get producerIdToConsumerIdMap(){return a(this,$a)}get logger(){return this.context.getValue("logger")}reset(){f(this,ln,new Map),f(this,li,new Map),f(this,$a,new Map)}async createProducer(e,r){var i;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const n=await this.sendTransport.produce(e,x(this,Wl,bv).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(_.E2EE_ACTIVE_PRODUCER,n),x(this,Jl,Pv).call(this,n,r),n}catch(n){throw this.logger.error("Failed to create producer",{error:n}),a(this,Gl).producerCreationFailureCount+=1,n}}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,ln).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){a(this,Ba)||clearTimeout(a(this,Ba)),f(this,Pr,a(this,Pr).concat(e)),await x(this,gc,vp).call(this)}closeConsumer(e){return this.closeConsumers([e])}async closeConsumers(e){if(!a(this,zs))return;const r=e.map(n=>this.consumers.get(n)).filter(n=>n!==void 0);if(r.length===0)return;const{failedConsumers:i}=await a(this,zs).close(r);i!=null&&i.length&&this.logger.warn("Failed to close some consumers",{consumerIds:i})}closeAllConsumers(){return this.closeConsumers(Array.from(a(this,li).keys()))}async switchConsumersToLayer(e,r){a(this,zs).switchConsumersToLayer(e,r)}}ln=new WeakMap,li=new WeakMap,$a=new WeakMap,pc=new WeakMap,zs=new WeakMap,Gl=new WeakMap,Pr=new WeakMap,Ba=new WeakMap,gc=new WeakSet,vp=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=a(this,Pr).splice(0,a(this,Pr).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,x(this,Kl,_v).bind(this),a(this,zs).negotiate.bind(a(this,zs)));if(o.forEach(x(this,zl,Rv).bind(this)),c!=null&&c.length){this.logger.error("Failed to create consumers for producers",{producers:c});const d=c.filter(({errorCode:l,producerId:u})=>l==="not_found_track_error"?(this.logger.error(`Track not found for producer: ${u}. This will not be retried.`),!1):l==="backend_error"?(this.logger.error("Unrecoverable error: backend error"),!1):!0);f(this,Pr,a(this,Pr).concat(d)),f(this,Ba,setTimeout(x(this,gc,vp).bind(this),e))}}catch(i){if(this.logger.error("failed to consume on transport",{error:i}),i.errorCode==="internal_error"&&i.errorDescription==="Backend error"||i.errorCode==="invalid_session_description"){this.logger.error("Irrecoverable error, closing current recvTransport to create a new one",{transport:this.recvTransport,error:{code:i.errorCode,message:i.errorDescription}});try{this.stopTransports({recv:!0})}catch(n){}await this.setupTransports({recv:!0})}}},Wl=new WeakSet,bv=function(e){return a(this,pc).create(e)},Jl=new WeakSet,Pv=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!==ol){const d={producerId:e.id,description:{sdp:o.sdp,type:o.type,target:ir.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,ln).set(e.id,e)},Kl=new WeakSet,_v=async function(e){try{return await this.recvTransport.canConsume(),await a(this,zs).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},zl=new WeakSet,Rv=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,{id:e.id,appData:e.appData,peerId:e.peerId})};const eu=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,Yl);m(this,Ql);m(this,mc,void 0);m(this,fc,void 0);m(this,Sc,void 0);m(this,Ha,void 0);m(this,qa,void 0);m(this,ja,void 0);m(this,vc,void 0);m(this,Tc,void 0);m(this,Ga,void 0);m(this,Lt,void 0);m(this,Os,void 0);m(this,Ds,!1);m(this,un,0);m(this,hn,0);m(this,_r,[]);m(this,yc,void 0);f(this,Ha,t),f(this,Lt,t),f(this,mc,e),f(this,fc,r),f(this,Sc,i),f(this,qa,n),f(this,ja,o),f(this,vc,c),f(this,Tc,d),f(this,Ga,l),f(this,yc,u),f(this,Os,t/2)}get voiceDetected(){return a(this,Ds)}processAudioChunk(t){var o,c;const e=x(o=eu,Xl,Iv).call(o,t),r=x(c=eu,Zl,Av).call(c,t);return x(this,Yl,Cv).call(this,e),e/a(this,Os)>a(this,Ga)&&e>a(this,Lt)&&r>a(this,mc)?(f(this,un,a(this,un)+1),f(this,hn,a(this,Sc)),a(this,un)>=a(this,fc)&&f(this,Ds,!0)):(f(this,un,0),a(this,hn)>0?f(this,hn,a(this,hn)-1):a(this,Ds)&&f(this,Ds,!1),a(this,Ds)||x(this,Ql,kv).call(this,e)),{energy:e,isVoice:a(this,Ds)}}reset(){f(this,Ds,!1),f(this,un,0),f(this,hn,0),f(this,Lt,a(this,Ha)),f(this,Os,a(this,Ha)/2),f(this,_r,[])}getThresholdInfo(){return{currentEnergyThreshold:a(this,Lt),backgroundNoiseEnergy:a(this,Os),energyRatioThreshold:a(this,Ga)}}};let _o=eu;mc=new WeakMap,fc=new WeakMap,Sc=new WeakMap,Ha=new WeakMap,qa=new WeakMap,ja=new WeakMap,vc=new WeakMap,Tc=new WeakMap,Ga=new WeakMap,Lt=new WeakMap,Os=new WeakMap,Ds=new WeakMap,un=new WeakMap,hn=new WeakMap,_r=new WeakMap,yc=new WeakMap,Yl=new WeakSet,Cv=function(t){a(this,Ds)?f(this,Lt,a(this,ja)*a(this,Lt)+(1-a(this,ja))*t):f(this,Lt,a(this,qa)*a(this,Lt)+(1-a(this,qa))*a(this,Os)),f(this,Lt,Math.max(a(this,vc),Math.min(a(this,Tc),a(this,Lt))))},Ql=new WeakSet,kv=function(t){if(t<a(this,Lt)*1.2)if(a(this,_r).push(t),a(this,_r).length>a(this,yc)&&a(this,_r).shift(),a(this,_r).length>=10){const e=[...a(this,_r)].sort((i,n)=>i-n),r=Math.floor(e.length/2);f(this,Os,e[r])}else f(this,Os,.95*a(this,Os)+.05*t)},Xl=new WeakSet,Iv=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Zl=new WeakSet,Av=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(_o,Xl),m(_o,Zl);class uS{constructor(t){p(this,"RNAudioSampleHandler");m(this,Ec,void 0);f(this,Ec,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,Ec).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()}}Ec=new WeakMap;class hS{constructor(t){p(this,"audioContext");p(this,"analyser");m(this,wc,void 0);f(this,wc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return a(this,wc).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)}}wc=new WeakMap;class v1{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 T1=60,y1=400,_c=class{constructor(t,e){m(this,tu);m(this,su);m(this,Rr,void 0);m(this,Cr,void 0);m(this,Ns,void 0);m(this,bc,void 0);m(this,pn,void 0);m(this,Wa,void 0);m(this,kr,void 0);m(this,ui,void 0);m(this,Ja,void 0);m(this,Ir,void 0);m(this,Ar,void 0);m(this,Ys,void 0);this.reportRequest=e,f(this,Ir,t),f(this,Wa,new _o);const{isReactNative:r}=navigator;f(this,Ar,r?new uS(a(this,Ir)):new hS(a(this,Ir))),f(this,Ys,r?v1:Jf)}get logger(){return a(this,Ir).getValue("logger")}set producerId(t){f(this,Ns,t)}set audioTrack(t){f(this,bc,t),a(this,Ar)instanceof hS&&(a(this,Ar).audioTrack=t)}start(){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${a(this,Ns)}`),a(this,Rr)&&a(this,Ys).clearInterval(a(this,Rr)),f(this,Rr,a(this,Ys).setInterval(async()=>{var i;if(!a(this,bc)||!a(this,Ns))return;const{energy:t}=x(this,tu,Mv).call(this),e=x(i=_c,Pc,Tp).call(i,t);let r=.9;a(this,Ja)!==e&&a(this,Ja)?r=.9:e?r=.3:r=.5,f(this,pn,(a(this,pn)||0)*(1-r)+t*r)},T1)),a(this,Cr)&&a(this,Ys).clearInterval(a(this,Cr)),f(this,Cr,a(this,Ys).setInterval(x(this,su,Ov).bind(this),y1))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${a(this,Ns)}`),a(this,Rr)&&(a(this,Ys).clearInterval(a(this,Rr)),f(this,Rr,void 0)),a(this,Cr)&&(a(this,Ys).clearInterval(a(this,Cr)),f(this,Cr,void 0))}catch(t){}a(this,Wa).reset(),a(this,Ar)instanceof uS&&a(this,Ar).stop()}};let Ro=_c;Rr=new WeakMap,Cr=new WeakMap,Ns=new WeakMap,bc=new WeakMap,pn=new WeakMap,Wa=new WeakMap,kr=new WeakMap,ui=new WeakMap,Ja=new WeakMap,Ir=new WeakMap,Ar=new WeakMap,Ys=new WeakMap,tu=new WeakSet,Mv=function(){var o;const{samples:t}=a(this,Ar),{energy:e,isVoice:r}=a(this,Wa).processAudioChunk(t),i=x(o=_c,ru,Dv).call(o,e);return a(this,Ir).getValue("flagsmith").hasFeature(Z.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: producer: ${a(this,Ns)}, energy: ${a(this,pn)},
|
|
16
|
+
`},Mi=tS,e1=ZD,rl=e1,Oi=Mi.parse;Mi.parseParams,Mi.parseFmtpConfig,Mi.parsePayloads,Mi.parseRemoteCandidates,Mi.parseImageAttributes,Mi.parseSimulcastStreamList;class il extends Lh{constructor(e,r){super(e);p(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new il(e,r)}get name(){return"Firefox60"}async send({track:e,encodings:r,codecOptions:i,screenShare:n}){this._assertSendDirection();const o=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},c=this.pc.addTransceiver(e,{direction:"sendonly",streams:[n?this._sendScreenShareStream:this._sendWebStream],...o});if(!this.supportsSendEncodings&&r){r.reverse();const h=c.sender.getParameters();h.encodings=r,await c.sender.setParameters(h)}const d=(h,g)=>{var F;const S=Oi(h),y=S.media[S.media.length-1],w=y.rtp.filter(L=>g.some(B=>B.name===L.codec)),b=y.fmtp.filter(L=>w.some(B=>B.payload===L.payload)),C=(F=y.rtcpFb)==null?void 0:F.filter(L=>w.some(B=>B.payload===L.payload)),D=w.map(L=>L.payload);return S.media[S.media.length-1].rtp=w,S.media[S.media.length-1].fmtp=b,S.media[S.media.length-1].rtcpFb=C,S.media[S.media.length-1].payloads=D.join(" "),rl(S)},l=await this.pc.createOffer();if(l.sdp=d(l.sdp,i),this.logger.debug(`send() | calling pc.setLocalDescription() [offer:${JSON.stringify(l)}]`),await this.pc.setLocalDescription(l),e==="audio"||e.kind==="audio"){const{enableDtx:h,enableStereo:g}=this,S=this.enableHighBitrate?g?128e3:64e3:g?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${g?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${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)}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:r}=e;r.onmessage=async i=>{const n=await i.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(n)))}})}}class Fh extends Lh{static createFactory(t){return()=>new Fh(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 g;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=((g=h.sdpFmtpLine)==null?void 0:g.split(";"))||[];S.push(...u.parameters);const y=[...new Set(S).values()];h.sdpFmtpLine=y.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,g=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=${g}`)}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}}addCustomEventListeners(){this.pc.ondatachannel=t=>{const{channel:e}=t;e.onmessage=async r=>{const i=String.fromCharCode(...new Uint8Array(r.data));this.safeEmit("datachannel",t.channel,i)}}}}function t1(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}class s1 extends tl{constructor(e,r){var i;super(e);m(this,Js);m(this,nc);m(this,Dl);m(this,Nl);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,ic,void 0);m(this,sn,void 0);m(this,Ws,void 0);m(this,Ol,void 0);this.id=r.id,this.localId=r.localId,f(this,ic,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,f(this,Ws,!1),this.producerId=r.producerId,this.track=r.track,f(this,sn,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,x(this,Dl,cv).call(this),f(this,Ol,e)}get closed(){return a(this,Ws)}get kind(){return this.track.kind}get paused(){return a(this,sn)}close(e,r){a(this,Ws)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,a(this,Js,mi)),f(this,Ws,!0),r&&(x(this,Nl,dv).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(a(this,Ws))throw new Nt("closed");return a(this,ic).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",a(this,Js,mi)),a(this,Ws)){this.logger.error("consumer::pause() | Consumer closed",a(this,Js,mi));return}f(this,sn,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",a(this,Js,mi)),a(this,Ws)){this.logger.error("Consumer::resume() | Consumer closed",a(this,Js,mi));return}f(this,sn,!1),this.track.enabled=!0,this.safeEmit("resume")}}ic=new WeakMap,sn=new WeakMap,Ws=new WeakMap,Ol=new WeakMap,Js=new WeakSet,mi=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},nc=new WeakSet,cp=function(){this.logger.debug('Consumer::track "ended" event',a(this,Js,mi)),this.safeEmit("trackended")},Dl=new WeakSet,cv=function(){this.track.addEventListener("ended",x(this,nc,cp).bind(this))},Nl=new WeakSet,dv=function(){try{this.track.removeEventListener("ended",x(this,nc,cp)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...a(this,Js,mi),error:e})}};class r1 extends tl{constructor(e,r){var i,n;super(e);m(this,Qt);p(this,"id");p(this,"localId");m(this,Is,void 0);p(this,"kind");p(this,"appData");p(this,"rtpSender");m(this,Ma,void 0);m(this,Oa,void 0);m(this,rn,void 0);m(this,hs,!1);m(this,ot,void 0);m(this,ci,void 0);m(this,Da,void 0);m(this,Vl,void 0);this.id=r.id,this.localId=r.localId,f(this,ot,r.track),this.kind=(i=r.track)==null?void 0:i.kind,f(this,ci,r.disableTrackOnPause?!((n=r.track)!=null&&n.enabled):!1),f(this,Da,void 0),f(this,Ma,r.stopTracks),f(this,Oa,r.disableTrackOnPause),f(this,rn,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),f(this,Is,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),f(this,Vl,e)}get closed(){return a(this,hs)}get track(){return a(this,ot)}get paused(){return a(this,ci)}get maxSpatialLayer(){return a(this,Da)}async close(e){if(a(this,hs))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,a(this,Qt,xs)),f(this,hs,!0),this._destroyTrack(),e===al){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await a(this,Is).stopSending(this.localId),{answer:n}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(n)}async getStats(){if(a(this,hs))throw new Nt("closed");return a(this,Is).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",a(this,Qt,xs)),a(this,hs)&&this.logger.error("Producer::pause() | Producer closed",a(this,Qt,xs)),f(this,ci,!0),a(this,ot)&&a(this,Oa)&&(a(this,ot).enabled=!1),a(this,rn)&&a(this,Is).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",a(this,Qt,xs)),a(this,hs)){this.logger.error("Producer::resume() | Producer closed",a(this,Qt,xs));return}f(this,ci,!1),a(this,ot)&&a(this,Oa)&&(a(this,ot).enabled=!0),a(this,rn)&&a(this,Is).replaceTrack(this.localId,a(this,ot)),this.emit("resume")}async replaceTrack({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,a(this,Qt,xs)),a(this,hs)){if(e&&a(this,Ma))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...a(this,Qt,xs),error:r})}throw new Nt("closed")}else if(e&&e.readyState==="ended")throw new Nt("track ended");if(e===a(this,ot)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,a(this,Qt,xs));return}(!a(this,rn)||!a(this,ci))&&await a(this,Is).replaceTrack(this.localId,e),this._destroyTrack(),f(this,ot,e),this._handleTrack()}async setMaxSpatialLayer(e){if(a(this,hs))throw new Nt("closed");if(this.kind!=="video")throw new wo("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await a(this,Is).setMaxSpatialLayer(this.localId,e),f(this,Da,e)}async setRtpEncodingParameters(e){if(a(this,hs))throw new Nt("closed");if(typeof e!="object")throw new TypeError("invalid params");await a(this,Is).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,a(this,Qt,xs)),this.safeEmit("trackended",this.track.id)}_handleTrack(){a(this,ot)&&a(this,ot).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(a(this,ot))try{a(this,ot).removeEventListener("ended",this._onTrackEnded),a(this,Ma)&&a(this,ot).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...a(this,Qt,xs),error:r})}}}Is=new WeakMap,Ma=new WeakMap,Oa=new WeakMap,rn=new WeakMap,hs=new WeakMap,ot=new WeakMap,ci=new WeakMap,Da=new WeakMap,Vl=new WeakMap,Qt=new WeakSet,xs=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function rS(s){return typeof s=="object"&&!Array.isArray(s)&&s!==null}function $h(s){return Math.random().toString(36).substring(2,2+s)}const nl=1;function iS(s){const t=s;return delete t.payload._bolt,t}function i1(s){return s.payload&&rS(s.payload)}function n1(s){var t,e;return i1(s)&&(e=(t=s.payload._bolt)==null?void 0:t.id)!=null?e:""}const Na=class extends lt.EventEmitter{constructor(e,r,i,n){super();p(this,"channel");p(this,"queue");p(this,"serverProtocolVersion");m(this,di,new Map);m(this,Ll,void 0);m(this,nn,void 0);p(this,"respond",(e,r,i=!1)=>{let n;i?n=Na.createErrorResponse(e,r):n=Na.createResponse(e,r),this.channel.send(JSON.stringify(n))});p(this,"notify",e=>{const r=Na.createNotification(e);this.channel.send(JSON.stringify(r))});p(this,"request",async e=>{const r=Na.createRequest(e),i=new Promise((n,o)=>{const{id:d}=r.payload._bolt,l={id:d,method:r.type,resolve:u=>{this.queue.delete(d)&&(clearTimeout(l.timer),n(u))},timer:setTimeout(()=>{this.queue.delete(d)&&o(new Error(`request timeout for message id: ${d}`))},2e4),cancel:u=>{this.queue.delete(d)&&(clearTimeout(l.timer),o(u))}};this.queue.set(d,l)});return this.channel.send(JSON.stringify(r)),i});p(this,"send",e=>{const r=JSON.stringify(e),i=16384;if(r.length>i){const n=i-200,o=Math.ceil(r.length/n),c=[];for(let l=0;l<o;l+=1){const u=l*n,h=(l+1)*n;c.push(r.slice(u,h))}const d=fi();for(let l=0;l<o;l+=1){const u=c[l],g=JSON.stringify({id:d,count:o,chunkIndex:l,chunk:u});a(this,nn).debug(`Sending message chunk over dc: ${g}`),this.channel.send(g)}}else a(this,nn).debug(`Sending message over dc: ${r}`),this.channel.send(r)});p(this,"processMessage",e=>{var i;a(this,di).has(e.id)||a(this,di).set(e.id,[]);const r=a(this,di).get(e.id);if(r[e.chunkIndex]=e,(r==null?void 0:r.length)===e.count&&!r.some(n=>n===void 0)){const n=a(this,di).get(e.id),o=n==null?void 0:n.reduce((d,l)=>d+l.chunk,"");a(this,di).delete(e.id);const c=JSON.parse(o);if(!c.payload||!rS(c.payload))throw new Error("corrupted incoming message over dc",{cause:{code:"CORRUPT_DC_MESSAGE",values:c}});if(this.processBoltHandshake(c))return;if(this.serverProtocolVersion=(i=c.payload._bolt)==null?void 0:i.version,!this.processResponseMsg(c))return c}});p(this,"processResponseMsg",e=>{const{id:r}=e.payload._bolt,i=this.queue.get(r);return i?(a(this,nn).debug(`resolving pending request with id: ${r}, complete response: ${JSON.stringify(e)}`),e.type==="error"?i.cancel(iS(e)):i.resolve(iS(e)),!0):!1});p(this,"processBoltHandshake",e=>{var r,i;return e.type==="_bolt"||e.type==="handshake"?(this.respond((i=(r=e.payload._bolt)==null?void 0:r.id)!=null?i:$h(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1});this.label=i,this.transportId=n,f(this,Ll,e),f(this,nn,e.getValue("logger")),this.channel=r,this.queue=new Map}};let Di=Na;di=new WeakMap,Ll=new WeakMap,nn=new WeakMap,p(Di,"createRequest",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:{...e.payload,_bolt:{id:$h(8),type:"REQUEST",version:nl}}}}),p(Di,"createResponse",(e,r)=>{var i;if((i=r.payload)!=null&&i._bolt)throw new Error("rpc fields are internal values");return{type:r.type,payload:{...r.payload,_bolt:{id:e,type:"RESPONSE",version:nl}}}}),p(Di,"createNotification",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:{...e.payload,bolt:{id:$h(8),type:"NOTIFY",version:nl}}}}),p(Di,"createErrorResponse",(e,r)=>({type:"error",payload:{error:r.message,_bolt:{id:e,type:"RESPONSE",version:nl}}}));const al="transport closed",Va=class extends tl{constructor(e,{id:r,direction:i,handlerFactory:n,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:u,config:h}){var w,b,C;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,"datachannels");p(this,"connected",!1);p(this,"eventsDCReadyPromise");p(this,"eventsDCReadyPromiseResolver");p(this,"eventsDCFailureTimer");p(this,"transportConnectionPromise");p(this,"consumerTrackEvents");p(this,"unknownTracksMap");p(this,"appData");m(this,an,void 0);f(this,an,e);const g=e.getValue("logger");g.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const S=t1(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.datachannels=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new Vh(g,!0),this.handler=n(),this.handler.enableHighBitrate=(w=h==null?void 0:h.enableHighBitrate)!=null?w:!1,this.handler.enableStereo=(b=h==null?void 0:h.enableStereo)!=null?b:!1,this.handler.enableDtx=(C=h==null?void 0:h.enableDtx)!=null?C:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:o,iceTransportPolicy:c,additionalSettings:l,proprietaryConstraints:d}),this.appData=u||{};const y=3e4;this.transportConnectionPromise=new Promise(D=>{const F=setTimeout(()=>{g.error("ICE connection timeout - possible firewall blocking WebRTC or TURN unreachable",{transport:{id:this.id,type:this.direction}}),D(!1)},y);this.once("connected",()=>{clearTimeout(F),D(!0)}),this.once("disconnect",()=>{clearTimeout(F),D(!1)}),this.once("close",()=>{clearTimeout(F),D(!1)})}),this.eventsDCReadyPromise=new Promise(D=>{this.eventsDCReadyPromiseResolver=D}),this.handler.on("@connectionstatechange",D=>{D!==this.connectionState&&(this.logger.debug(`connection state changed to ${D}`),this.connectionState=D,D==="connected"&&(this.connected=!0,this.emit("connected")),D==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(D==="failed"||D==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",D))}),this.handler.on("@icecandidate",({candidate:D})=>{this.closed||this.safeEmit("icecandidate",D)}),this.handler.on("dc_open",D=>{let F=this.datachannels.get(D.label);F||(F||(F=new Di(a(this,an),D,D.label,this.serverId),this.datachannels.set(D.label,F)),this.eventsDCFailureTimer=setTimeout(()=>{D.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",D.label))},5e3))}),this.handler.on("datachannel",(D,F)=>{D.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const L=this.datachannels.get(D.label);if(!L){this.logger.error("unregistered datachannel for message",{rtcChannel:{label:D.label,message:F}});return}try{const B=JSON.parse(F);this.logger.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:B.id,count:B.count,chunkIndex:B.chunkIndex,chunk:B.chunk,transprtId:this.serverId}});const Q=L.processMessage(B);if(!Q)return;this.logger.debug(`datachannel message with id:${B.id} on transport:${this.serverId}complete - ${JSON.stringify(Q)}`),this.emit(`datachannel:${D.label}`,L.label,Q)}catch(B){this.logger.error("error parsing message",{error:B})}})}get closed(){return this.connectionState==="closed"}setServerId(e){this.serverId=e}getDatachannel(e){return this.datachannels.get(e)}get isEventsDCReady(){return this.eventsDCReadyPromise}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(al).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(al)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new Nt("closed");return this.handler.getTransportStats()}async connect(e){try{if(await this.awaitQueue.push(async()=>{const{offerSdp:r,callback:i}=await this.handler.connect(),{transportId:n,answer:o}=await e(r);this.setServerId(n),await i(o)}),!await this.transportConnectionPromise)throw new Error("ice connection failed")}catch(r){throw this.logger.error("transport failed to connect:",{error:r}),r}}async restartIce(){if(this.logger.debug("restartIce()"),this.closed)throw new Nt("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new wo("not a sending Transport");if(r.readyState==="ended")throw new Nt("track ended");if(i&&typeof i!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!await this.transportConnectionPromise)throw new Ai("transport not connected");return!0}async produce(e,r){if(!await this.canProduce(e))throw new Error("Cannot produce");const{track:n,encodings:o,codecOptions:c,stopTracks:d=!0,disableTrackOnPause:l=!0,zeroRtpOnPause:u=!1,appData:h={}}=e;this.logger.debug(`produce() [track:${n.id}]`);const{producerId:g,localId:S,rtpSender:y}=await this.awaitQueue.push(async()=>{const{offerSdp:w,callback:b,sender:C,mid:D}=await this.handler.send({track:n,encodings:o,codecOptions:c,screenShare:h==null?void 0:h.screenShare}),{answer:F,producerId:L}=await r({offer:w,kind:n.kind,paused:l?!n.enabled||Object.hasOwn(n,"fakeTracks"):!1,appData:{...h||{},mid:D},codecOptions:c,producingTransportId:this.serverId}),B=await b(F);return{producerId:L,localId:B,rtpSender:C}},"Transport.produce");return this.createProducerObject({id:g,localId:S,track:n,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:u,appData:h,handler:this.handler,rtpSender:y})}async createProducerObject(e){const r=new r1(a(this,an),e);return this.producers.set(r.id,r),r.once("close",()=>{this.producers.delete(r.id)}),this.emit("newproducer",r),r}async closeProducer(e){await this.awaitQueue.push(e.close.bind(e),"Transport.closeProducer")}async canConsume(){if(this.closed)throw new Nt("closed");if(this.direction!=="recv")throw new wo("not a receiving transport");if(!await this.transportConnectionPromise)throw new Ai("transport not connected");return!0}async consume(e,r,i){return this.awaitQueue.push(async()=>{const n={},{consumerStates:o,sessionDescription:c,failedProducers:d}=await r(e);o.forEach((u,h)=>{n[h]=this.createConsumerObjectAndWaitForTrack({...u,producerId:h})}),c&&(this.logger.info("Session description found, sending negotiation request"),await i(c));const l=[];return await Promise.all(Object.entries(n).map(([u,h])=>h.then(g=>l.push(g)).catch(()=>{this.logger.error(`Failed to create consumer object, producer: ${u}`,{error:{message:"This should not happen"},transport:{serverId:this.serverId}})}))),{consumers:l,failedProducers:d}},"Transport.consume",{producersLength:e.length})}static parseCodecAndFmtpMappings(e,r){const i=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:rl(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:rl(i)}}async closeConsumers(e,r){try{const i=e.map(l=>l.transceiver.mid),n=Va.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=Va.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("Created offer for closing consumers",{sdp:c.sdp}),c=Va.setCodecAndFmtpMappings(c,i,n),c=Va.setHeaderExtensionMappings(c,o),this.logger.info("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("Received answer in close consumers",{sdp:d.sdp}),await this.setRemoteDescription(d),this.logger.info("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("Received offer from SFU",{sdp:e.sdp}),await this.setRemoteDescription(e);const r=await this.handler.pc.createAnswer();this.logger.info("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=rl(i),this.logger.info("Setting munged SDP",{sdp:r.sdp}),await this.setLocalDescription(r),this.logger.info("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))}sendErrorOverDC(e,r,i){const n=this.getDatachannel(e);if(!n)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});n.respond(r,i,!0)}sendResponseOverDC(e,r,i){const n=this.getDatachannel(e);if(!n)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});n.respond(r,i)}async createConsumerObjectAndWaitForTrack(e){const{consumerId:r,producerId:i,producingPeerId:n,producingTransportId:o,streamId:c,paused:d,screenShare:l,appData:u,kind:h,mimeType:g}=e,S=`${c}:${h}`,y={...e,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(w,b)=>{const C=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${S} producingPeerId: ${n}`),this.consumerTrackEvents.delete(S),y.isTimedout=!0,b(y)},5e3),D=(L,B)=>{try{if(L.readyState==="ended")clearTimeout(C),b(y);else{const Q=L;Q.enabled=!0,this.handler.midTransceiverMap.set(B.mid,B);const se=new s1(a(this,an),{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:g});this.consumers.set(r,se),se.once("close",()=>{this.consumers.delete(se.id),this.handler.midTransceiverMap.delete(B.mid)}),this.logger.info("consumer created for ",{consumer:{id:r,kind:h,appData:{screenShare:l},peerId:n,producerId:i}}),this.emit("newconsumer",se),clearTimeout(C),w(se)}}catch(Q){this.logger.warn("error while creating consumer:",Q),clearTimeout(C),b(y)}},F=this.unknownTracksMap.get(S);F?(this.logger.info(`track event already received [trackId: ${F.track.id}] [mid: ${F.transceiver.mid}]`),this.unknownTracksMap.delete(S),D(F.track,F.transceiver)):(this.logger.info(`Registering onTrack handler for key ${S} [producingPeerId: ${n}]`),this.consumerTrackEvents.set(S,D))})}async setRemoteDescription(e){await this.handler.pc.setRemoteDescription(e)}async setLocalDescription(e){this.logger.debug(`${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),await this.handler.pc.setLocalDescription(e)}async sendDataChannelMessage(e,r){const i=this.getDatachannel(e);if(!i)throw qD("DC_NOT_READY",`${e} datachannel not ready`);const n=(await i.request(r)).payload;return this.logger.info(`sendDataChannelMessage::response ${JSON.stringify(n)}`),n}};let Bh=Va;an=new WeakMap;function a1(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=yp.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 o1{constructor(t,{handlerName:e,handlerFactory:r}={}){p(this,"handlerFactory");m(this,wr,void 0);m(this,on,void 0);const i=t.getValue("logger");if(i.debug("constructor()"),f(this,wr,t),f(this,on,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,on).debug(`Device::constructor() | handler given: ${e}`);else if(e=a1(a(this,on)),e)a(this,on).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=xh.createFactory(a(this,wr));break;case"Safari12":this.handlerFactory=Fh.createFactory(a(this,wr));break;case"Firefox60":this.handlerFactory=il.createFactory(a(this,wr),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=il.createFactory(a(this,wr),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=fi();return new Bh(a(this,wr),{id:e,...t,handlerFactory:this.handlerFactory})}}wr=new WeakMap,on=new WeakMap;const c1=2e3;class d1 extends lt.EventEmitter{constructor(e,r){super();m(this,Fa);m(this,dc);m(this,xl);m(this,lc);m(this,Ul);m(this,Fl);m(this,$l);m(this,Bl);m(this,Hl);m(this,uc);m(this,hc);p(this,"context");m(this,La,void 0);m(this,ft,void 0);m(this,St,void 0);m(this,ac,void 0);m(this,oc,void 0);m(this,cn,void 0);m(this,xa,void 0);m(this,cc,void 0);m(this,Ua,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});m(this,dn,void 0);m(this,Ks,"all");this.context=e,f(this,cn,r),f(this,La,new o1(e)),f(this,xa,new JD(r)),f(this,cc,ys),a(this,Fa,Su).mediaState={send:{state:Bn.NEW},recv:{state:Bn.NEW}},(On(this.context,"forceRelay")||this.context.getValue("flagsmith").hasFeature(Z.FORCE_RELAY))&&f(this,Ks,"relay"),this.logger.info(`ICE Transport Policy initially set to ${a(this,Ks)}`),x(this,dc,dp).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return a(this,cn)}get socketHandler(){return a(this,xa)}get sendTransport(){return a(this,ft)}get recvTransport(){return a(this,St)}get events(){return a(this,cc)}set sendTransportConnectedCallback(e){f(this,ac,e)}set recvTransportConnectedCallback(e){f(this,oc,e)}async setupTransports(e){await x(this,xl,lv).call(this,e);let r,i;e.send&&(r=x(this,lc,lp).call(this,a(this,ft)).then(n=>{try{a(this,ac).call(this,n)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=x(this,lc,lp).call(this,a(this,St)).then(n=>{try{a(this,oc).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,ft);this.logger.info("Closing send transport",{transport:{id:n,serverId:o,type:c}}),a(this,ft).close(),a(this,ft).removeAllListeners(),f(this,ft,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,St);this.logger.info("Closing recv transport",{transport:{id:n,serverId:o,type:c}}),(r=a(this,St))==null||r.close(),(i=a(this,St))==null||i.removeAllListeners(),f(this,St,void 0)}x(this,dc,dp).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}La=new WeakMap,ft=new WeakMap,St=new WeakMap,ac=new WeakMap,oc=new WeakMap,cn=new WeakMap,xa=new WeakMap,cc=new WeakMap,Ua=new WeakMap,dn=new WeakMap,Ks=new WeakMap,Fa=new WeakSet,Su=function(){return this.context.getValue("connectionHandler")},dc=new WeakSet,dp=function(){f(this,dn,{send:void 0,recv:void 0})},xl=new WeakSet,lv=async function(e){var o,c,d,l,u,h,g,S;(On(this.context,"forceRelay")||this.context.getValue("flagsmith").hasFeature(Z.FORCE_RELAY))&&f(this,Ks,"relay"),this.logger.info(`ICE Transport Policy set to ${a(this,Ks)}`);const n=await yt().getICEServers().catch(y=>(this.logger.warn(`failed to get iceservers from server: ${y.message}`),[]));if(e.send){const y=this.context.getValue("flagsmith").hasFeature(Z.DISABLE_OPUS_DTX_CF);x(this,Fl,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:(g=(h=(u=this.context.getValue("defaults").mediaConfiguration)==null?void 0:u.audio)==null?void 0:h.enableStereo)!=null?g:!1,enableDtx:!!y},iceTransportPolicy:a(this,Ks)})}e.recv&&x(this,$l,pv).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(S=this.context.getValue("modules").e2ee)==null?void 0:S.enabled},iceTransportPolicy:a(this,Ks)})},lc=new WeakSet,lp=async function(e){const{id:r,serverId:i,direction:n}=e;x(this,Bl,gv).call(this,e);try{return await eS(async(c,d)=>{c>0&&this.logger.debug(`Retrying transport connect, count: ${c}`,{transport:{id:r,serverId:i,type:n}});try{if(e.closed)throw new Ai("Cannot reconnect closed transport");await x(this,Ul,uv).call(this,e)}catch(l){if(l instanceof Ai){d(l);return}throw this.logger.error("Failed to connect transport, retrying",{transport:e,error:l}),l}},{delayTime:100,strategy:"exponential",maxRetryCount:15}),e}catch(o){throw this.logger.error(`Failed to connect send transport after retry: ${e.id}`,{error:o,transport:{id:r,serverId:i,type:n}}),e.close(),e.removeAllListeners(),o}},Ul=new WeakSet,uv=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!a(this,cn).isConnected)throw new Ai("Socket is not connected");if(e.connectionState==="closed")throw new Ai("Transport is closed");try{await e.connect(n=>x(this,Hl,mv).call(this,i,n)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(n){throw a(this,Ua).transportFailureCount[i]+=1,n.message==="ice connection failed"?new Ai(n.message):n}},Fl=new WeakSet,hv=function(e){var r,i;if(a(this,ft)&&a(this,ft).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=a(this,ft))==null?void 0:r.id,serverId:(i=a(this,ft))==null?void 0:i.serverId,type:"send"}});return}f(this,ft,a(this,La).createTransport({...e,direction:"send"})),this.context.getValue("callstats").configureSendTransport(a(this,ft))},$l=new WeakSet,pv=function(e){var r,i;if(a(this,St)&&a(this,St).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=a(this,St))==null?void 0:r.id,serverId:(i=a(this,St))==null?void 0:i.serverId,type:"recv"}});return}f(this,St,a(this,La).createTransport({...e,direction:"recv"})),this.context.getValue("callstats").configureRecvTransport(a(this,St))},Bl=new WeakSet,gv=function(e){const{direction:r,id:i}=e;e.on("connectionstatechange",async n=>{x(this,hc,hp).call(this,{state:n,direction:r}),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,dn)[r];c!==void 0&&(clearTimeout(c),a(this,dn)[r]=void 0)};switch(n){case"connected":o(),a(this,Ua).lastConnectionTime=performance.now();break;case"disconnected":a(this,dn)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await x(this,uc,up).call(this,e.direction)},c1);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 x(this,uc,up).call(this,e.direction);break}}),e.on("icecandidate",async n=>{this.logger.debug("Sending iceCandidate:",{iceCandidate:n})}),e.on("datachannel:events",async(n,o)=>{var c,d;this.logger.debug("Got data channel message on event:",{rtcChannel:{label:n,message:o}});try{switch(o.type){case"handshake":{const l={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,n1(o),l);break}case"hub-disconnect":{this.logger.debug(`media hub disconnected, full_reconnect: ${(c=o.payload)==null?void 0:c.full_reconnect}`),((d=o.payload)==null?void 0:d.full_reconnect)===!0&&this.handleErrors("rejoin");break}case"error":break;default:break}}catch(l){this.logger.error(`Unable to handle the incoming datachannel message on channel ${n}`)}}),e.on("dc_error",()=>{e.direction==="recv"&&(this.logger.warn("Events datachannel did not open in 5s"),this.handleErrors("reconnectRecvTransport"))})},Hl=new WeakSet,mv=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?ir.SUBSCRIBER:ir.PUBLISHER},producers:[]};return a(this,xa).connectTransport(c)}catch(n){throw this.logger.error(`Error in ${e} transport connection:`,{error:n}),n}},uc=new WeakSet,up=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),this.context.getValue("flagsmith").hasFeature(Z.CF_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED)&&a(this,cn).isConnected&&a(this,Ua).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),f(this,Ks,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:a(this,ft)}),this.context.getValue("peerSessionStore").emit(_.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:a(this,St)}),this.context.getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}x(this,hc,hp).call(this,{state:Bn.CONNECTED,direction:e})},hc=new WeakSet,hp=function(e){const{state:r,direction:i}=e;a(this,Fa,Su).mediaState[i]={state:r},this.context.getValue("peerSessionStore").emit(_.TRANSPORT_STATE_UPDATE,{transport:i,...a(this,Fa,Su).mediaState[i]})};class l1{constructor(t,e,r,i,n){m(this,ql,void 0);m(this,ps,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=n,f(this,ql,t),f(this,ps,t.getValue("logger"))}async create(t){if(!t||t&&t.length===0)throw new Error("List of producers is required");const e=new Map,r=[];t.forEach(d=>{const{producingPeerId:l,producerId:u,producingTransportId:h}=d,g={simulcast:{preferredRid:"f",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}};e.set(u,l),r.push({producingPeerId:l,producerId:u,producingTransportId:h,...g})});const i=await this.socketHandler.consume({requests:r,consumingTransportId:this.recvTransport.serverId}),n=new Map;t.forEach(d=>n.set(d.producerId,d));const o=new Map,c=[];return Object.entries(i.consumerStateMap).forEach(([d,l])=>{const u=n.get(d);if(!u)return;if(l.errorCode){a(this,ps).warn(`Consumer request failed for producer ${d}`,{error:{message:l.errorCode}}),c.push({...u,errorCode:l.errorCode});return}let h={};try{h=JSON.parse(l.producerState.appData)}catch(g){}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,ps).info("Negotiating socket consumer",{transport:this.recvTransport}),a(this,ps).debug(`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:ir.SUBSCRIBER}};return a(this,ps).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,qR.toBinary(r)),a(this,ps).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){a(this,ps).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,ps).info(`Closing consumers: ${JSON.stringify(n)}`);const o={description:{sdp:i.sdp,type:i.type,target:ir.SUBSCRIBER},consumerIds:n,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=fk.fromBinary(c).description;return{sdp:d.sdp,type:d.type}};return await this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(t,e),"ConsumerStrategy.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,ps).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:n})=>n)})}}ql=new WeakMap,ps=new WeakMap;class Hh{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,g;const c=Hh.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:ir.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(h=i.screenShare)!=null?h:!1,mimeType:`${e}/${(g=n[0])==null?void 0:g.name}`,producingTransportId:o},{answer:l,producerId:u}=await this.socketHandler.produce(d);return{answer:l,producerId:u}}}class u1 extends d1{constructor(e,r){super(e,r);m(this,gc);m(this,Gl);m(this,Wl);m(this,Jl);m(this,Kl);m(this,ln,void 0);m(this,li,void 0);m(this,$a,void 0);m(this,pc,void 0);m(this,zs,void 0);m(this,jl,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});m(this,Pr,[]);m(this,Ba,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{f(this,pc,new Hh(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{a(this,$a).clear(),f(this,zs,new l1(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return a(this,ln)}get consumers(){return a(this,li)}get producerIdToConsumerIdMap(){return a(this,$a)}get logger(){return this.context.getValue("logger")}reset(){f(this,ln,new Map),f(this,li,new Map),f(this,$a,new Map)}async createProducer(e,r){var i;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const n=await this.sendTransport.produce(e,x(this,Gl,fv).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(_.E2EE_ACTIVE_PRODUCER,n),x(this,Wl,Sv).call(this,n,r),n}catch(n){throw this.logger.error("Failed to create producer",{error:n}),a(this,jl).producerCreationFailureCount+=1,n}}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,ln).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){a(this,Ba)||clearTimeout(a(this,Ba)),f(this,Pr,a(this,Pr).concat(e)),await x(this,gc,pp).call(this)}closeConsumer(e){return this.closeConsumers([e])}async closeConsumers(e){if(!a(this,zs))return;const r=e.map(n=>this.consumers.get(n)).filter(n=>n!==void 0);if(r.length===0)return;const{failedConsumers:i}=await a(this,zs).close(r);i!=null&&i.length&&this.logger.warn("Failed to close some consumers",{consumerIds:i})}closeAllConsumers(){return this.closeConsumers(Array.from(a(this,li).keys()))}async switchConsumersToLayer(e,r){a(this,zs).switchConsumersToLayer(e,r)}}ln=new WeakMap,li=new WeakMap,$a=new WeakMap,pc=new WeakMap,zs=new WeakMap,jl=new WeakMap,Pr=new WeakMap,Ba=new WeakMap,gc=new WeakSet,pp=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=a(this,Pr).splice(0,a(this,Pr).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,x(this,Jl,vv).bind(this),a(this,zs).negotiate.bind(a(this,zs)));if(o.forEach(x(this,Kl,Tv).bind(this)),c!=null&&c.length){this.logger.error("Failed to create consumers for producers",{producers:c});const d=c.filter(({errorCode:l,producerId:u})=>l==="not_found_track_error"?(this.logger.error(`Track not found for producer: ${u}. This will not be retried.`),!1):l==="backend_error"?(this.logger.error("Unrecoverable error: backend error"),!1):!0);f(this,Pr,a(this,Pr).concat(d)),f(this,Ba,setTimeout(x(this,gc,pp).bind(this),e))}}catch(i){if(this.logger.error("failed to consume on transport",{error:i}),i.errorCode==="internal_error"&&i.errorDescription==="Backend error"||i.errorCode==="invalid_session_description"){this.logger.error("Irrecoverable error, closing current recvTransport to create a new one",{transport:this.recvTransport,error:{code:i.errorCode,message:i.errorDescription}});try{this.stopTransports({recv:!0})}catch(n){}await this.setupTransports({recv:!0})}}},Gl=new WeakSet,fv=function(e){return a(this,pc).create(e)},Wl=new WeakSet,Sv=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!==al){const d={producerId:e.id,description:{sdp:o.sdp,type:o.type,target:ir.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,ln).set(e.id,e)},Jl=new WeakSet,vv=async function(e){try{return await this.recvTransport.canConsume(),await a(this,zs).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},Kl=new WeakSet,Tv=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,{id:e.id,appData:e.appData,peerId:e.peerId})};const Zl=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,zl);m(this,Yl);m(this,mc,void 0);m(this,fc,void 0);m(this,Sc,void 0);m(this,Ha,void 0);m(this,qa,void 0);m(this,ja,void 0);m(this,vc,void 0);m(this,Tc,void 0);m(this,Ga,void 0);m(this,Lt,void 0);m(this,As,void 0);m(this,Ms,!1);m(this,un,0);m(this,hn,0);m(this,_r,[]);m(this,yc,void 0);f(this,Ha,t),f(this,Lt,t),f(this,mc,e),f(this,fc,r),f(this,Sc,i),f(this,qa,n),f(this,ja,o),f(this,vc,c),f(this,Tc,d),f(this,Ga,l),f(this,yc,u),f(this,As,t/2)}get voiceDetected(){return a(this,Ms)}processAudioChunk(t){var o,c;const e=x(o=Zl,Ql,bv).call(o,t),r=x(c=Zl,Xl,wv).call(c,t);return x(this,zl,yv).call(this,e),e/a(this,As)>a(this,Ga)&&e>a(this,Lt)&&r>a(this,mc)?(f(this,un,a(this,un)+1),f(this,hn,a(this,Sc)),a(this,un)>=a(this,fc)&&f(this,Ms,!0)):(f(this,un,0),a(this,hn)>0?f(this,hn,a(this,hn)-1):a(this,Ms)&&f(this,Ms,!1),a(this,Ms)||x(this,Yl,Ev).call(this,e)),{energy:e,isVoice:a(this,Ms)}}reset(){f(this,Ms,!1),f(this,un,0),f(this,hn,0),f(this,Lt,a(this,Ha)),f(this,As,a(this,Ha)/2),f(this,_r,[])}getThresholdInfo(){return{currentEnergyThreshold:a(this,Lt),backgroundNoiseEnergy:a(this,As),energyRatioThreshold:a(this,Ga)}}};let _o=Zl;mc=new WeakMap,fc=new WeakMap,Sc=new WeakMap,Ha=new WeakMap,qa=new WeakMap,ja=new WeakMap,vc=new WeakMap,Tc=new WeakMap,Ga=new WeakMap,Lt=new WeakMap,As=new WeakMap,Ms=new WeakMap,un=new WeakMap,hn=new WeakMap,_r=new WeakMap,yc=new WeakMap,zl=new WeakSet,yv=function(t){a(this,Ms)?f(this,Lt,a(this,ja)*a(this,Lt)+(1-a(this,ja))*t):f(this,Lt,a(this,qa)*a(this,Lt)+(1-a(this,qa))*a(this,As)),f(this,Lt,Math.max(a(this,vc),Math.min(a(this,Tc),a(this,Lt))))},Yl=new WeakSet,Ev=function(t){if(t<a(this,Lt)*1.2)if(a(this,_r).push(t),a(this,_r).length>a(this,yc)&&a(this,_r).shift(),a(this,_r).length>=10){const e=[...a(this,_r)].sort((i,n)=>i-n),r=Math.floor(e.length/2);f(this,As,e[r])}else f(this,As,.95*a(this,As)+.05*t)},Ql=new WeakSet,bv=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Xl=new WeakSet,wv=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(_o,Ql),m(_o,Xl);class nS{constructor(t){p(this,"RNAudioSampleHandler");m(this,Ec,void 0);f(this,Ec,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,Ec).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()}}Ec=new WeakMap;class aS{constructor(t){p(this,"audioContext");p(this,"analyser");m(this,bc,void 0);f(this,bc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return a(this,bc).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)}}bc=new WeakMap;class h1{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 p1=60,g1=400,_c=class{constructor(t,e){m(this,eu);m(this,tu);m(this,Rr,void 0);m(this,Cr,void 0);m(this,Os,void 0);m(this,wc,void 0);m(this,pn,void 0);m(this,Wa,void 0);m(this,kr,void 0);m(this,ui,void 0);m(this,Ja,void 0);m(this,Ir,void 0);m(this,Ar,void 0);m(this,Ys,void 0);this.reportRequest=e,f(this,Ir,t),f(this,Wa,new _o);const{isReactNative:r}=navigator;f(this,Ar,r?new nS(a(this,Ir)):new aS(a(this,Ir))),f(this,Ys,r?h1:Bf)}get logger(){return a(this,Ir).getValue("logger")}set producerId(t){f(this,Os,t)}set audioTrack(t){f(this,wc,t),a(this,Ar)instanceof aS&&(a(this,Ar).audioTrack=t)}start(){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${a(this,Os)}`),a(this,Rr)&&a(this,Ys).clearInterval(a(this,Rr)),f(this,Rr,a(this,Ys).setInterval(async()=>{var i;if(!a(this,wc)||!a(this,Os))return;const{energy:t}=x(this,eu,Pv).call(this),e=x(i=_c,Pc,gp).call(i,t);let r=.9;a(this,Ja)!==e&&a(this,Ja)?r=.9:e?r=.3:r=.5,f(this,pn,(a(this,pn)||0)*(1-r)+t*r)},p1)),a(this,Cr)&&a(this,Ys).clearInterval(a(this,Cr)),f(this,Cr,a(this,Ys).setInterval(x(this,tu,_v).bind(this),g1))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${a(this,Os)}`),a(this,Rr)&&(a(this,Ys).clearInterval(a(this,Rr)),f(this,Rr,void 0)),a(this,Cr)&&(a(this,Ys).clearInterval(a(this,Cr)),f(this,Cr,void 0))}catch(t){}a(this,Wa).reset(),a(this,Ar)instanceof nS&&a(this,Ar).stop()}};let Ro=_c;Rr=new WeakMap,Cr=new WeakMap,Os=new WeakMap,wc=new WeakMap,pn=new WeakMap,Wa=new WeakMap,kr=new WeakMap,ui=new WeakMap,Ja=new WeakMap,Ir=new WeakMap,Ar=new WeakMap,Ys=new WeakMap,eu=new WeakSet,Pv=function(){var o;const{samples:t}=a(this,Ar),{energy:e,isVoice:r}=a(this,Wa).processAudioChunk(t),i=x(o=_c,su,Rv).call(o,e);return a(this,Ir).getValue("flagsmith").hasFeature(Z.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: producer: ${a(this,Os)}, energy: ${a(this,pn)},
|
|
17
17
|
slogScale: ${i}, isVoice: ${r}, minEnergy: ${a(this,kr)},
|
|
18
|
-
maxEnergy: ${a(this,ui)}`),i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,kr)||i<a(this,kr))&&f(this,kr,i),(!a(this,ui)||i>a(this,ui))&&f(this,ui,i),{energy:(i-a(this,kr))/(a(this,ui)-a(this,kr))*10||0,isVoice:r})},Pc=new WeakSet,Tp=function(t){return t<5},su=new WeakSet,Ov=function(t=a(this,pn)){var r;if(!a(this,Ns)||!t){a(this,Ir).getValue("flagsmith").hasFeature(Z.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,Ns)}`);return}const e={producerId:a(this,Ns),energy:Math.round(t),silent:x(r=_c,Pc,Tp).call(r,t)};f(this,Ja,e.silent),this.reportRequest(e)},ru=new WeakSet,Dv=function(t){const e=Math.log10(t);return Math.round(e)},m(Ro,Pc),m(Ro,ru);const E1=(s=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const e=new window.MediaStreamTrackGenerator({kind:"audio"}),r=e.writable.getWriter(),i=48e3,n=128,o=1;let c=0,d=null;const l=async()=>{try{const g=new Float32Array(n*o),S=new window.AudioData({format:"f32",sampleRate:i,numberOfFrames:n,numberOfChannels:o,timestamp:c,data:g});c+=n/i*1e6,await r.ready,await r.write(S)}catch(g){d&&clearInterval(d),r.releaseLock(),e.writable.abort()}};d=window.setInterval(l,100);const h=new MediaStream([e]).getAudioTracks()[0];return h.addEventListener("ended",()=>{d&&clearInterval(d),r.releaseLock(),e.writable.abort()}),Object.assign(h,{fakeTracks:"fakeTracks:fakeAudioTrack"}),h.enabled=s,h}catch(e){}const t=window.AudioContext||window.webkitAudioContext;if(t)try{const e=new t;if(!e||e.state!=="running"||!e.destination)return;const r=e.createOscillator();r.frequency.value=0,r.type="sine";const i=e.createGain();i.gain.value=0,r.connect(i);const n=e.createMediaStreamDestination();i.connect(n),r.start();const o=n.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=s,o):void 0}catch(e){return}},w1=(s=!1)=>{var n,o;const t=new MediaStream().getVideoTracks()[0],e=document.createElement("canvas");e.height=(n=t==null?void 0:t.getSettings().height)!=null?n:720,e.width=(o=t==null?void 0:t.getSettings().width)!=null?o:1280;const r=e.getContext("2d");r.fillStyle="black",r.fillRect(0,0,e.width,e.height),setInterval(()=>{r.fillStyle="black",r.fillRect(0,0,e.width,e.height)},1e3);const i=e.captureStream().getVideoTracks()[0];return Object.assign(i,{fakeTracks:"fakeTracks:fakeVideoTrack"}),i.enabled=s,i};var b1=Object.defineProperty,P1=Object.getOwnPropertyDescriptor,ce=(s,t,e,r)=>{for(var i=r>1?void 0:r?P1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&b1(t,e,i),i};const Wt=["video/VP9","video/VP8"],pS=(rp=class{constructor(s,t){m(this,hi);m(this,iu);m(this,nu);m(this,au);m(this,Ac);m(this,cu);m(this,du);m(this,lu);m(this,at);m(this,Tn);m(this,uu);m(this,hu);m(this,pu);p(this,"context");p(this,"authToken");p(this,"e2ee");m(this,Rc,void 0);m(this,Cc,void 0);m(this,vt,void 0);m(this,j,void 0);m(this,Ka,void 0);m(this,kt,void 0);m(this,gn,void 0);m(this,mn,void 0);m(this,fn,void 0);m(this,kc,void 0);m(this,fs,null);m(this,Mr,void 0);m(this,Ic,void 0);m(this,Sn,void 0);m(this,vn,void 0);m(this,It,void 0);m(this,xt,void 0);var r,i;this.context=s;const{socket:e}=t;this.mediaJoined=!1,f(this,Sn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,vn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,vt,e),f(this,gn,!1),f(this,j,new S1(s,e)),f(this,kt,a(this,j).events),f(this,Mr,new Set),f(this,It,new Map),f(this,mn,!1),f(this,fn,new Uh(s.getValue("logger"))),f(this,xt,new Ro(this.context,a(this,j).socketHandler.audioActivity.bind(a(this,j).socketHandler))),this.e2ee=(i=(r=s.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?i:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,kc,Ju(async()=>{if(!a(this,hi,Qa).mediaJoinAttempted)return;const{roomJoined:n}=await this.joinRoom(a(this,Cc),a(this,Rc),!0,!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,hi,Qa).mediaJoined}set mediaJoined(s){a(this,hi,Qa).mediaJoined=s}reset(){a(this,j).closeAllProducers(),a(this,j).closeAllConsumers(),a(this,It).clear(),a(this,Mr).clear(),f(this,fs,null),a(this,fn).stop(),a(this,j).stopAllTransports(),a(this,j).reset(),f(this,fn,new Uh)}async joinRoom(s,t,e=!1,r=!1,i={}){a(this,hi,Qa).mediaJoinAttempted=!0,f(this,gn,!0),e&&this.reset();try{return await a(this,fn).push(()=>x(this,iu,Nv).call(this,s,t,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(s,t,e=!1,r={}){return a(this,fs)?a(this,fs):(f(this,fs,(async()=>{try{await x(this,Ac,yp).call(this,s,t,e,r)}catch(i){throw f(this,fs,null),i}})()),a(this,fs))}getConsumers(){return a(this,j).consumers}getProducers(){return a(this,j).producers}async leaveRoom(){a(this,j).stopAllTransports(),f(this,mn,!1),a(this,hi,Qa).mediaJoinAttempted=!1;const s={closeRoom:!1};a(this,vt).sendMessagePromise(a(this,kt).leaveRoom,yC.toBinary(s)).then(e=>{var r;(r=ck.fromBinary(e.payload))!=null&&r.closed&&this.logger.warn("Weird state on peer closed and should not happen")}).catch(e=>{this.logger.error("error on sending leave room request",{error:e})}),this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct()}async activatePeers(s){return this.createConsumers(s)}async createConsumers(s){return s.length===0?Promise.resolve():a(this,j).createConsumers(s)}async closeConsumers(s){if(!s.length)return;const t=s.reduce((e,r)=>{const i=a(this,j).producerIdToConsumerIdMap.get(r.producerId);return i?(e.push(i),e):(this.logger.warn(`consumer not found in close consumers: ${r.producerId}`),e)},[]);await a(this,j).closeConsumers(t)}async _shareWebcam(s,t){var h,g,S,y;const e=t==="video/VP9"?me.WEBCAM:me.WEBCAM_BACKUP,r=x(this,at,Mt).call(this,e);if(r){const w=await r;if(a(this,j).producers.has(w)){const b=a(this,j).producers.get(w);if(!b.closed)return await b.replaceTrack({track:s}),await this.resumeWebcam(e),s;await this.disableWebcam(t)}return this._shareWebcam(s,t)}const i=[t].concat(Wt.filter(w=>w!==t)),n=x(this,pu,qv).call(this,s,i),o=On(this.context,"disableSimulcast"),c=(g=(h=this.context)==null?void 0:h.getValue("overrides"))==null?void 0:g.simulcastConfig;o||c&&c.disable||!((y=(S=this.context)==null?void 0:S.getValue("theme"))!=null&&y.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),n.encodings=sD(this.context,s)),this.context.getValue("flagsmith").hasFeature(Z.TRACK_HINT)&&(n.track.contentHint=this.context.getValue("flagsmith").getValue(Z.TRACK_HINT));const l=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,It).delete(e)},u=a(this,j).createProducer(n,l);return x(this,Tn,rd).call(this,e,u.then(w=>w.id)),u.then(w=>w.track)}async shareWebcam(s){var r;if(s===void 0)return null;const t=(r=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:r.toString();if(t)return this.logger.debug(`Calling _shareWebcam with forced video codec: ${t}`),this._shareWebcam(s,t);const e=Wt.filter(i=>{var n,o;return((o=(n=a(this,Ka).sender)==null?void 0:n.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===i))>=0&&a(this,vn).get(i).size>0});return e.length===0&&e.push(Wt[0]),await Promise.all(e.map(i=>(this.logger.debug(`Calling _shareWebcam with video codec: ${i}`),this._shareWebcam(s,i)))),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:be.isElectron()},stopTracks:!1},i=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,It).delete(me.SCREENSHARE_VIDEO),a(this,It).delete(me.SCREENSHARE_AUDIO)},n=a(this,j).createProducer(r,i);x(this,Tn,rd).call(this,me.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:be.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},d=()=>{};o=a(this,j).createProducer(c,d),x(this,Tn,rd).call(this,me.SCREENSHARE_AUDIO,o.then(l=>l.id))}await Promise.all([n,o||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()}async shareMic(s){try{if(s===void 0)throw new Nt("track undefined");const t=x(this,at,Mt).call(this,me.MIC);if(t){const n=await t;if(a(this,j).producers.has(n)){const o=a(this,j).producers.get(n);if(!o.closed){await o.replaceTrack({track:s}),await this.resumeMic(),a(this,xt)&&(a(this,xt).audioTrack=s,a(this,xt).producerId=n,a(this,xt).start());return}await a(this,j).closeProducer(n,{stopTrack:!1})}await this.shareMic(s);return}const e=x(this,hu,Hv).call(this,s),r=()=>{a(this,It).delete(me.MIC)},i=a(this,j).createProducer(e,r);x(this,Tn,rd).call(this,me.MIC,i.then(n=>n.id)),await i.then(n=>{a(this,xt)&&(a(this,xt).audioTrack=n.track,a(this,xt).producerId=n.id,a(this,xt).start())})}catch(t){throw new k(t)}}async pauseMic(){var r;const s=await x(this,at,Mt).call(this,me.MIC),t=a(this,j).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,xt))==null||r.stop();const e={producerId:t.id,pause:!0};a(this,vt).sendMessage(a(this,kt).toggleProducer,xd.toBinary(e))}async pauseWebcam(){const s=await x(this,at,Mt).call(this,me.WEBCAM),t=await x(this,at,Mt).call(this,me.WEBCAM_BACKUP),e=a(this,j).producers.get(s),r=a(this,j).producers.get(t);if(!e&&!r){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}const i=n=>{const o={producerId:n.id,pause:!0};a(this,vt).sendMessage(a(this,kt).toggleProducer,xd.toBinary(o))};e&&(e.pause(),i(e)),r&&(r.pause(),i(r))}async resumeMic(){const s=await x(this,at,Mt).call(this,me.MIC),t=a(this,j).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,vt).sendMessage(a(this,kt).toggleProducer,xd.toBinary(e))}async resumeWebcam(s=me.WEBCAM){const t=await x(this,at,Mt).call(this,s),e=a(this,j).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,vt).sendMessage(a(this,kt).toggleProducer,xd.toBinary(r))}async disableWebcam(s){const t=s==="video/VP9"?me.WEBCAM:me.WEBCAM_BACKUP,e=await x(this,at,Mt).call(this,t);x(this,uu,Bv).call(this,t),e&&await a(this,j).closeProducer(e)}async disableMic(){var t;const s=await x(this,at,Mt).call(this,me.MIC);s&&await a(this,j).closeProducer(s),(t=a(this,xt))==null||t.stop(),a(this,It).delete(me.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const s=await x(this,at,Mt).call(this,me.SCREENSHARE_VIDEO),t=await x(this,at,Mt).call(this,me.SCREENSHARE_AUDIO);s&&await a(this,j).closeProducer(s),t&&await a(this,j).closeProducer(t),a(this,Mr).clear(),a(this,It).delete(me.SCREENSHARE_VIDEO),a(this,It).delete(me.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(s,t){if(s){const e=await x(this,at,Mt).call(this,me.WEBCAM),r=await x(this,at,Mt).call(this,me.WEBCAM_BACKUP);await a(this,j).closeProducer(e,{stopTrack:!1}),await a(this,j).closeProducer(r,{stopTrack:!1}),this.shareWebcam(s)}if(t){const e=await x(this,at,Mt).call(this,me.SCREENSHARE_VIDEO);await a(this,j).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,j).socketHandler.changeDisplayName(e))throw new Error("failed to change display name!")}kick(s){const t={peerIds:[s]};a(this,j).socketHandler.kickPeer(t)}kickAll(){a(this,j).socketHandler.kickAll()}async muteAll(s){if(!await a(this,j).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await a(this,j).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(s){if(!await a(this,j).socketHandler.hostControlForPeer(s,"audio"))throw new Error("failed to mute given participant")}async disableVideo(s){if(!await a(this,j).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,vt).sendMessagePromise(a(this,kt).globalPinPeer,NC.toBinary(t))}catch(e){this.logger.error("Error in pinning peer:",{error:e})}}validateScreenShare(s){return this.peerId===s.peerId&&a(this,j).producers.get(s.producerId)&&a(this,Mr).add(s.consumerPeerId),a(this,Mr).size}async switchConsumersToLayer(s,t){const e=s.map(r=>this.getConsumers().get(r));a(this,j).switchConsumersToLayer(e,t)}async handleSocketEvents(){a(this,vt).on(a(this,kt).peerProducerCreateBroadcast,({payload:s})=>{var t,e;if(this.mediaJoined)try{const{participantId:r,producerState:i}=Uk.fromBinary(s);if(r===this.peerId)return;if(i!=null&&i.mimeType||(i.mimeType=i.kind===qs.AUDIO?"audio/opus":"video/VP8"),i.kind===qs.VIDEO&&!i.screenShare&&((e=(t=a(this,Ka).receiver)==null?void 0:t.video)==null?void 0:e.codecs.findIndex(n=>n.mimeType===Wt[0]))>=0&&a(this,Sn).get(Wt[0]).has(r)&&i.mimeType!==Wt[0]){this.logger.warn(`Ignoring producer: ${i.producerId}`);return}this.logger.info(`producer created broadcast: ${r}, producer state: ${i}`),this.context.getValue("peerSessionStore").emit(_.NEW_PRODUCER,{peerId:r,producer:{...i,kind:i.kind===qs.AUDIO?"audio":"video",producingPeerId:r}})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),a(this,vt).on(a(this,kt).peerProducerToggleBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,initiatorParticipantId:e,producerState:{kind:r,pause:i,producerId:n,screenShare:o}}=tf.fromBinary(s);if(o)return;const c=r===qs.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${t}, producerId: ${n}, kind:${c}, paused:${i} payload: ${JSON.stringify(tf.fromBinary(s))}`),t===this.peerId&&e!==this.peerId&&i&&this.context.getValue("peerSessionStore").emit(c==="audio"?_.MUTE_SELF:_.MUTE_SELF_VIDEO),t===this.peerId)return;this.context.getValue("peerSessionStore").emit(_.PRODUCER_TOGGLE,{peerId:t,producerId:n,paused:i,kind:c}),Array.from(this.getConsumers().values()).filter(l=>l.producerId===n).forEach(l=>{l.kind==="video"&&i||l.paused!==i&&(this.logger.debug(`consumer state mismatched for ${l.id}. updating consumer pause state ${l.paused} to ${i}`),i?(l.pause(),this.context.getValue("peerSessionStore").emit(_.CONSUMER_PAUSED,{id:l.id})):(l.resume(),this.context.getValue("peerSessionStore").emit(_.CONSUMER_RESUMED,{id:l.id})))})}catch(t){this.logger.error("error in producer toggle broadcast handler",{error:t})}}),a(this,vt).on(a(this,kt).peerLeaveBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t}=ah.fromBinary(s);if(t===this.peerId)return;this.logger.info(`peer left broadcast:${t}`),a(this,Mr).delete(t),a(this,j).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,vt).on(a(this,kt).peerProducerCloseBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,producerState:{producerId:e}}=Bk.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,j).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,j).closeConsumer(r).then(()=>{this.logger.info(`closed consumer: ${r}`),a(this,j).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,vt).on(a(this,kt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,gn)&&!a(this,mn)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(_.ROOM_NODE_DISCONNECTED),a(this,kc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(s=>{s.forEach((t,e)=>{const r=a(this,j).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,j).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})})})}handlePeerCapabilities(s,t){var e,r,i,n;for(let o=0;o<=Wt.length;o+=1){const c=Wt[o];if(((r=(e=t==null?void 0:t.receiver)==null?void 0:e.video)==null?void 0:r.codecs.findIndex(d=>d.mimeType===c))>=0||o===Wt.length-1){a(this,vn).get(c).add(s);break}}for(let o=0;o<=Wt.length;o+=1){const c=Wt[o];if(((n=(i=t==null?void 0:t.sender)==null?void 0:i.video)==null?void 0:n.codecs.findIndex(d=>d.mimeType===c))>=0||o===Wt.length-1){a(this,Sn).get(c).add(s);break}}}handlePeerLeaving(s){this.context.getValue("flagsmith").hasFeature(Z.FORCE_VIDEO_CODEC)||(a(this,Sn).forEach(t=>t.delete(s)),a(this,vn).forEach((t,e)=>{t.delete(s),!(t.size!==0||e===Wt[0])&&this.disableWebcam(e)}))}},Rc=new WeakMap,Cc=new WeakMap,vt=new WeakMap,j=new WeakMap,Ka=new WeakMap,kt=new WeakMap,gn=new WeakMap,mn=new WeakMap,fn=new WeakMap,kc=new WeakMap,fs=new WeakMap,Mr=new WeakMap,Ic=new WeakMap,Sn=new WeakMap,vn=new WeakMap,It=new WeakMap,xt=new WeakMap,hi=new WeakSet,Qa=function(){return this.context.getValue("connectionHandler")},iu=new WeakSet,Nv=async function(s,t,e,r){f(this,Cc,s);try{return a(this,fs)?await a(this,fs):await x(this,Ac,yp).call(this,s,t,e,r),x(this,au,Lv).call(this,t),{roomJoined:await x(this,nu,Vv).call(this)}}catch(i){return this.logger.error("Failed to complete room join",{error:i}),{roomJoined:!1,error:i}}finally{f(this,fs,null)}},nu=new WeakSet,Vv=async function(){try{this.mediaJoined=!0;const{roomState:s}=await a(this,j).socketHandler.notifySelfJoinComplete();return f(this,Rc,s.roomUuid),f(this,mn,!0),f(this,gn,!1),!0}catch(s){return this.logger.error("Error completing room join",{error:s}),this.mediaJoined=!1,!1}},au=new WeakSet,Lv=function(s){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:s,roomViewType:"groupCall",deviceInfo:{...be.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)},Ac=new WeakSet,yp=async function(s,t,e,r){var i,n;try{(n=a(this,Ic))!=null||f(this,Ic,x(i=pS,ou,xv).call(i));const o=x(this,cu,Uv).call(this);await x(this,du,Fv).call(this,s,t,e,o),await a(this,j).setupTransports({send:!0,recv:!0}),await x(this,lu,$v).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},ou=new WeakSet,xv=function(){const{ipInfo:s}=ht();if(!(s!=null&&s.loc))return;const[t,e]=s.loc.split(",").map(parseFloat);return{latitude:t,longitude:e}},cu=new WeakSet,Uv=function(){var e;const s=(e=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:e.toString(),t=XD(s);return f(this,Ka,t),t},du=new WeakSet,Fv=async function(s,t,e,r){await aS(async(i,n)=>{if(!a(this,vt).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,j).socketHandler.joinRoom(t,s,r,e,a(this,Ic))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}},{delayTime:1e3,strategy:"exponential",maxRetryCount:15})},lu=new WeakSet,$v=async function(s){if(!(!this.context.getValue("flagsmith").hasFeature(Z.PRECREATE_PRODUCERS)||!s))try{const e=[];if(s.canProduceVideo===H.Allowed&&e.push(this.shareWebcam(w1(!1))),s.canProduceAudio===H.Allowed){const r=E1(!1);r&&e.push(this.shareMic(r))}e.length>0&&await Promise.all(e)}catch(e){this.logger.warn("Failed to precreate producers",{error:e})}},at=new WeakSet,Mt=function(s){return a(this,It).get(s)},Tn=new WeakSet,rd=function(s,t){return a(this,It).set(s,t)},uu=new WeakSet,Bv=function(s){return a(this,It).delete(s)},hu=new WeakSet,Hv=function(s){return{track:s,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},pu=new WeakSet,qv=function(s,t){return{track:s,codecOptions:t?t.map(e=>({name:e.split("/")[1]})):[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},m(rp,ou),rp);let re=pS;ce([E.trace("MediaNodeClient.reset",{country:E.location.country})],re.prototype,"reset",1),ce([E.trace("MediaNodeClient.joinRoom")],re.prototype,"joinRoom",1),ce([E.trace("MediaNodeClient.leaveRoom")],re.prototype,"leaveRoom",1),ce([E.trace("MediaNodeClient.activatePeers")],re.prototype,"activatePeers",1),ce([E.trace("MediaNodeClient.createConsumers")],re.prototype,"createConsumers",1),ce([E.trace("MediaNodeClient.closeConsumers")],re.prototype,"closeConsumers",1),ce([E.trace("MediaNodeClient._shareWebcam")],re.prototype,"_shareWebcam",1),ce([E.trace("MediaNodeClient.shareWebcam")],re.prototype,"shareWebcam",1),ce([E.trace("MediaNodeClient.shareScreen")],re.prototype,"shareScreen",1),ce([E.trace("MediaNodeClient.shareMic")],re.prototype,"shareMic",1),ce([E.trace("MediaNodeClient.pauseMic")],re.prototype,"pauseMic",1),ce([E.trace("MediaNodeClient.pauseWebcam")],re.prototype,"pauseWebcam",1),ce([E.trace("MediaNodeClient.resumeMic")],re.prototype,"resumeMic",1),ce([E.trace("MediaNodeClient.resumeWebcam")],re.prototype,"resumeWebcam",1),ce([E.trace("MediaNodeClient.disableWebcam")],re.prototype,"disableWebcam",1),ce([E.trace("MediaNodeClient.disableMic")],re.prototype,"disableMic",1),ce([E.trace("MediaNodeClient.disableScreenShare")],re.prototype,"disableScreenShare",1),ce([E.trace("MediaNodeClient.muteSelf")],re.prototype,"muteSelf",1),ce([E.trace("MediaNodeClient.resetVideoProducers")],re.prototype,"resetVideoProducers",1),ce([E.trace("MediaNodeClient.changeDisplayName")],re.prototype,"changeDisplayName",1),ce([E.trace("MediaNodeClient.kickPeer")],re.prototype,"kick",1),ce([E.trace("MediaNodeClient.kickAllPeers")],re.prototype,"kickAll",1),ce([E.trace("MediaNodeClient.muteAll")],re.prototype,"muteAll",1),ce([E.trace("MediaNodeClient.muteAllVideo")],re.prototype,"muteAllVideo",1),ce([E.trace("MediaNodeClient.disableAudio")],re.prototype,"disableAudio",1),ce([E.trace("MediaNodeClient.disableVideo")],re.prototype,"disableVideo",1),ce([E.trace("MediaNodeClient.pinPeer")],re.prototype,"pinPeer",1),ce([E.trace("MediaNodeClient.validateScreenShare")],re.prototype,"validateScreenShare",1);function gS(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 re(s,t);return s.setValue("roomNodeClient",r),r}function mS(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,R1=Object.getOwnPropertyDescriptor,Ni=(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&&_1(t,e,i),i};const fS=(rv=class{constructor(s,t,e,r){m(this,At);p(this,"self");p(this,"authToken");m(this,yn,void 0);p(this,"viewType");m(this,Vs,void 0);m(this,X,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,f(this,X,s),this.viewType=r,this.authToken=n,f(this,yn,i),f(this,Vs,e),this.setupEvents()}get peerId(){return a(this,X).getValue("peerId")}get telemetry(){return a(this,X).getValue("telemetry")}get logger(){return a(this,X).getValue("logger")}get mediaJoined(){return a(this,X).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const n=ht(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await Ze.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");if(navigator.product!=="ReactNative"){const u=!s.getValue("flagsmith").hasFeature(Z.PRECALL_BANDWIDTH_TEST);setTimeout(async()=>{const h=await d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(h)}),s.getValue("callstats").devices("AUDIO",h==null?void 0:h.filter(g=>g.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",h==null?void 0:h.filter(g=>g.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",h==null?void 0:h.filter(g=>g.kind==="audiooutput")),l.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:o,engineName:be.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:s.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:bm(s),skipConnectivityChecks:u}),l.info("Callstats:: initialized")}catch(g){l.error("Callstats:: initialization failed",{error:g})}},0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new fS(s,d,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===H.Allowed&&r)try{await a(this,At,ts).shareMic(s),this.self.audioEnabled||a(this,At,ts).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===H.Allowed&&i)try{const d=await a(this,At,ts).shareWebcam(t);d&&d.id!==t.id&&a(this,X).getValue("flagsmith").hasFeature(Z.EXP_RESHARE)&&await a(this,At,ts).shareWebcam(d),this.self.videoEnabled||a(this,At,ts).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===H.Allowed&&n)try{await((c=a(this,At,ts))==null?void 0:c.shareScreen({video:o.video,audio:o.audio}))}catch(d){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,X).getValue("callstats").callEnded(),a(this,At,ts).reset(),s&&await this.joinRoom(s)}setupEvents(){a(this,X).getValue("peerSessionStore").on(_.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),a(this,X).getValue("peerSessionStore").on(_.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,X).getValue("peerSessionStore").on(_.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,X).getValue("peerSessionStore").on(_.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,X).getValue("peerSessionStore").on(_.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),a(this,X).getValue("peerSessionStore").on(_.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&a(this,X).getValue("flagsmith").hasFeature(Z.REFRESH_ID_ON_DISCONNECTION)&&(t=fi()),a(this,yn).updateURL(t),a(this,X).getValue("telemetry").resetPeerId(t),ht().setHeader("tracing-id",t),sr.remapContext(t,a(this,X)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,X).getValue("peerSessionStore").on(_.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Vs).on(U.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Vs).on(qd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,X).getValue("peerSessionStore").emit(_.UPDATE_PERMISSIONS,t.patch)})}),a(this,Vs).on(U.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Vs).on(U.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Vs).on(U.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,X).getValue("peerSessionStore").onAsync(_.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,X).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,X).getValue("peerSessionStore").on(_.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,X).getValue("callstats").audioOff())}),a(this,X).getValue("peerSessionStore").on(_.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,X).getValue("callstats").videoOff())}),a(this,X).getValue("peerSessionStore").onAsync(_.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,X).getValue("peerSessionStore").on(_.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await a(this,Vs).joinRoom(this.self);a(this,Vs).socket.flush();const e=_h(t.stageType);if(a(this,X).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}await this.joinMediaRoom(s),a(this,X).notify("stageStatus")}catch(t){throw this.logger.error("Error in joinRoom",{error:t}),t}}async leaveRoom(s="left"){var t,e;if(this.logger.info(`Leaving room with state: ${s}`),(t=a(this,X).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),a(this,X).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,X).notify("stageStatus");try{(e=a(this,yn))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}mS(a(this,X)),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,c;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=a(this,X).getAllValues();try{if(e===tr.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}gS(a(this,X),{socket:a(this,yn),peerId:t})}const{canProduceAudio:d,canProduceVideo:l,canProduceScreenshare:u}=this.self.permissions,{roomJoined:h,error:g}=(o=await((n=a(this,At,ts))==null?void 0:n.joinRoom(this.self.name,r,s,s,{canProduceAudio:d,canProduceVideo:l,canProduceScreenshare:u})))!=null?o:{};if(!h)throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:g}),g;i==="ON_STAGE"&&await this.shareMediaTracks(),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(d){throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:d}),new k(`${(c=d==null?void 0:d.message)!=null?c:"could not connect to media servers"}`,"0002")}}async leaveMediaRoom(s){const t=a(this,X).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===tr.Webinar)&&a(this,At,ts)&&(a(this,At,ts).mediaJoined&&s!=="disconnected"&&await a(this,At,ts).leaveRoom(),!(s==="stageLeft"&&t===tr.Livestream)&&(a(this,At,ts).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()}},yn=new WeakMap,Vs=new WeakMap,X=new WeakMap,At=new WeakSet,ts=function(){return a(this,X).getValue("roomNodeClient")},rv);let jr=fS;Ni([E.trace("SelfController.resetSelf")],jr.prototype,"resetSelf",1),Ni([E.trace("SelfController.setupEvents")],jr.prototype,"setupEvents",1),Ni([E.trace("SelfController.joinRoom")],jr.prototype,"joinRoom",1),Ni([E.trace("SelfController.leaveRoom")],jr.prototype,"leaveRoom",1),Ni([E.trace("SelfController.joinMediaRoom")],jr.prototype,"joinMediaRoom",1),Ni([E.trace("SelfController.leaveMediaRoom")],jr.prototype,"leaveMediaRoom",1),Ni([E.trace("SelfController.init")],jr,"init",1);class C1{constructor(t){m(this,Mc,void 0);f(this,Mc,t)}on(t,e){let r;t===U.roomPeerCount?r=nf.fromBinary.bind(nf):r=wf.fromBinary.bind(wf),a(this,Mc).on(t,({payload:i})=>{if(t===U.roomPeerCount&&!i)return;const n=r(i);e(n)})}}Mc=new WeakMap;class k1{constructor(t,e){m(this,Oc,void 0);m(this,Dc,void 0);f(this,Oc,e),f(this,Dc,t)}get logger(){return a(this,Dc).getValue("logger")}on(t,e){let r,i;switch(t){case U.transcript:{r=oh.fromBinary.bind(oh),i=oh.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Oc).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)})}}Oc=new WeakMap,Dc=new WeakMap;var I1=Object.defineProperty,A1=Object.getOwnPropertyDescriptor,Wh=(s,t,e,r)=>{for(var i=r>1?void 0:r?A1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&I1(t,e,i),i};class cl{constructor(t,e){m(this,Or,void 0);m(this,za,void 0);f(this,Or,e),f(this,za,t)}get logger(){return a(this,za).getValue("logger")}get telemetry(){return a(this,za).getValue("telemetry")}getPolls(){return a(this,Or).sendMessagePromise(ar.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Or).sendMessage(ar.createPoll,PM.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Or).sendMessage(ar.votePoll,RM.toBinary(r))}on(t,e){let r,i;switch(t){case ar.updatePoll:case ar.createPoll:case ar.votePoll:{r=yh.fromBinary.bind(yh),i=yh.create();break}}a(this,Or).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,Or).removeListeners(t)}}Or=new WeakMap,za=new WeakMap,Wh([E.trace("PollSocketHandler.getPolls")],cl.prototype,"getPolls",1),Wh([E.trace("PollSocketHandler.createPoll")],cl.prototype,"createPoll",1),Wh([E.trace("PollSocketHandler.votePoll")],cl.prototype,"votePoll",1);var M1=Object.defineProperty,O1=Object.getOwnPropertyDescriptor,D1=(s,t,e,r)=>{for(var i=r>1?void 0:r?O1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&M1(t,e,i),i};class SS{constructor(t,e){p(this,"socket");m(this,Zt,void 0);f(this,Zt,t),this.socket=e,this.handleSocketEvents(),a(this,Zt).setValue("roomSocketHandler",this)}get telemetry(){return a(this,Zt).getValue("telemetry")}get logger(){return a(this,Zt).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(U.joinRoom,fI.toBinary(e));try{const{peer:n}=Nn.fromBinary((await r).payload);a(this,Zt).getValue("connectionHandler").socketJoined=!0,a(this,Zt).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,Zt).getValue("peerSessionStore").emit(_.ROOM_STATE,d),a(this,Zt).getValue("peerSessionStore").emit(_.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),new k("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,n)}}async getAllAddedParticipants(){try{return eA.fromBinary((await this.socket.sendMessagePromise(U.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(U.getRoomPeersInfo,aI.toBinary(n));i=lh.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(U.getRoomPeersInfo);t=lh.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(U.getRoomPeersInfo);t=lh.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(U.getPeerInfo,cf.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(U.getRoomInfo);t=of.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(U.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(U.broadcastMessage,mo.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(U.broadcastToEntity,mo.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(U.broadcastToEntity,mo.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(U.leaveRoom,vI.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(U.kick,hf.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(U.kickAll,Ym.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(U.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.acceptWaitingRoomRequests,aA.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.denyWaitingRoomRequests,cA.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(qd.updateUserPreset,xA.toBinary(r))}handleSocketEvents(){this.socket.on(U.broadcastMessage,({payload:t})=>{try{const e=mo.fromBinary(t);a(this,Zt).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(U.broadcastToEntity,({payload:t})=>{try{const e=mo.fromBinary(t);a(this,Zt).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 U.joinRoom:case U.leaveRoom:case U.kick:case U.kickAll:{r=Nn.fromBinary.bind(Nn),i=Nn.create();break}case U.getWaitingRoomRequests:{r=(n,o)=>n?pf.fromBinary(n,o):{requests:[]},i=pf.create();break}case U.recordingPaused:case U.recordingStarted:case U.recordingStopped:{r=Rf.fromBinary.bind(Rf);break}case qd.updateUserPreset:{r=ff.fromBinary.bind(ff);break}case ws.peerJoinedBroadcast:case Fr.peerJoinedBroadcast:{r=Zm.fromBinary.bind(Zm);break}case ws.selfJoinComplete:case Fr.selfJoinComplete:{r=nh.fromBinary.bind(nh);break}case ws.globalPeerPinBroadcast:case Fr.globalPeerPinBroadcast:{r=sf.fromBinary.bind(sf);break}case ws.selectedPeer:case Fr.selectedPeer:{r=ih.fromBinary.bind(ih);break}case ws.selectedPeerDiff:case Fr.selectedPeerDiff:{r=Xm.fromBinary.bind(Xm);break}case ws.leaveRoom:case Fr.leaveRoom:{r=ah.fromBinary.bind(ah);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(qd.getUserPresets,AA.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}}}Zt=new WeakMap,D1([E.trace("RoomSocketHandler.joinRoom")],SS.prototype,"joinRoom",1);class N1{constructor(t){m(this,Ut,void 0);f(this,Ut,t)}async getStageRequests(){const{payload:t}=await a(this,Ut).sendMessagePromise(U.getStageRequests);return t?Th.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,Ut).sendMessage(U.requestStageAccess)}cancelRequestAccess(){a(this,Ut).sendMessage(U.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,Ut).sendMessage(U.grantStageAccess,gM.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,Ut).sendMessage(U.denyStageAccess,fM.toBinary(e))}joinStage(){return a(this,Ut).sendMessagePromise(U.joinStage,void 0,void 0,U.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,Ut).sendMessagePromise(U.leaveStage,Pf.toBinary(e),void 0,U.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,Ut).sendMessagePromise(U.leaveStage,Pf.toBinary(e))}on(t,e){let r;switch(t){case U.grantStageAccess:case U.denyStageAccess:{r=void 0;break}case U.getStagePeers:{r=bf.fromBinary.bind(bf);break}case U.getStageRequests:case U.requestStageAccess:case U.cancelStageRequest:{r=Th.fromBinary.bind(Th);break}case U.peerStageStatusUpdate:{r=rf.fromBinary.bind(rf);break}}a(this,Ut).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,Ut).sendMessagePromise(U.getPeerInfo,cf.toBinary({peerId:t}));return Nn.fromBinary(e.payload)}}Ut=new WeakMap;class V1{constructor(t,e){m(this,Ye,void 0);m(this,Nc,void 0);f(this,Ye,e),f(this,Nc,t)}get logger(){return a(this,Nc).getValue("logger")}addPlugin(t,e){a(this,Ye).sendMessage(G.addPlugin,M0.toBinary({pluginId:t,staggered:e}))}removePlugin(t){a(this,Ye).sendMessage(G.removePlugin,D0.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await a(this,Ye).sendMessagePromise(G.getPlugins);return t?sM.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};a(this,Ye).sendMessage(G.customPluginEventToRoom,q0.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const n={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};a(this,Ye).sendMessage(G.customPluginEventToPeers,G0.toBinary(n),i)}enablePluginForRoom(t,e){a(this,Ye).sendMessage(G.enablePluginForRoom,V0.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){a(this,Ye).sendMessage(G.enablePluginForPeers,F0.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){a(this,Ye).sendMessage(G.disablePluginForRoom,x0.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){a(this,Ye).sendMessage(G.disablePluginForPeers,B0.toBinary({pluginId:t,peerIds:e}),r)}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,Ye).sendMessage(G.storeInsertKeys,vf.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,Ye).sendMessage(G.storeGetKeys,z0.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,Ye).sendMessage(G.storeDeleteKeys,Q0.toBinary(n),i)}storeDelete(t,e,r){a(this,Ye).sendMessage(G.storeDelete,Z0.toBinary({pluginId:t,storeName:e}),r)}getPluginDataOld(t,e){this.logger.info("getPluginDataOld",{plugin:{id:t,storeName:e}})}storePluginDataOld(t,e,r){const i={pluginId:t,storeName:e,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};a(this,Ye).sendMessage(G.storeInsertKeys,vf.toBinary(i))}on(t,e){let r;switch(t){case G.addPlugin:case G.enablePluginForPeers:case G.enablePluginForRoom:{r=vh.fromBinary.bind(vh);break}case G.removePlugin:case G.disablePluginForPeers:case G.disablePluginForRoom:{r=Tf.fromBinary.bind(Tf);break}case G.customPluginEventToPeers:case G.customPluginEventToRoom:{r=Ef.fromBinary.bind(Ef);break}case G.storeInsertKeys:case G.storeGetKeys:case G.storeDeleteKeys:case G.storeDelete:{r=yf.fromBinary.bind(yf);break}}a(this,Ye).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}Ye=new WeakMap,Nc=new WeakMap;var L1=Object.defineProperty,x1=(s,t,e)=>t in s?L1(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,U1=(s,t,e)=>(x1(s,typeof t!="symbol"?t+"":t,e),e),Jh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},O=(s,t,e)=>(Jh(s,t,"read from private field"),e?e.call(s):t.get(s)),ye=(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)},ie=(s,t,e,r)=>(Jh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),Pe=(s,t,e)=>(Jh(s,t,"access private method"),e),dl={},F1={get exports(){return dl},set exports(s){dl=s}},Hn=typeof Reflect=="object"?Reflect:null,vS=Hn&&typeof Hn.apply=="function"?Hn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},ll;Hn&&typeof Hn.ownKeys=="function"?ll=Hn.ownKeys:Object.getOwnPropertySymbols?ll=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:ll=function(s){return Object.getOwnPropertyNames(s)};function $1(s){console&&console.warn&&console.warn(s)}var TS=Number.isNaN||function(s){return s!==s};function de(){de.init.call(this)}F1.exports=de,dl.once=j1,de.EventEmitter=de,de.prototype._events=void 0,de.prototype._eventsCount=0,de.prototype._maxListeners=void 0;var yS=10;function ul(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(de,"defaultMaxListeners",{enumerable:!0,get:function(){return yS},set:function(s){if(typeof s!="number"||s<0||TS(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");yS=s}}),de.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},de.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||TS(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 ES(s){return s._maxListeners===void 0?de.defaultMaxListeners:s._maxListeners}de.prototype.getMaxListeners=function(){return ES(this)},de.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")vS(c,this,t);else for(var d=c.length,l=RS(c,d),e=0;e<d;++e)vS(l[e],this,t);return!0};function wS(s,t,e,r){var i,n,o;if(ul(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=ES(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,$1(c)}return s}de.prototype.addListener=function(s,t){return wS(this,s,t,!1)},de.prototype.on=de.prototype.addListener,de.prototype.prependListener=function(s,t){return wS(this,s,t,!0)};function B1(){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 bS(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=B1.bind(r);return i.listener=e,r.wrapFn=i,i}de.prototype.once=function(s,t){return ul(t),this.on(s,bS(this,s,t)),this},de.prototype.prependOnceListener=function(s,t){return ul(t),this.prependListener(s,bS(this,s,t)),this},de.prototype.removeListener=function(s,t){var e,r,i,n,o;if(ul(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():H1(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this},de.prototype.off=de.prototype.removeListener,de.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 PS(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?q1(i):RS(i,i.length)}de.prototype.listeners=function(s){return PS(this,s,!0)},de.prototype.rawListeners=function(s){return PS(this,s,!1)},de.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):_S.call(s,t)},de.prototype.listenerCount=_S;function _S(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}de.prototype.eventNames=function(){return this._eventsCount>0?ll(this._events):[]};function RS(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function H1(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function q1(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function j1(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))}CS(s,t,n,{once:!0}),t!=="error"&&G1(s,i,{once:!0})})}function G1(s,t,e){typeof s.on=="function"&&CS(s,"error",t,e)}function CS(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 W1 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 W1;class IS{static encode(t){return kS.toBinary(t)}static decode(t){return kS.fromBinary(new Uint8Array(t))}}function J1(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Gr;class K1{constructor(t={}){U1(this,"opts"),ye(this,Gr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ie(this,Gr,0)}async wait(){ie(this,Gr,O(this,Gr)+1);const t=J1(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**O(this,Gr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return O(this,Gr)}reset(){ie(this,Gr,0)}}Gr=new WeakMap;const Wr={debug:0,info:1,warn:2,error:3};var Vi,Li;class z1{constructor(t){ye(this,Vi,void 0),ye(this,Li,void 0),ie(this,Vi,console),ie(this,Li,t)}debug(...t){Wr[O(this,Li)]>Wr.debug||O(this,Vi).debug("[Sockrates]:",...t)}info(...t){Wr[O(this,Li)]>Wr.info||O(this,Vi).info("[Sockrates]:",...t)}warn(...t){Wr[O(this,Li)]>Wr.warn||O(this,Vi).warn("[Sockrates]:",...t)}error(...t){Wr[O(this,Li)]>Wr.error||O(this,Vi).error("[Sockrates]:",...t)}}Vi=new WeakMap,Li=new WeakMap;var AS=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(AS||{});const Y1="2",Q1="3";var De,qn,_e,Ue,Jr,et,ur,Kr,Rs,jn,hr,Kh,MS,Co,hl,zh,OS,Yh,DS,pl,Qh,Xh,NS,ko,gl,Io,ml,fl,Zh,Gn,Ao,Mo,Sl;class X1{constructor(t,e){var g,S,y,w,b,C,D,F,L,B;ye(this,Kh),ye(this,Co),ye(this,zh),ye(this,Yh),ye(this,pl),ye(this,Xh),ye(this,ko),ye(this,Io),ye(this,fl),ye(this,Gn),ye(this,Mo),ye(this,De,void 0),ye(this,qn,void 0),ye(this,_e,void 0),ye(this,Ue,void 0),ye(this,Jr,void 0),ye(this,et,void 0),ye(this,ur,void 0),ye(this,Kr,void 0),ye(this,Rs,void 0),ye(this,jn,void 0),ye(this,hr,void 0);var r,i,n,o,c,d,l,u,h;ie(this,qn,t),ie(this,Jr,[]),ie(this,et,new dl),ie(this,ur,!0),ie(this,Rs,!1),ie(this,_e,e!=null?e:{}),(g=(r=O(this,_e)).autoReconnect)!=null||(r.autoReconnect=!0),(S=(i=O(this,_e)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(y=(n=O(this,_e)).pingTimeout)!=null||(n.pingTimeout=3e4),(w=(o=O(this,_e)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(b=(c=O(this,_e)).debug)!=null||(c.debug=!0),(C=(d=O(this,_e)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(D=(l=O(this,_e)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(F=(u=O(this,_e)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(L=(h=O(this,_e)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),ie(this,Kr,{code:void 0,reason:void 0}),ie(this,Ue,(B=O(this,_e).logger)!=null?B:new z1(O(this,_e).debug?"debug":"info")),ie(this,hr,new K1)}get readyState(){var t;return(t=O(this,De))==null?void 0:t.readyState}get url(){return O(this,qn)}updateURL(t){ie(this,qn,t),Pe(this,Xh,NS).call(this)}get config(){return O(this,_e)}get sendQueue(){return O(this,Jr)}flush(){if(!O(this,_e).queueOnDisconnect)return!1;const t=[];return O(this,Jr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ie(this,Jr,t),O(this,Jr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){O(this,Ue).debug("Websocket was already connecting or connected.");return}if(O(this,ur)!==!1)return new Promise((e,r)=>{Pe(this,Gn,Ao).call(this),Pe(this,Mo,Sl).call(this);try{ie(this,De,new WebSocket(Pe(this,Kh,MS).call(this,O(this,qn)))),O(this,De).binaryType="arraybuffer",O(this,Ue).debug("Connecting");const i=setTimeout(()=>{O(this,Ue).debug("Connection timeout. Closing socket"),ie(this,ur,!0),Pe(this,Mo,Sl).call(this),O(this,De).close(3001,"Connection Timeout"),O(this,_e).autoReconnect&&!O(this,Rs)&&(O(this,et).emit("reconnecting"),Pe(this,ko,gl).call(this)),r(new Error("Connection timed out!"))},O(this,_e).connectionTimeout);O(this,De).onopen=()=>{O(this,Ue).debug(`Ready State: ${AS[O(this,De).readyState]}`),i&&clearTimeout(i),Pe(this,fl,Zh).call(this),ie(this,Kr,{code:void 0,reason:void 0}),O(this,et).emit("connected"),O(this,_e).flushOnReconnect&&this.flush(),e()},O(this,De).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),O(this,Ue).debug("Socket closed. Close event:",{event:n}),O(this,Ue).debug(`Connection closed code: ${o}`),O(this,Ue).debug(`Connection closed reason: ${c}`),O(this,Rs)||Pe(this,pl,Qh).call(this,o,c)}catch(o){Pe(this,Co,hl).call(this,o)}},O(this,De).onerror=n=>{Pe(this,Co,hl).call(this,n)},O(this,De).onmessage=n=>Pe(this,zh,OS).call(this,n)}catch(i){Pe(this,Co,hl).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(O(this,_e).queueOnDisconnect&&(!O(this,De)||O(this,De).readyState!==1))return O(this,Ue).debug("Queuing message since socket is not connected!",n),O(this,Jr).push(n),!1;const o=IS.encode(n);return Pe(this,Io,ml).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return Pe(this,Io,ml).call(this,t)}receive(t,e){return O(this,et).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")){O(this,et).on(t,e);return}this.receive(t,e)}removeAllListeners(){O(this,et).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){O(this,et).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){O(this,et).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ie(this,ur,!1),Pe(this,Gn,Ao).call(this),this.removeAllListeners(),ie(this,Kr,{code:1e3,reason:"Sockrates disconnect method called"}),O(this,De).close(1e3,"Sockrates disconnect method called.")}}De=new WeakMap,qn=new WeakMap,_e=new WeakMap,Ue=new WeakMap,Jr=new WeakMap,et=new WeakMap,ur=new WeakMap,Kr=new WeakMap,Rs=new WeakMap,jn=new WeakMap,hr=new WeakMap,Kh=new WeakSet,MS=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)://.")},Co=new WeakSet,hl=function(s,t){O(this,Ue).error("Error:",{error:s}),O(this,et).emit("errored",{error:s}),t==null||t(s)},zh=new WeakSet,OS=function(s){if(Pe(this,fl,Zh).call(this),s.data===Y1){O(this,Ue).debug("Received ping from server"),Pe(this,Io,ml).call(this,Q1);return}const t=IS.decode(s.data),{id:e,payload:r}=t;O(this,Ue).debug("Received message",{event:t.event,messageID:e}),O(this,et).emit(t.event.toString(),{id:e,payload:r})},Yh=new WeakSet,DS=function(){return O(this,De).readyState===1},pl=new WeakSet,Qh=function(s,t){ie(this,Kr,{reason:t,code:s}),O(this,et).emit("disconnected",{code:s,reason:t})},Xh=new WeakSet,NS=function(){const{reason:s,code:t}=O(this,Kr);t&&t!==1e3&&O(this,ur)&&O(this,_e).autoReconnect&&!O(this,Rs)&&(O(this,Ue).debug(`Triggering reconnection due to ${s}.`),O(this,et).emit("reconnecting"),Pe(this,ko,gl).call(this))},ko=new WeakSet,gl=async function(s=!0){if(s&&O(this,Rs)){O(this,Ue).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(O(this,Rs)||O(this,hr).reset(),O(this,_e).maxReconnectionAttempts!==null&&O(this,hr).getAttempts()>=O(this,_e).maxReconnectionAttempts){O(this,et).emit("failed"),ie(this,Rs,!1);return}ie(this,Rs,!0),Pe(this,Mo,Sl).call(this),Pe(this,Gn,Ao).call(this);try{if(await O(this,hr).wait(),O(this,ur)===!1)return;if(O(this,Ue).debug(`Reconnection attempt ${O(this,hr).getAttempts()}`),O(this,et).emit("reconnectAttempt",{attempt:O(this,hr).getAttempts()}),await this.connect(),!Pe(this,Yh,DS).call(this))throw Error("Reconnect Failed");ie(this,Rs,!1),ie(this,Kr,{code:void 0,reason:void 0}),O(this,et).emit("reconnected")}catch(t){O(this,Ue).debug("Failed to reconnect."),O(this,et).emit("reconnectFailure",{attempt:O(this,hr).getAttempts()}),Pe(this,ko,gl).call(this,!1)}},Io=new WeakSet,ml=function(s){try{return O(this,De).send(s),!0}catch(t){return O(this,Ue).error(t.message),!1}},fl=new WeakSet,Zh=function(){this.config.disconnectOnPingTimeout&&(O(this,Ue).debug("Resetting ping timeout"),Pe(this,Gn,Ao).call(this),ie(this,jn,setTimeout(()=>{var s;O(this,Ue).debug("Disconnecting the socket due to ping timeout"),ie(this,ur,!0);const t=3002,e="Ping timeout";(s=O(this,De))==null||s.close(t,e),Pe(this,pl,Qh).call(this,t,e)},O(this,_e).pingTimeout)))},Gn=new WeakSet,Ao=function(){O(this,jn)&&(clearTimeout(O(this,jn)),ie(this,jn,void 0))},Mo=new WeakSet,Sl=function(){O(this,De)&&(O(this,De).onopen=void 0,O(this,De).onerror=void 0,O(this,De).onmessage=void 0,O(this,De).onclose=void 0)};var Z1=Object.defineProperty,eN=Object.getOwnPropertyDescriptor,vl=(s,t,e,r)=>{for(var i=r>1?void 0:r?eN(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&&Z1(t,e,i),i};const VS=65535,tN=3e3,LS=(iv=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){m(this,Me);m(this,Vc);m(this,Lc);m(this,pi,void 0);m(this,Ae,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");m(this,Ss,void 0);m(this,ot,void 0);var n;if(!t||!e||!r)throw new k("peerId, meetingId, or authToken can not be empty","0404");f(this,Ss,void 0),f(this,ot,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,pi,x(this,Vc,Ep).call(this,t)),f(this,Ae,new X1(a(this,pi),{autoReconnect:!0,disconnectOnPingTimeout:(n=i.includes("PING"))!=null?n:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Me,je).socketJoinAttempted}set joinAttempted(s){a(this,Me,je).socketJoinAttempted=s}get telemetry(){return a(this,ot).getValue("telemetry")}get logger(){return a(this,ot).getValue("logger")}get peerId(){return a(this,ot).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,pi,x(this,Vc,Ep).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Ae).updateURL(a(this,pi))}static getSocketEdgeDomain(s){return wi({servicePrefix:"socket-edge",baseURI:s})}get url(){return a(this,pi)}async connect(){a(this,Me,je).socketJoinAttempted=!0,await a(this,Ae).connect(),a(this,Me,je).socketJoinAttempted=!0,a(this,Me,je).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){a(this,Me,je).socketJoinAttempted=!1,a(this,Ae).disconnect(),a(this,Me,je).socketJoinAttempted=!0,a(this,Me,je).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Ae).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return a(this,ot).getValue("telemetry").injectContext(r),a(this,Ae).send(s,e!=null?e:x(this,Lc,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}){const n=i!=null?i:s;return new Promise((o,c)=>{const d=(y,w)=>{a(this,Ae).removeListener(n,y),a(this,Ae).removeListener(VS,w),a(this,Ae).removeListener(Fr.errorResponse,w),a(this,Ae).removeListener(ws.errorResponse,w)},l=r!=null?r:x(this,Lc,wp).call(this),u={};a(this,ot).getValue("telemetry").injectContext(u);const g=({id:y,payload:w})=>{if(l===y){let b;try{const C=XC.fromBinary(w);b=new Error(C.errorMessage)}catch(C){b=new Error("failed to parse error message",{cause:C});try{const D=Zk.fromBinary(w);b=new Error(D.message)}catch(D){b=new Error("failed to parse error message",{cause:D})}}c(b),d(S,g)}},S=({id:y,payload:w})=>{l===y&&(o({id:y,payload:w}),d(S,g))};a(this,Ae).on(n,S),a(this,Ae).on(VS,g),a(this,Ae).on(Fr.errorResponse,g),a(this,Ae).on(ws.errorResponse,g),setTimeout(()=>{d(S,g),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Ae).send(s,l,e,new TextEncoder().encode(JSON.stringify(u)))})}on(s,t){a(this,Ae).on(s,t)}onStateEvent(s,t){a(this,Ae).on(s,t)}removeListener(s,t){a(this,Ae).removeListener(s,t)}removeListeners(s){a(this,Ae).removeListeners(s)}flush(){return a(this,Ae).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),a(this,Ss)&&(clearTimeout(a(this,Ss)),f(this,Ss,void 0)),a(this,Me,je).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t},country:E.location.country});const{recv:e,send:r}=(i=a(this,Me,je).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==Bn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Bn.CONNECTED?a(this,ot).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Me,je).joinAttempted}):f(this,Ss,setTimeout(()=>{a(this,ot).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Me,je).joinAttempted}),f(this,Ss,void 0)},tN)),a(this,Me,je).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge",{country:E.location.country}),a(this,Me,je).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),a(this,Me,je).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),a(this,Me,je).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Me,je).mediaJoinAttempted}}),a(this,Ss)&&(clearTimeout(a(this,Ss)),f(this,Ss,void 0)),a(this,ot).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Me,je).mediaJoinAttempted}),a(this,Me,je).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge",{country:E.location.country}),a(this,ot).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_FAILED),a(this,Me,je).updateSocketConnectionState("failed")})}},pi=new WeakMap,Ae=new WeakMap,Me=new WeakSet,je=function(){return a(this,ot).getValue("connectionHandler")},Ss=new WeakMap,ot=new WeakMap,Vc=new WeakSet,Ep=function(s){let t=LS.getSocketEdgeDomain(a(this,ot).getValue("baseURI"));typeof On(a(this,ot),"socket_server_base")=="string"&&(t=On(a(this,ot),"socket_server_base"));const e=`wss://${t}`,r=new URL(`${e}/ws`),i=this.peerId,n={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...i!==s&&{oldPeerID:i},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>Ud[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(n).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},Lc=new WeakSet,wp=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},iv);let Oo=LS;vl([E.trace("SocketService.connect")],Oo.prototype,"connect",1),vl([E.trace("SocketService.disconnect")],Oo.prototype,"disconnect",1),vl([E.trace("SocketService.sendMessagePromise")],Oo.prototype,"sendMessagePromise",1),vl([E.trace("SocketService.sendMessagePromiseWithTimeout")],Oo.prototype,"sendMessagePromiseWithTimeout",1);class sN{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=RI.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=XI.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=uf.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 HI.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(U.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(U.createConnectedRooms,AI.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(U.deleteConnectedRooms,$I.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(U.movePeers,KI.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 rN=Object.defineProperty,iN=Object.getOwnPropertyDescriptor,nN=(s,t,e,r)=>{for(var i=r>1?void 0:r?iN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&rN(t,e,i),i};class xS extends $t{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);m(this,Ls,void 0);f(this,Ls,e)}get supportsConnectedMeetings(){return a(this,Ls).getValue("self").id!==""}get isActive(){return this.meetings.length!==0}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
|
|
19
|
-
Please connect with our support team to enable connected meetings.`)}async getConnectedMeetings(){this.validateConnectedMeetingsAction(),this.logger.info("Getting connected meetings dump");const e=await a(this,
|
|
20
|
-
Please connect with our support team to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:a(this,Se).getValue("self").videoEnabled,audio:a(this,Se).getValue("self").audioEnabled};try{a(this,Se).getValue("self").cleanupEvents(),await a(this,Se).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,Se).getValue("meeting"))==null?void 0:i.meta)==null?void 0:n.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await $S.init({...a(this,Se).getValue("options"),cachedUserDetails:null,defaults:{...a(this,Se).getValue("options").defaults,...e,mediaHandler:a(this,Se).getValue("self")},authToken:s});this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(o=r==null?void 0:r.meta)==null?void 0:o.meetingId}`);try{const{hidden:d}=a(this,Se).getValue("self");r.self.setName(a(this,Se).getValue("self").name),await r.join(),d&&r.self.hide()}catch(d){this.logger.error("ConnectedMeetingsController.joinRoom",{error:d})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(c=r==null?void 0:r.meta)==null?void 0:c.meetingId}`),this.connectedMeetings.emit("meetingChanged",r),r}handleConnectedRoomsDump(s){const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(s);this.connectedMeetings.meetings=t.meetings.map(e=>({id:e.id,title:e.title,participants:e.participants||[]})),this.connectedMeetings.parentMeeting={id:t.parentMeeting.id,title:t.parentMeeting.title,participants:t.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(s){return a(this,Se).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=a(this,Se).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,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(s).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},Se=new WeakMap,nv);let Tl=US;ep([E.trace("ConnectedMeetingsController.getConnectedMeetings")],Tl.prototype,"getConnectedMeetings",1),ep([E.trace("ConnectedMeetingsController.setupEvents")],Tl.prototype,"setupEvents",1),ep([E.trace("ConnectedMeetingsController.switchMeeting")],Tl.prototype,"switchMeeting",1);var cN=Object.defineProperty,dN=Object.getOwnPropertyDescriptor,yl=(s,t,e,r)=>{for(var i=r>1?void 0:r?dN(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&&cN(t,e,i),i};const Wn=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 L,B;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(mS(s),be.isSupported()===!1)throw new k("Browser not supported","0010",c,!0);const d=tO(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 LO(s);s.setValue("connectionHandler",l);const u=Wn.createSocketService(s),h=u.connect(),g=d.getUserDetails(),S=d.getPlugins();let y,w="";try{await Wn.setupFlagsmith(s)}catch(W){c.error("Failed to setup flagsmith",{error:W})}try{await h}catch(W){c.error("[Controller]: Failed to connect to socket server:",{error:W})}try{({meetingTitle:w}=await d.getRoomNodeData()),y=await g,c.info("CF SFU is being used."),s.setValue("presetName",y.preset.name)}catch(W){c.error("Failed to get room metadata",{error:W})}const b=Dh.init(y.preset,!s.getValue("modules").theme);s.setValue("theme",b);const C=Vh.init(s,b.viewType,y.preset.permissions),D=Wn.setupControllers(u,s,y,S,w,b,C);_O(b)&&((L=Wn.createRoomNodeClient(s,u).initializeConnection(y.participant.name,i,!1,C))==null||L.catch(ae=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:ae})})),E.location.country=(B=d.ipInfo)==null?void 0:B.country;const{controllers:F}=await D;return aR(),new Wn(e,F,s)}static async setupFlagsmith(s){var l;const{peerId:t,baseURI:e,overrides:r,meetingId:i,organizationId:n,logger:o}=s.getAllValues(),c=nR(i),d={entity:Yu.PEER,clientId:n,isAnonUser:!n,sdkVersion:s.getValue("sdkVersion"),presetName:s.getValue("presetName"),meetingHash:c,roomName:i,...be.getDeviceInfo(),isReactNative:navigator.isReactNative};try{const u=(l=r==null?void 0:r.whitelabelled_flags_endpoint)==null||l?wi({servicePrefix:"flags",baseURI:e}):"edge.api.flagsmith.com";await s.getValue("flagsmith").identify(`${Yu.PEER}_${t}`,JSON.parse(JSON.stringify(d)),!1,5e3,u,o),o.info("flagsmith::allFlags",{flags:JSON.stringify(s.getValue("flagsmith").getAllFlags())},!0)}catch(u){o.error("Failed to fetch flagsmith flags")}}static async setupControllers(s,t,e,r,i,n,o){var V,R,Je;const c=t.getValue("modules"),{participant:d}=e,l=t.getValue("defaults"),u=t.getValue("logger"),{viewType:h,mediaConstraints:{audio:g}}=n;t.setValue("viewType",h),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(V=g.enableHighBitrate)!=null?V:!1,enableStereo:(R=g.enableStereo)!=null?R:!1}},...l}),t.setValue("maxPreferredStreams",be.isMobile()?n.maxVideoStreams.mobile:n.maxVideoStreams.desktop);let S,y,w,b,C,D,F,L,B;const W=new k1(t,s),ae=new sN(s);t.setValue("connectedMeetingsSocketHandler",ae);const Tt=new cl(t,s),xs=new or(t,s),_n=new N1(s),Us=new SS(t,s),I=new V1(t,s),T=new C1(s),P=await jr.init(t,Us,d,o,n);t.setValue("selfController",P);const $=await Vf.init(t,P.self,Us,W,i);if(c.participant&&(L=new lr(t,P.self,Us)),(Je=c.e2ee)!=null&&Je.enabled&&c.e2ee.manager.init(u,t.getValue("peerSessionStore")),c.chat&&(y=await as.init(t,xs,P.self,L.participants)),c.internals&&(C=await kh.init(t)),c.livestream&&n.viewType===tr.Livestream&&t.getValue("flagsmith").hasFeature(Z.LIVESTREAM)&&(F=new tS(t,P.self,T)),c.poll&&(S=await Mf.init(t,P.self,Tt)),c.recording&&(D=new $f(t,P.self,Us)),c.stage&&(w=new Lf(t,_n,Us,P.self,L.participants)),c.plugin){if(!L)throw new k("The plugin module cannot be initialized without the `participant` module","0102");const Dr=await r;b=await vo.init(t,Dr,I,xs,y==null?void 0:y.chat,P.self,L.participants,i)}if(c.connectedMeetings&&(B=await Tl.init(t)),c.pip){const Dr=await Qu._init(t,P.self);t.setValue("pip",Dr)}const qe={storesManager:new ND(t,I),pollController:S,selfController:P,metaController:$,chatController:y,stageController:w,pluginController:b,recordingController:D,internalsController:C,livestreamController:F,participantController:L,connectedMeetingsController:B};return{theme:n,permissions:o,controllers:qe}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return gS(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=["PING"];return new Oo(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Do=Wn;yl([E.trace("Controller.init")],Do,"init",1),yl([E.trace("setupFlagsmith")],Do,"setupFlagsmith",1),yl([E.trace("Controller.createRoomNodeClient")],Do,"createRoomNodeClient",1),yl([E.trace("Controller.createSocketService")],Do,"createSocketService",1);class lN{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 FS=new lN;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=bi.baseURI.prod;t&&(n=t);const o=`https://${wi({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new k("Invalid auth token","0004")}}class hN{constructor(){m(this,gu);m(this,gi,new Audio);m(this,En,new MediaStream);m(this,wn,new Map);m(this,xc,void 0);a(this,gi).srcObject=a(this,En),a(this,gi).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,wn).has(e.id)||(a(this,En).addTrack(e),a(this,wn).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,gi).setSinkId(t)}removeTrack(t){const e=a(this,wn).get(t);e&&(a(this,En).removeTrack(e),a(this,wn).delete(t))}async play(){return a(this,gi).srcObject=a(this,En),a(this,gi).play().catch(t=>{x(this,gu,jv).call(this,t)})}onError(t){f(this,xc,t)}}gi=new WeakMap,En=new WeakMap,wn=new WeakMap,xc=new WeakMap,gu=new WeakSet,jv=function(t){var e;(e=a(this,xc))==null||e.call(this,t)};class pN extends hN{constructor(){super();m(this,bn,void 0);f(this,bn,new Map)}addParticipantTrack(e,r){a(this,bn).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,bn).get(e);r&&this.removeTrack(r),a(this,bn).delete(e)}}bn=new WeakMap;var gN=Object.defineProperty,mN=Object.getOwnPropertyDescriptor,El=(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&&gN(t,e,i),i};let zr=(av=class{constructor(t,e){m(this,Qe,void 0);m(this,Pn,void 0);f(this,Pn,t),f(this,Qe,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:fi(),n=sr.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new iS(n,o);return await c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var g,S,y,w,b,C;be.init();const e=(S=(g=t==null?void 0:t.cachedUserDetails)==null?void 0:g.peerId)!=null?S:fi(),{authToken:r,baseURI:i}=t,{meetingId:n,...o}=uN(r,i);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=zr.setupContext(e,t,n,o),d=c.getValue("telemetry"),l=c.getValue("logger");Kv(l),FS.init(l),d.init(c,{roomName:n,userId:o.participantId,organizationId:o.orgId,peerId:e},(w=(y=t.modules)==null?void 0:y.tracing)!=null?w:!0),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(b=t.authToken)==null?void 0:b.slice(0,10)}...
|
|
21
|
-
${(
|
|
18
|
+
maxEnergy: ${a(this,ui)}`),i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,kr)||i<a(this,kr))&&f(this,kr,i),(!a(this,ui)||i>a(this,ui))&&f(this,ui,i),{energy:(i-a(this,kr))/(a(this,ui)-a(this,kr))*10||0,isVoice:r})},Pc=new WeakSet,gp=function(t){return t<5},tu=new WeakSet,_v=function(t=a(this,pn)){var r;if(!a(this,Os)||!t){a(this,Ir).getValue("flagsmith").hasFeature(Z.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,Os)}`);return}const e={producerId:a(this,Os),energy:Math.round(t),silent:x(r=_c,Pc,gp).call(r,t)};f(this,Ja,e.silent),this.reportRequest(e)},su=new WeakSet,Rv=function(t){const e=Math.log10(t);return Math.round(e)},m(Ro,Pc),m(Ro,su);const m1=(s=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const e=new window.MediaStreamTrackGenerator({kind:"audio"}),r=e.writable.getWriter(),i=48e3,n=128,o=1;let c=0,d=null;const l=async()=>{try{const g=new Float32Array(n*o),S=new window.AudioData({format:"f32",sampleRate:i,numberOfFrames:n,numberOfChannels:o,timestamp:c,data:g});c+=n/i*1e6,await r.ready,await r.write(S)}catch(g){d&&clearInterval(d),r.releaseLock(),e.writable.abort()}};d=window.setInterval(l,100);const h=new MediaStream([e]).getAudioTracks()[0];return h.addEventListener("ended",()=>{d&&clearInterval(d),r.releaseLock(),e.writable.abort()}),Object.assign(h,{fakeTracks:"fakeTracks:fakeAudioTrack"}),h.enabled=s,h}catch(e){}const t=window.AudioContext||window.webkitAudioContext;if(t)try{const e=new t;if(!e||e.state!=="running"||!e.destination)return;const r=e.createOscillator();r.frequency.value=0,r.type="sine";const i=e.createGain();i.gain.value=0,r.connect(i);const n=e.createMediaStreamDestination();i.connect(n),r.start();const o=n.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=s,o):void 0}catch(e){return}},f1=(s=!1)=>{var n,o;const t=new MediaStream().getVideoTracks()[0],e=document.createElement("canvas");e.height=(n=t==null?void 0:t.getSettings().height)!=null?n:720,e.width=(o=t==null?void 0:t.getSettings().width)!=null?o:1280;const r=e.getContext("2d");r.fillStyle="black",r.fillRect(0,0,e.width,e.height),setInterval(()=>{r.fillStyle="black",r.fillRect(0,0,e.width,e.height)},1e3);const i=e.captureStream().getVideoTracks()[0];return Object.assign(i,{fakeTracks:"fakeTracks:fakeVideoTrack"}),i.enabled=s,i};var S1=Object.defineProperty,v1=Object.getOwnPropertyDescriptor,ce=(s,t,e,r)=>{for(var i=r>1?void 0:r?v1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&S1(t,e,i),i};const Gt=["video/VP9","video/VP8"];class ie{constructor(t,e){m(this,hi);m(this,ru);m(this,iu);m(this,nu);m(this,Ic);m(this,au);m(this,ou);m(this,cu);m(this,ct);m(this,Tn);m(this,du);m(this,lu);m(this,uu);p(this,"context");p(this,"authToken");p(this,"e2ee");m(this,Rc,void 0);m(this,Cc,void 0);m(this,vt,void 0);m(this,j,void 0);m(this,Ka,void 0);m(this,kt,void 0);m(this,gn,void 0);m(this,mn,void 0);m(this,fn,void 0);m(this,kc,void 0);m(this,gs,null);m(this,Mr,void 0);m(this,Sn,void 0);m(this,vn,void 0);m(this,It,void 0);m(this,xt,void 0);var i,n;this.context=t;const{socket:r}=e;this.mediaJoined=!1,f(this,Sn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,vn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,vt,r),f(this,gn,!1),f(this,j,new u1(t,r)),f(this,kt,a(this,j).events),f(this,Mr,new Set),f(this,It,new Map),f(this,mn,!1),f(this,fn,new Vh(t.getValue("logger"))),f(this,xt,new Ro(this.context,a(this,j).socketHandler.audioActivity.bind(a(this,j).socketHandler))),this.e2ee=(n=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,kc,ju(async()=>{if(!a(this,hi,Qa).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(a(this,Cc),a(this,Rc),!0,!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,hi,Qa).mediaJoined}set mediaJoined(t){a(this,hi,Qa).mediaJoined=t}reset(){a(this,j).closeAllProducers(),a(this,j).closeAllConsumers(),a(this,It).clear(),a(this,Mr).clear(),f(this,gs,null),a(this,fn).stop(),a(this,j).stopAllTransports(),a(this,j).reset(),f(this,fn,new Vh)}async joinRoom(t,e,r=!1,i=!1,n={}){a(this,hi,Qa).mediaJoinAttempted=!0,f(this,gn,!0),r&&this.reset();try{return await a(this,fn).push(()=>x(this,ru,Cv).call(this,t,e,i,n),"joinRoom")}catch(o){return this.logger.error("Error in room joining process",{error:o}),this.context.getValue("peerSessionStore").emit(_.ROOM_NODE_FAILED),{roomJoined:!1,error:o}}}async initializeConnection(t,e,r=!1,i={}){return a(this,gs)?a(this,gs):(f(this,gs,(async()=>{try{await x(this,Ic,mp).call(this,t,e,r,i)}catch(n){throw f(this,gs,null),n}})()),a(this,gs))}getConsumers(){return a(this,j).consumers}getProducers(){return a(this,j).producers}async leaveRoom(){a(this,j).stopAllTransports(),f(this,mn,!1),a(this,hi,Qa).mediaJoinAttempted=!1;const t={closeRoom:!1};a(this,vt).sendMessagePromise(a(this,kt).leaveRoom,gC.toBinary(t)).then(r=>{var i;(i=sk.fromBinary(r.payload))!=null&&i.closed&&this.logger.warn("Weird state on peer closed and should not happen")}).catch(r=>{this.logger.error("error on sending leave room request",{error:r})}),this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct()}async activatePeers(t){return this.createConsumers(t)}async createConsumers(t){return t.length===0?Promise.resolve():a(this,j).createConsumers(t)}async closeConsumers(t){if(!t.length)return;const e=t.reduce((r,i)=>{const n=a(this,j).producerIdToConsumerIdMap.get(i.producerId);return n?(r.push(n),r):(this.logger.warn(`consumer not found in close consumers: ${i.producerId}`),r)},[]);await a(this,j).closeConsumers(e)}async _shareWebcam(t,e){var g,S,y,w;const r=e==="video/VP9"?me.WEBCAM:me.WEBCAM_BACKUP,i=x(this,ct,Mt).call(this,r);if(i){const b=await i;if(a(this,j).producers.has(b)){const C=a(this,j).producers.get(b);if(!C.closed)return await C.replaceTrack({track:t}),await this.resumeWebcam(r),t;await this.disableWebcam(e)}return this._shareWebcam(t,e)}const n=[e].concat(Gt.filter(b=>b!==e)),o=x(this,uu,Vv).call(this,t,n),c=On(this.context,"disableSimulcast"),d=(S=(g=this.context)==null?void 0:g.getValue("overrides"))==null?void 0:S.simulcastConfig;c||d&&d.disable||!((w=(y=this.context)==null?void 0:y.getValue("theme"))!=null&&w.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),o.encodings=YO(this.context,t)),this.context.getValue("flagsmith").hasFeature(Z.TRACK_HINT)&&(o.track.contentHint=this.context.getValue("flagsmith").getValue(Z.TRACK_HINT));const u=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,It).delete(r)},h=a(this,j).createProducer(o,u);return x(this,Tn,sd).call(this,r,h.then(b=>b.id)),h.then(b=>b.track)}async shareWebcam(t){var i;if(t===void 0)return null;const e=(i=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:i.toString();if(e)return this.logger.debug(`Calling _shareWebcam with forced video codec: ${e}`),this._shareWebcam(t,e);const r=Gt.filter(n=>{var o,c;return((c=(o=a(this,Ka).sender)==null?void 0:o.video)==null?void 0:c.codecs.findIndex(d=>d.mimeType===n))>=0&&a(this,vn).get(n).size>0});return r.length===0&&r.push(Gt[0]),await Promise.all(r.map(n=>(this.logger.debug(`Calling _shareWebcam with video codec: ${n}`),this._shareWebcam(t,n)))),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:we.isElectron()},stopTracks:!1},n=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,It).delete(me.SCREENSHARE_VIDEO),a(this,It).delete(me.SCREENSHARE_AUDIO)},o=a(this,j).createProducer(i,n);x(this,Tn,sd).call(this,me.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:we.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},l=()=>{};c=a(this,j).createProducer(d,l),x(this,Tn,sd).call(this,me.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 Nt("track undefined");const e=x(this,ct,Mt).call(this,me.MIC);if(e){const o=await e;if(a(this,j).producers.has(o)){const c=a(this,j).producers.get(o);if(!c.closed){await c.replaceTrack({track:t}),await this.resumeMic(),a(this,xt)&&(a(this,xt).audioTrack=t,a(this,xt).producerId=o,a(this,xt).start());return}await a(this,j).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=x(this,lu,Nv).call(this,t),i=()=>{a(this,It).delete(me.MIC)},n=a(this,j).createProducer(r,i);x(this,Tn,sd).call(this,me.MIC,n.then(o=>o.id)),await n.then(o=>{a(this,xt)&&(a(this,xt).audioTrack=o.track,a(this,xt).producerId=o.id,a(this,xt).start())})}catch(e){throw new k(e)}}async pauseMic(){var i;const t=await x(this,ct,Mt).call(this,me.MIC),e=a(this,j).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,xt))==null||i.stop();const r={producerId:e.id,pause:!0};a(this,vt).sendMessage(a(this,kt).toggleProducer,Ld.toBinary(r))}async pauseWebcam(){const t=await x(this,ct,Mt).call(this,me.WEBCAM),e=await x(this,ct,Mt).call(this,me.WEBCAM_BACKUP),r=a(this,j).producers.get(t),i=a(this,j).producers.get(e);if(!r&&!i){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}const n=o=>{const c={producerId:o.id,pause:!0};a(this,vt).sendMessage(a(this,kt).toggleProducer,Ld.toBinary(c))};r&&(r.pause(),n(r)),i&&(i.pause(),n(i))}async resumeMic(){const t=await x(this,ct,Mt).call(this,me.MIC),e=a(this,j).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,vt).sendMessage(a(this,kt).toggleProducer,Ld.toBinary(r))}async resumeWebcam(t=me.WEBCAM){const e=await x(this,ct,Mt).call(this,t),r=a(this,j).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,vt).sendMessage(a(this,kt).toggleProducer,Ld.toBinary(i))}async disableWebcam(t){const e=t==="video/VP9"?me.WEBCAM:me.WEBCAM_BACKUP,r=await x(this,ct,Mt).call(this,e);x(this,du,Dv).call(this,e),r&&await a(this,j).closeProducer(r)}async disableMic(){var e;const t=await x(this,ct,Mt).call(this,me.MIC);t&&await a(this,j).closeProducer(t),(e=a(this,xt))==null||e.stop(),a(this,It).delete(me.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await x(this,ct,Mt).call(this,me.SCREENSHARE_VIDEO),e=await x(this,ct,Mt).call(this,me.SCREENSHARE_AUDIO);t&&await a(this,j).closeProducer(t),e&&await a(this,j).closeProducer(e),a(this,Mr).clear(),a(this,It).delete(me.SCREENSHARE_VIDEO),a(this,It).delete(me.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await x(this,ct,Mt).call(this,me.WEBCAM),i=await x(this,ct,Mt).call(this,me.WEBCAM_BACKUP);await a(this,j).closeProducer(r,{stopTrack:!1}),await a(this,j).closeProducer(i,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await x(this,ct,Mt).call(this,me.SCREENSHARE_VIDEO);await a(this,j).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,j).socketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}kick(t){const e={peerIds:[t]};a(this,j).socketHandler.kickPeer(e)}kickAll(){a(this,j).socketHandler.kickAll()}async muteAll(t){if(!await a(this,j).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await a(this,j).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await a(this,j).socketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await a(this,j).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,vt).sendMessagePromise(a(this,kt).globalPinPeer,kC.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&a(this,j).producers.get(t.producerId)&&a(this,Mr).add(t.consumerPeerId),a(this,Mr).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));a(this,j).switchConsumersToLayer(r,e)}async handleSocketEvents(){a(this,vt).on(a(this,kt).peerProducerCreateBroadcast,({payload:t})=>{var e,r;if(this.mediaJoined)try{const{participantId:i,producerState:n}=Ok.fromBinary(t);if(i===this.peerId)return;if(n!=null&&n.mimeType||(n.mimeType=n.kind===Bs.AUDIO?"audio/opus":"video/VP8"),n.kind===Bs.VIDEO&&!n.screenShare&&((r=(e=a(this,Ka).receiver)==null?void 0:e.video)==null?void 0:r.codecs.findIndex(o=>o.mimeType===Gt[0]))>=0&&a(this,Sn).get(Gt[0]).has(i)&&n.mimeType!==Gt[0]){this.logger.warn(`Ignoring producer: ${n.producerId}`);return}this.logger.info(`producer created broadcast: ${i}, producer state: ${n}`),this.context.getValue("peerSessionStore").emit(_.NEW_PRODUCER,{peerId:i,producer:{...n,kind:n.kind===Bs.AUDIO?"audio":"video",producingPeerId:i}})}catch(i){this.logger.error("error in peer-producer-create-broadcast",{error:i})}}),a(this,vt).on(a(this,kt).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:r,producerState:{kind:i,pause:n,producerId:o,screenShare:c}}=zm.fromBinary(t);if(c)return;const d=i===Bs.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${o}, kind:${d}, paused:${n} payload: ${JSON.stringify(zm.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,vt).on(a(this,kt).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=rh.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),a(this,Mr).delete(e),a(this,j).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,vt).on(a(this,kt).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=Vk.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,j).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,j).closeConsumer(i).then(()=>{this.logger.info(`closed consumer: ${i}`),a(this,j).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,vt).on(a(this,kt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,gn)&&!a(this,mn)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(_.ROOM_NODE_DISCONNECTED),a(this,kc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=a(this,j).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,j).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})})})}handlePeerCapabilities(t,e){var r,i,n,o;for(let c=0;c<=Gt.length;c+=1){const d=Gt[c];if(((i=(r=e==null?void 0:e.receiver)==null?void 0:r.video)==null?void 0:i.codecs.findIndex(l=>l.mimeType===d))>=0||c===Gt.length-1){a(this,vn).get(d).add(t);break}}for(let c=0;c<=Gt.length;c+=1){const d=Gt[c];if(((o=(n=e==null?void 0:e.sender)==null?void 0:n.video)==null?void 0:o.codecs.findIndex(l=>l.mimeType===d))>=0||c===Gt.length-1){a(this,Sn).get(d).add(t);break}}}handlePeerLeaving(t){this.context.getValue("flagsmith").hasFeature(Z.FORCE_VIDEO_CODEC)||(a(this,Sn).forEach(e=>e.delete(t)),a(this,vn).forEach((e,r)=>{e.delete(t),!(e.size!==0||r===Gt[0])&&this.disableWebcam(r)}))}}Rc=new WeakMap,Cc=new WeakMap,vt=new WeakMap,j=new WeakMap,Ka=new WeakMap,kt=new WeakMap,gn=new WeakMap,mn=new WeakMap,fn=new WeakMap,kc=new WeakMap,gs=new WeakMap,Mr=new WeakMap,Sn=new WeakMap,vn=new WeakMap,It=new WeakMap,xt=new WeakMap,hi=new WeakSet,Qa=function(){return this.context.getValue("connectionHandler")},ru=new WeakSet,Cv=async function(t,e,r,i){f(this,Cc,t);try{return a(this,gs)?await a(this,gs):await x(this,Ic,mp).call(this,t,e,r,i),x(this,nu,Iv).call(this,e),{roomJoined:await x(this,iu,kv).call(this)}}catch(n){return this.logger.error("Failed to complete room join",{error:n}),{roomJoined:!1,error:n}}finally{f(this,gs,null)}},iu=new WeakSet,kv=async function(){try{this.mediaJoined=!0;const{roomState:t}=await a(this,j).socketHandler.notifySelfJoinComplete();return f(this,Rc,t.roomUuid),f(this,mn,!0),f(this,gn,!1),!0}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,!1}},nu=new WeakSet,Iv=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const r={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:{...we.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)},Ic=new WeakSet,mp=async function(t,e,r,i){try{const n=x(this,au,Av).call(this);await x(this,ou,Mv).call(this,t,e,r,n),await a(this,j).setupTransports({send:!0,recv:!0}),await x(this,cu,Ov).call(this,i)}catch(n){throw this.logger.error("Failed to initialize connection",{error:n}),n}},au=new WeakSet,Av=function(){var r;const t=(r=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:r.toString(),e=WD(t);return f(this,Ka,e),e},ou=new WeakSet,Mv=async function(t,e,r,i){await eS(async(n,o)=>{if(!a(this,vt).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,j).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})},cu=new WeakSet,Ov=async function(t){if(!(!this.context.getValue("flagsmith").hasFeature(Z.PRECREATE_PRODUCERS)||!t))try{const r=[];if(t.canProduceVideo===H.Allowed&&r.push(this.shareWebcam(f1(!1))),t.canProduceAudio===H.Allowed){const i=m1(!1);i&&r.push(this.shareMic(i))}r.length>0&&await Promise.all(r)}catch(r){this.logger.warn("Failed to precreate producers",{error:r})}},ct=new WeakSet,Mt=function(t){return a(this,It).get(t)},Tn=new WeakSet,sd=function(t,e){return a(this,It).set(t,e)},du=new WeakSet,Dv=function(t){return a(this,It).delete(t)},lu=new WeakSet,Nv=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},uu=new WeakSet,Vv=function(t,e){return{track:t,codecOptions:e?e.map(r=>({name:r.split("/")[1]})):[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},ce([E.trace("MediaNodeClient.reset")],ie.prototype,"reset",1),ce([E.trace("MediaNodeClient.joinRoom")],ie.prototype,"joinRoom",1),ce([E.trace("MediaNodeClient.leaveRoom")],ie.prototype,"leaveRoom",1),ce([E.trace("MediaNodeClient.activatePeers")],ie.prototype,"activatePeers",1),ce([E.trace("MediaNodeClient.createConsumers")],ie.prototype,"createConsumers",1),ce([E.trace("MediaNodeClient.closeConsumers")],ie.prototype,"closeConsumers",1),ce([E.trace("MediaNodeClient._shareWebcam")],ie.prototype,"_shareWebcam",1),ce([E.trace("MediaNodeClient.shareWebcam")],ie.prototype,"shareWebcam",1),ce([E.trace("MediaNodeClient.shareScreen")],ie.prototype,"shareScreen",1),ce([E.trace("MediaNodeClient.shareMic")],ie.prototype,"shareMic",1),ce([E.trace("MediaNodeClient.pauseMic")],ie.prototype,"pauseMic",1),ce([E.trace("MediaNodeClient.pauseWebcam")],ie.prototype,"pauseWebcam",1),ce([E.trace("MediaNodeClient.resumeMic")],ie.prototype,"resumeMic",1),ce([E.trace("MediaNodeClient.resumeWebcam")],ie.prototype,"resumeWebcam",1),ce([E.trace("MediaNodeClient.disableWebcam")],ie.prototype,"disableWebcam",1),ce([E.trace("MediaNodeClient.disableMic")],ie.prototype,"disableMic",1),ce([E.trace("MediaNodeClient.disableScreenShare")],ie.prototype,"disableScreenShare",1),ce([E.trace("MediaNodeClient.muteSelf")],ie.prototype,"muteSelf",1),ce([E.trace("MediaNodeClient.resetVideoProducers")],ie.prototype,"resetVideoProducers",1),ce([E.trace("MediaNodeClient.changeDisplayName")],ie.prototype,"changeDisplayName",1),ce([E.trace("MediaNodeClient.kickPeer")],ie.prototype,"kick",1),ce([E.trace("MediaNodeClient.kickAllPeers")],ie.prototype,"kickAll",1),ce([E.trace("MediaNodeClient.muteAll")],ie.prototype,"muteAll",1),ce([E.trace("MediaNodeClient.muteAllVideo")],ie.prototype,"muteAllVideo",1),ce([E.trace("MediaNodeClient.disableAudio")],ie.prototype,"disableAudio",1),ce([E.trace("MediaNodeClient.disableVideo")],ie.prototype,"disableVideo",1),ce([E.trace("MediaNodeClient.pinPeer")],ie.prototype,"pinPeer",1),ce([E.trace("MediaNodeClient.validateScreenShare")],ie.prototype,"validateScreenShare",1);function oS(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 ie(s,t);return s.setValue("roomNodeClient",r),r}function cS(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 T1=Object.defineProperty,y1=Object.getOwnPropertyDescriptor,Ni=(s,t,e,r)=>{for(var i=r>1?void 0:r?y1(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&&T1(t,e,i),i};const dS=(YS=class{constructor(s,t,e,r){m(this,At);p(this,"self");p(this,"authToken");m(this,yn,void 0);p(this,"viewType");m(this,Ds,void 0);m(this,X,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,f(this,X,s),this.viewType=r,this.authToken=n,f(this,yn,i),f(this,Ds,e),this.setupEvents()}get peerId(){return a(this,X).getValue("peerId")}get telemetry(){return a(this,X).getValue("telemetry")}get logger(){return a(this,X).getValue("logger")}get mediaJoined(){return a(this,X).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const n=yt(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await Ze.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");if(navigator.product!=="ReactNative"){const u=!s.getValue("flagsmith").hasFeature(Z.PRECALL_BANDWIDTH_TEST);setTimeout(async()=>{const h=await d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(h)}),s.getValue("callstats").devices("AUDIO",h==null?void 0:h.filter(g=>g.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",h==null?void 0:h.filter(g=>g.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",h==null?void 0:h.filter(g=>g.kind==="audiooutput")),l.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:o,engineName:we.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:s.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:j_(s),skipConnectivityChecks:u}),l.info("Callstats:: initialized")}catch(g){l.error("Callstats:: initialization failed",{error:g})}},0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new dS(s,d,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===H.Allowed&&r)try{await a(this,At,es).shareMic(s),this.self.audioEnabled||a(this,At,es).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===H.Allowed&&i)try{const d=await a(this,At,es).shareWebcam(t);d&&d.id!==t.id&&a(this,X).getValue("flagsmith").hasFeature(Z.EXP_RESHARE)&&await a(this,At,es).shareWebcam(d),this.self.videoEnabled||a(this,At,es).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===H.Allowed&&n)try{await((c=a(this,At,es))==null?void 0:c.shareScreen({video:o.video,audio:o.audio}))}catch(d){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,X).getValue("callstats").callEnded(),a(this,At,es).reset(),s&&await this.joinRoom(s)}setupEvents(){a(this,X).getValue("peerSessionStore").on(_.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),a(this,X).getValue("peerSessionStore").on(_.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,X).getValue("peerSessionStore").on(_.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,X).getValue("peerSessionStore").on(_.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,X).getValue("peerSessionStore").on(_.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),a(this,X).getValue("peerSessionStore").on(_.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&a(this,X).getValue("flagsmith").hasFeature(Z.REFRESH_ID_ON_DISCONNECTION)&&(t=fi()),a(this,yn).updateURL(t),a(this,X).getValue("telemetry").resetPeerId(t),yt().setHeader("tracing-id",t),sr.remapContext(t,a(this,X)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,X).getValue("peerSessionStore").on(_.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Ds).on(U.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Ds).on(Hd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,X).getValue("peerSessionStore").emit(_.UPDATE_PERMISSIONS,t.patch)})}),a(this,Ds).on(U.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Ds).on(U.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Ds).on(U.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,X).getValue("peerSessionStore").onAsync(_.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,X).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,X).getValue("peerSessionStore").on(_.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,X).getValue("callstats").audioOff())}),a(this,X).getValue("peerSessionStore").on(_.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,X).getValue("callstats").videoOff())}),a(this,X).getValue("peerSessionStore").onAsync(_.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,X).getValue("peerSessionStore").on(_.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await a(this,Ds).joinRoom(this.self);a(this,Ds).socket.flush();const e=bh(t.stageType);if(a(this,X).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}await this.joinMediaRoom(s),a(this,X).notify("stageStatus")}catch(t){throw this.logger.error("Error in joinRoom",{error:t}),t}}async leaveRoom(s="left"){var t,e;if(this.logger.info(`Leaving room with state: ${s}`),(t=a(this,X).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),a(this,X).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,X).notify("stageStatus");try{(e=a(this,yn))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}cS(a(this,X)),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,c;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=a(this,X).getAllValues();try{if(e===tr.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}oS(a(this,X),{socket:a(this,yn),peerId:t})}const{canProduceAudio:d,canProduceVideo:l,canProduceScreenshare:u}=this.self.permissions,{roomJoined:h,error:g}=(o=await((n=a(this,At,es))==null?void 0:n.joinRoom(this.self.name,r,s,s,{canProduceAudio:d,canProduceVideo:l,canProduceScreenshare:u})))!=null?o:{};if(!h)throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:g}),g;i==="ON_STAGE"&&await this.shareMediaTracks(),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(d){throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:d}),new k(`${(c=d==null?void 0:d.message)!=null?c:"could not connect to media servers"}`,"0002")}}async leaveMediaRoom(s){const t=a(this,X).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===tr.Webinar)&&a(this,At,es)&&(a(this,At,es).mediaJoined&&s!=="disconnected"&&await a(this,At,es).leaveRoom(),!(s==="stageLeft"&&t===tr.Livestream)&&(a(this,At,es).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()}},yn=new WeakMap,Ds=new WeakMap,X=new WeakMap,At=new WeakSet,es=function(){return a(this,X).getValue("roomNodeClient")},YS);let jr=dS;Ni([E.trace("SelfController.resetSelf")],jr.prototype,"resetSelf",1),Ni([E.trace("SelfController.setupEvents")],jr.prototype,"setupEvents",1),Ni([E.trace("SelfController.joinRoom")],jr.prototype,"joinRoom",1),Ni([E.trace("SelfController.leaveRoom")],jr.prototype,"leaveRoom",1),Ni([E.trace("SelfController.joinMediaRoom")],jr.prototype,"joinMediaRoom",1),Ni([E.trace("SelfController.leaveMediaRoom")],jr.prototype,"leaveMediaRoom",1),Ni([E.trace("SelfController.init")],jr,"init",1);class E1{constructor(t){m(this,Ac,void 0);f(this,Ac,t)}on(t,e){let r;t===U.roomPeerCount?r=Xm.fromBinary.bind(Xm):r=ff.fromBinary.bind(ff),a(this,Ac).on(t,({payload:i})=>{if(t===U.roomPeerCount&&!i)return;const n=r(i);e(n)})}}Ac=new WeakMap;class b1{constructor(t,e){m(this,Mc,void 0);m(this,Oc,void 0);f(this,Mc,e),f(this,Oc,t)}get logger(){return a(this,Oc).getValue("logger")}on(t,e){let r,i;switch(t){case U.transcript:{r=ih.fromBinary.bind(ih),i=ih.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Mc).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)})}}Mc=new WeakMap,Oc=new WeakMap;var w1=Object.defineProperty,P1=Object.getOwnPropertyDescriptor,qh=(s,t,e,r)=>{for(var i=r>1?void 0:r?P1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&w1(t,e,i),i};class ol{constructor(t,e){m(this,Or,void 0);m(this,za,void 0);f(this,Or,e),f(this,za,t)}get logger(){return a(this,za).getValue("logger")}get telemetry(){return a(this,za).getValue("telemetry")}getPolls(){return a(this,Or).sendMessagePromise(ar.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Or).sendMessage(ar.createPoll,vM.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Or).sendMessage(ar.votePoll,yM.toBinary(r))}on(t,e){let r,i;switch(t){case ar.updatePoll:case ar.createPoll:case ar.votePoll:{r=Sh.fromBinary.bind(Sh),i=Sh.create();break}}a(this,Or).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,Or).removeListeners(t)}}Or=new WeakMap,za=new WeakMap,qh([E.trace("PollSocketHandler.getPolls")],ol.prototype,"getPolls",1),qh([E.trace("PollSocketHandler.createPoll")],ol.prototype,"createPoll",1),qh([E.trace("PollSocketHandler.votePoll")],ol.prototype,"votePoll",1);var _1=Object.defineProperty,R1=Object.getOwnPropertyDescriptor,C1=(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&&_1(t,e,i),i};class lS{constructor(t,e){p(this,"socket");m(this,Xt,void 0);f(this,Xt,t),this.socket=e,this.handleSocketEvents(),a(this,Xt).setValue("roomSocketHandler",this)}get telemetry(){return a(this,Xt).getValue("telemetry")}get logger(){return a(this,Xt).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}async joinRoom(t){var i;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(i=t.name)!=null?i:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise(U.joinRoom,lI.toBinary(e));try{const{peer:n}=Nn.fromBinary((await r).payload);a(this,Xt).getValue("connectionHandler").socketJoined=!0,a(this,Xt).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,Xt).getValue("peerSessionStore").emit(_.ROOM_STATE,d),a(this,Xt).getValue("peerSessionStore").emit(_.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),new k("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,n)}}async getAllAddedParticipants(){try{return KI.fromBinary((await this.socket.sendMessagePromise(U.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(U.getRoomPeersInfo,eI.toBinary(n));i=oh.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(U.getRoomPeersInfo);t=oh.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(U.getRoomPeersInfo);t=oh.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(U.getPeerInfo,tf.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=ef.create();try{const e=await this.socket.sendMessagePromise(U.getRoomInfo);t=ef.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=cf.create();try{const e=await this.socket.sendMessagePromise(U.getRoomStageState);t=cf.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(U.broadcastMessage,mo.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(U.broadcastToEntity,mo.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(U.broadcastToEntity,mo.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(U.leaveRoom,hI.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(U.kick,af.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(U.kickAll,jm.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(U.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.acceptWaitingRoomRequests,eA.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.denyWaitingRoomRequests,sA.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Hd.updateUserPreset,MA.toBinary(r))}handleSocketEvents(){this.socket.on(U.broadcastMessage,({payload:t})=>{try{const e=mo.fromBinary(t);a(this,Xt).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(U.broadcastToEntity,({payload:t})=>{try{const e=mo.fromBinary(t);a(this,Xt).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 U.joinRoom:case U.leaveRoom:case U.kick:case U.kickAll:{r=Nn.fromBinary.bind(Nn),i=Nn.create();break}case U.getWaitingRoomRequests:{r=(n,o)=>n?of.fromBinary(n,o):{requests:[]},i=of.create();break}case U.recordingPaused:case U.recordingStarted:case U.recordingStopped:{r=yf.fromBinary.bind(yf);break}case Hd.updateUserPreset:{r=lf.fromBinary.bind(lf);break}case ys.peerJoinedBroadcast:case Fr.peerJoinedBroadcast:{r=Jm.fromBinary.bind(Jm);break}case ys.selfJoinComplete:case Fr.selfJoinComplete:{r=sh.fromBinary.bind(sh);break}case ys.globalPeerPinBroadcast:case Fr.globalPeerPinBroadcast:{r=Ym.fromBinary.bind(Ym);break}case ys.selectedPeer:case Fr.selectedPeer:{r=th.fromBinary.bind(th);break}case ys.selectedPeerDiff:case Fr.selectedPeerDiff:{r=Wm.fromBinary.bind(Wm);break}case ys.leaveRoom:case Fr.leaveRoom:{r=rh.fromBinary.bind(rh);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(Hd.getUserPresets,PA.toBinary(e)),i=kA.fromBinary(r.payload).peerPresets[0],n=new TextDecoder().decode(i.preset),o=JSON.parse(n).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(r){throw this.logger.error("Error in getting user preset",{error:r}),r}}}Xt=new WeakMap,C1([E.trace("RoomSocketHandler.joinRoom")],lS.prototype,"joinRoom",1);class k1{constructor(t){m(this,Ut,void 0);f(this,Ut,t)}async getStageRequests(){const{payload:t}=await a(this,Ut).sendMessagePromise(U.getStageRequests);return t?fh.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,Ut).sendMessage(U.requestStageAccess)}cancelRequestAccess(){a(this,Ut).sendMessage(U.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,Ut).sendMessage(U.grantStageAccess,cM.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,Ut).sendMessage(U.denyStageAccess,lM.toBinary(e))}joinStage(){return a(this,Ut).sendMessagePromise(U.joinStage,void 0,void 0,U.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,Ut).sendMessagePromise(U.leaveStage,vf.toBinary(e),void 0,U.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,Ut).sendMessagePromise(U.leaveStage,vf.toBinary(e))}on(t,e){let r;switch(t){case U.grantStageAccess:case U.denyStageAccess:{r=void 0;break}case U.getStagePeers:{r=Sf.fromBinary.bind(Sf);break}case U.getStageRequests:case U.requestStageAccess:case U.cancelStageRequest:{r=fh.fromBinary.bind(fh);break}case U.peerStageStatusUpdate:{r=Qm.fromBinary.bind(Qm);break}}a(this,Ut).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,Ut).sendMessagePromise(U.getPeerInfo,tf.toBinary({peerId:t}));return Nn.fromBinary(e.payload)}}Ut=new WeakMap;class I1{constructor(t,e){m(this,Ye,void 0);m(this,Dc,void 0);f(this,Ye,e),f(this,Dc,t)}get logger(){return a(this,Dc).getValue("logger")}addPlugin(t,e){a(this,Ye).sendMessage(G.addPlugin,_0.toBinary({pluginId:t,staggered:e}))}removePlugin(t){a(this,Ye).sendMessage(G.removePlugin,C0.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await a(this,Ye).sendMessagePromise(G.getPlugins);return t?Y0.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};a(this,Ye).sendMessage(G.customPluginEventToRoom,x0.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const n={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};a(this,Ye).sendMessage(G.customPluginEventToPeers,F0.toBinary(n),i)}enablePluginForRoom(t,e){a(this,Ye).sendMessage(G.enablePluginForRoom,I0.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){a(this,Ye).sendMessage(G.enablePluginForPeers,D0.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){a(this,Ye).sendMessage(G.disablePluginForRoom,M0.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){a(this,Ye).sendMessage(G.disablePluginForPeers,V0.toBinary({pluginId:t,peerIds:e}),r)}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,Ye).sendMessage(G.storeInsertKeys,hf.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,Ye).sendMessage(G.storeGetKeys,q0.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,Ye).sendMessage(G.storeDeleteKeys,G0.toBinary(n),i)}storeDelete(t,e,r){a(this,Ye).sendMessage(G.storeDelete,J0.toBinary({pluginId:t,storeName:e}),r)}getPluginDataOld(t,e){this.logger.info("getPluginDataOld",{plugin:{id:t,storeName:e}})}storePluginDataOld(t,e,r){const i={pluginId:t,storeName:e,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};a(this,Ye).sendMessage(G.storeInsertKeys,hf.toBinary(i))}on(t,e){let r;switch(t){case G.addPlugin:case G.enablePluginForPeers:case G.enablePluginForRoom:{r=mh.fromBinary.bind(mh);break}case G.removePlugin:case G.disablePluginForPeers:case G.disablePluginForRoom:{r=pf.fromBinary.bind(pf);break}case G.customPluginEventToPeers:case G.customPluginEventToRoom:{r=mf.fromBinary.bind(mf);break}case G.storeInsertKeys:case G.storeGetKeys:case G.storeDeleteKeys:case G.storeDelete:{r=gf.fromBinary.bind(gf);break}}a(this,Ye).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}Ye=new WeakMap,Dc=new WeakMap;var A1=Object.defineProperty,M1=(s,t,e)=>t in s?A1(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,O1=(s,t,e)=>(M1(s,typeof t!="symbol"?t+"":t,e),e),jh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},O=(s,t,e)=>(jh(s,t,"read from private field"),e?e.call(s):t.get(s)),ye=(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)=>(jh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),Pe=(s,t,e)=>(jh(s,t,"access private method"),e),cl={},D1={get exports(){return cl},set exports(s){cl=s}},Hn=typeof Reflect=="object"?Reflect:null,uS=Hn&&typeof Hn.apply=="function"?Hn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},dl;Hn&&typeof Hn.ownKeys=="function"?dl=Hn.ownKeys:Object.getOwnPropertySymbols?dl=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:dl=function(s){return Object.getOwnPropertyNames(s)};function N1(s){console&&console.warn&&console.warn(s)}var hS=Number.isNaN||function(s){return s!==s};function de(){de.init.call(this)}D1.exports=de,cl.once=U1,de.EventEmitter=de,de.prototype._events=void 0,de.prototype._eventsCount=0,de.prototype._maxListeners=void 0;var pS=10;function ll(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(de,"defaultMaxListeners",{enumerable:!0,get:function(){return pS},set:function(s){if(typeof s!="number"||s<0||hS(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");pS=s}}),de.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},de.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||hS(s))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+s+".");return this._maxListeners=s,this};function gS(s){return s._maxListeners===void 0?de.defaultMaxListeners:s._maxListeners}de.prototype.getMaxListeners=function(){return gS(this)},de.prototype.emit=function(s){for(var t=[],e=1;e<arguments.length;e++)t.push(arguments[e]);var r=s==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var n;if(t.length>0&&(n=t[0]),n instanceof Error)throw n;var o=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw o.context=n,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")uS(c,this,t);else for(var d=c.length,l=TS(c,d),e=0;e<d;++e)uS(l[e],this,t);return!0};function mS(s,t,e,r){var i,n,o;if(ll(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=gS(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,N1(c)}return s}de.prototype.addListener=function(s,t){return mS(this,s,t,!1)},de.prototype.on=de.prototype.addListener,de.prototype.prependListener=function(s,t){return mS(this,s,t,!0)};function V1(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function fS(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=V1.bind(r);return i.listener=e,r.wrapFn=i,i}de.prototype.once=function(s,t){return ll(t),this.on(s,fS(this,s,t)),this},de.prototype.prependOnceListener=function(s,t){return ll(t),this.prependListener(s,fS(this,s,t)),this},de.prototype.removeListener=function(s,t){var e,r,i,n,o;if(ll(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():L1(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this},de.prototype.off=de.prototype.removeListener,de.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 SS(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?x1(i):TS(i,i.length)}de.prototype.listeners=function(s){return SS(this,s,!0)},de.prototype.rawListeners=function(s){return SS(this,s,!1)},de.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):vS.call(s,t)},de.prototype.listenerCount=vS;function vS(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}de.prototype.eventNames=function(){return this._eventsCount>0?dl(this._events):[]};function TS(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function L1(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function x1(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function U1(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,n),r(o)}function n(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}yS(s,t,n,{once:!0}),t!=="error"&&F1(s,i,{once:!0})})}function F1(s,t,e){typeof s.on=="function"&&yS(s,"error",t,e)}function yS(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(n){r.once&&s.removeEventListener(t,i),e(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class $1 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 ES=new $1;class bS{static encode(t){return ES.toBinary(t)}static decode(t){return ES.fromBinary(new Uint8Array(t))}}function B1(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Gr;class H1{constructor(t={}){O1(this,"opts"),ye(this,Gr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ne(this,Gr,0)}async wait(){ne(this,Gr,O(this,Gr)+1);const t=B1(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**O(this,Gr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return O(this,Gr)}reset(){ne(this,Gr,0)}}Gr=new WeakMap;const Wr={debug:0,info:1,warn:2,error:3};var Vi,Li;class q1{constructor(t){ye(this,Vi,void 0),ye(this,Li,void 0),ne(this,Vi,console),ne(this,Li,t)}debug(...t){Wr[O(this,Li)]>Wr.debug||O(this,Vi).debug("[Sockrates]:",...t)}info(...t){Wr[O(this,Li)]>Wr.info||O(this,Vi).info("[Sockrates]:",...t)}warn(...t){Wr[O(this,Li)]>Wr.warn||O(this,Vi).warn("[Sockrates]:",...t)}error(...t){Wr[O(this,Li)]>Wr.error||O(this,Vi).error("[Sockrates]:",...t)}}Vi=new WeakMap,Li=new WeakMap;var wS=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(wS||{});const j1="2",G1="3";var De,qn,_e,Ue,Jr,et,ur,Kr,Ps,jn,hr,Gh,PS,Co,ul,Wh,_S,Jh,RS,hl,Kh,zh,CS,ko,pl,Io,gl,ml,Yh,Gn,Ao,Mo,fl;class W1{constructor(t,e){var g,S,y,w,b,C,D,F,L,B;ye(this,Gh),ye(this,Co),ye(this,Wh),ye(this,Jh),ye(this,hl),ye(this,zh),ye(this,ko),ye(this,Io),ye(this,ml),ye(this,Gn),ye(this,Mo),ye(this,De,void 0),ye(this,qn,void 0),ye(this,_e,void 0),ye(this,Ue,void 0),ye(this,Jr,void 0),ye(this,et,void 0),ye(this,ur,void 0),ye(this,Kr,void 0),ye(this,Ps,void 0),ye(this,jn,void 0),ye(this,hr,void 0);var r,i,n,o,c,d,l,u,h;ne(this,qn,t),ne(this,Jr,[]),ne(this,et,new cl),ne(this,ur,!0),ne(this,Ps,!1),ne(this,_e,e!=null?e:{}),(g=(r=O(this,_e)).autoReconnect)!=null||(r.autoReconnect=!0),(S=(i=O(this,_e)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(y=(n=O(this,_e)).pingTimeout)!=null||(n.pingTimeout=3e4),(w=(o=O(this,_e)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(b=(c=O(this,_e)).debug)!=null||(c.debug=!0),(C=(d=O(this,_e)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(D=(l=O(this,_e)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(F=(u=O(this,_e)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(L=(h=O(this,_e)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),ne(this,Kr,{code:void 0,reason:void 0}),ne(this,Ue,(B=O(this,_e).logger)!=null?B:new q1(O(this,_e).debug?"debug":"info")),ne(this,hr,new H1)}get readyState(){var t;return(t=O(this,De))==null?void 0:t.readyState}get url(){return O(this,qn)}updateURL(t){ne(this,qn,t),Pe(this,zh,CS).call(this)}get config(){return O(this,_e)}get sendQueue(){return O(this,Jr)}flush(){if(!O(this,_e).queueOnDisconnect)return!1;const t=[];return O(this,Jr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ne(this,Jr,t),O(this,Jr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){O(this,Ue).debug("Websocket was already connecting or connected.");return}if(O(this,ur)!==!1)return new Promise((e,r)=>{Pe(this,Gn,Ao).call(this),Pe(this,Mo,fl).call(this);try{ne(this,De,new WebSocket(Pe(this,Gh,PS).call(this,O(this,qn)))),O(this,De).binaryType="arraybuffer",O(this,Ue).debug("Connecting");const i=setTimeout(()=>{O(this,Ue).debug("Connection timeout. Closing socket"),ne(this,ur,!0),Pe(this,Mo,fl).call(this),O(this,De).close(3001,"Connection Timeout"),O(this,_e).autoReconnect&&!O(this,Ps)&&(O(this,et).emit("reconnecting"),Pe(this,ko,pl).call(this)),r(new Error("Connection timed out!"))},O(this,_e).connectionTimeout);O(this,De).onopen=()=>{O(this,Ue).debug(`Ready State: ${wS[O(this,De).readyState]}`),i&&clearTimeout(i),Pe(this,ml,Yh).call(this),ne(this,Kr,{code:void 0,reason:void 0}),O(this,et).emit("connected"),O(this,_e).flushOnReconnect&&this.flush(),e()},O(this,De).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),O(this,Ue).debug("Socket closed. Close event:",{event:n}),O(this,Ue).debug(`Connection closed code: ${o}`),O(this,Ue).debug(`Connection closed reason: ${c}`),O(this,Ps)||Pe(this,hl,Kh).call(this,o,c)}catch(o){Pe(this,Co,ul).call(this,o)}},O(this,De).onerror=n=>{Pe(this,Co,ul).call(this,n)},O(this,De).onmessage=n=>Pe(this,Wh,_S).call(this,n)}catch(i){Pe(this,Co,ul).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(O(this,_e).queueOnDisconnect&&(!O(this,De)||O(this,De).readyState!==1))return O(this,Ue).debug("Queuing message since socket is not connected!",n),O(this,Jr).push(n),!1;const o=bS.encode(n);return Pe(this,Io,gl).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return Pe(this,Io,gl).call(this,t)}receive(t,e){return O(this,et).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")){O(this,et).on(t,e);return}this.receive(t,e)}removeAllListeners(){O(this,et).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){O(this,et).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){O(this,et).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ne(this,ur,!1),Pe(this,Gn,Ao).call(this),this.removeAllListeners(),ne(this,Kr,{code:1e3,reason:"Sockrates disconnect method called"}),O(this,De).close(1e3,"Sockrates disconnect method called.")}}De=new WeakMap,qn=new WeakMap,_e=new WeakMap,Ue=new WeakMap,Jr=new WeakMap,et=new WeakMap,ur=new WeakMap,Kr=new WeakMap,Ps=new WeakMap,jn=new WeakMap,hr=new WeakMap,Gh=new WeakSet,PS=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)://.")},Co=new WeakSet,ul=function(s,t){O(this,Ue).error("Error:",{error:s}),O(this,et).emit("errored",{error:s}),t==null||t(s)},Wh=new WeakSet,_S=function(s){if(Pe(this,ml,Yh).call(this),s.data===j1){O(this,Ue).debug("Received ping from server"),Pe(this,Io,gl).call(this,G1);return}const t=bS.decode(s.data),{id:e,payload:r}=t;O(this,Ue).debug("Received message",{event:t.event,messageID:e}),O(this,et).emit(t.event.toString(),{id:e,payload:r})},Jh=new WeakSet,RS=function(){return O(this,De).readyState===1},hl=new WeakSet,Kh=function(s,t){ne(this,Kr,{reason:t,code:s}),O(this,et).emit("disconnected",{code:s,reason:t})},zh=new WeakSet,CS=function(){const{reason:s,code:t}=O(this,Kr);t&&t!==1e3&&O(this,ur)&&O(this,_e).autoReconnect&&!O(this,Ps)&&(O(this,Ue).debug(`Triggering reconnection due to ${s}.`),O(this,et).emit("reconnecting"),Pe(this,ko,pl).call(this))},ko=new WeakSet,pl=async function(s=!0){if(s&&O(this,Ps)){O(this,Ue).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(O(this,Ps)||O(this,hr).reset(),O(this,_e).maxReconnectionAttempts!==null&&O(this,hr).getAttempts()>=O(this,_e).maxReconnectionAttempts){O(this,et).emit("failed"),ne(this,Ps,!1);return}ne(this,Ps,!0),Pe(this,Mo,fl).call(this),Pe(this,Gn,Ao).call(this);try{if(await O(this,hr).wait(),O(this,ur)===!1)return;if(O(this,Ue).debug(`Reconnection attempt ${O(this,hr).getAttempts()}`),O(this,et).emit("reconnectAttempt",{attempt:O(this,hr).getAttempts()}),await this.connect(),!Pe(this,Jh,RS).call(this))throw Error("Reconnect Failed");ne(this,Ps,!1),ne(this,Kr,{code:void 0,reason:void 0}),O(this,et).emit("reconnected")}catch(t){O(this,Ue).debug("Failed to reconnect."),O(this,et).emit("reconnectFailure",{attempt:O(this,hr).getAttempts()}),Pe(this,ko,pl).call(this,!1)}},Io=new WeakSet,gl=function(s){try{return O(this,De).send(s),!0}catch(t){return O(this,Ue).error(t.message),!1}},ml=new WeakSet,Yh=function(){this.config.disconnectOnPingTimeout&&(O(this,Ue).debug("Resetting ping timeout"),Pe(this,Gn,Ao).call(this),ne(this,jn,setTimeout(()=>{var s;O(this,Ue).debug("Disconnecting the socket due to ping timeout"),ne(this,ur,!0);const t=3002,e="Ping timeout";(s=O(this,De))==null||s.close(t,e),Pe(this,hl,Kh).call(this,t,e)},O(this,_e).pingTimeout)))},Gn=new WeakSet,Ao=function(){O(this,jn)&&(clearTimeout(O(this,jn)),ne(this,jn,void 0))},Mo=new WeakSet,fl=function(){O(this,De)&&(O(this,De).onopen=void 0,O(this,De).onerror=void 0,O(this,De).onmessage=void 0,O(this,De).onclose=void 0)};var J1=Object.defineProperty,K1=Object.getOwnPropertyDescriptor,Sl=(s,t,e,r)=>{for(var i=r>1?void 0:r?K1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&J1(t,e,i),i};const kS=65535,z1=3e3,IS=(QS=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){m(this,Me);m(this,Nc);m(this,Vc);m(this,pi,void 0);m(this,Ae,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");m(this,ms,void 0);m(this,it,void 0);var n;if(!t||!e||!r)throw new k("peerId, meetingId, or authToken can not be empty","0404");f(this,ms,void 0),f(this,it,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,pi,x(this,Nc,fp).call(this,t)),f(this,Ae,new W1(a(this,pi),{autoReconnect:!0,disconnectOnPingTimeout:(n=i.includes("PING"))!=null?n:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Me,je).socketJoinAttempted}set joinAttempted(s){a(this,Me,je).socketJoinAttempted=s}get telemetry(){return a(this,it).getValue("telemetry")}get logger(){return a(this,it).getValue("logger")}get peerId(){return a(this,it).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,pi,x(this,Nc,fp).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Ae).updateURL(a(this,pi))}static getSocketEdgeDomain(s){return bi({servicePrefix:"socket-edge",baseURI:s})}get url(){return a(this,pi)}async connect(){a(this,Me,je).socketJoinAttempted=!0,await a(this,Ae).connect(),a(this,Me,je).socketJoinAttempted=!0,a(this,Me,je).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){a(this,Me,je).socketJoinAttempted=!1,a(this,Ae).disconnect(),a(this,Me,je).socketJoinAttempted=!0,a(this,Me,je).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Ae).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return a(this,it).getValue("telemetry").injectContext(r),a(this,Ae).send(s,e!=null?e:x(this,Vc,Sp).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}){const n=i!=null?i:s;return new Promise((o,c)=>{const d=(y,w)=>{a(this,Ae).removeListener(n,y),a(this,Ae).removeListener(kS,w),a(this,Ae).removeListener(Fr.errorResponse,w),a(this,Ae).removeListener(ys.errorResponse,w)},l=r!=null?r:x(this,Vc,Sp).call(this),u={};a(this,it).getValue("telemetry").injectContext(u);const g=({id:y,payload:w})=>{if(l===y){let b;try{const C=WC.fromBinary(w);b=new Error(C.errorMessage)}catch(C){b=new Error("failed to parse error message",{cause:C});try{const D=Jk.fromBinary(w);b=new Error(D.message)}catch(D){b=new Error("failed to parse error message",{cause:D})}}c(b),d(S,g)}},S=({id:y,payload:w})=>{l===y&&(o({id:y,payload:w}),d(S,g))};a(this,Ae).on(n,S),a(this,Ae).on(kS,g),a(this,Ae).on(Fr.errorResponse,g),a(this,Ae).on(ys.errorResponse,g),setTimeout(()=>{d(S,g),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Ae).send(s,l,e,new TextEncoder().encode(JSON.stringify(u)))})}on(s,t){a(this,Ae).on(s,t)}onStateEvent(s,t){a(this,Ae).on(s,t)}removeListener(s,t){a(this,Ae).removeListener(s,t)}removeListeners(s){a(this,Ae).removeListeners(s)}flush(){return a(this,Ae).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),a(this,ms)&&(clearTimeout(a(this,ms)),f(this,ms,void 0)),a(this,Me,je).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t}});const{recv:e,send:r}=(i=a(this,Me,je).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==Bn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Bn.CONNECTED?a(this,it).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Me,je).joinAttempted}):f(this,ms,setTimeout(()=>{a(this,it).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Me,je).joinAttempted}),f(this,ms,void 0)},z1)),a(this,Me,je).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge"),a(this,Me,je).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),a(this,Me,je).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),a(this,Me,je).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Me,je).mediaJoinAttempted}}),a(this,ms)&&(clearTimeout(a(this,ms)),f(this,ms,void 0)),a(this,it).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Me,je).mediaJoinAttempted}),a(this,Me,je).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge"),a(this,it).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_FAILED),a(this,Me,je).updateSocketConnectionState("failed")})}},pi=new WeakMap,Ae=new WeakMap,Me=new WeakSet,je=function(){return a(this,it).getValue("connectionHandler")},ms=new WeakMap,it=new WeakMap,Nc=new WeakSet,fp=function(s){const t=a(this,it).getValue("socketBaseURI")||a(this,it).getValue("baseURI");let e=IS.getSocketEdgeDomain(t);typeof On(a(this,it),"socket_server_base")=="string"&&(e=On(a(this,it),"socket_server_base"));const r=`wss://${e}`,i=new URL(`${r}/ws`),n=this.peerId,o={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...n!==s&&{oldPeerID:n},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(c=>xd[c]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(o).forEach(([c,d])=>{i.searchParams.append(c,d.toString())}),i.href},Vc=new WeakSet,Sp=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},QS);let Oo=IS;Sl([E.trace("SocketService.connect")],Oo.prototype,"connect",1),Sl([E.trace("SocketService.disconnect")],Oo.prototype,"disconnect",1),Sl([E.trace("SocketService.sendMessagePromise")],Oo.prototype,"sendMessagePromise",1),Sl([E.trace("SocketService.sendMessagePromiseWithTimeout")],Oo.prototype,"sendMessagePromiseWithTimeout",1);class Y1{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=yI.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=WI.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=nf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return rf.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return LI.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(U.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(U.createConnectedRooms,PI.toBinary({payloads:t}));return rf.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(U.deleteConnectedRooms,NI.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(U.movePeers,HI.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 Q1=Object.defineProperty,X1=Object.getOwnPropertyDescriptor,Z1=(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&&Q1(t,e,i),i};class AS extends $t{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);m(this,Ns,void 0);f(this,Ns,e)}get supportsConnectedMeetings(){return a(this,Ns).getValue("self").id!==""}get isActive(){return this.meetings.length!==0}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
|
|
19
|
+
Please connect with our support team to enable connected meetings.`)}async getConnectedMeetings(){this.validateConnectedMeetingsAction(),this.logger.info("Getting connected meetings dump");const e=await a(this,Ns).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await a(this,Ns).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.validateConnectedMeetingsAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),await a(this,Ns).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.validateConnectedMeetingsAction(),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,Ns).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,Ns).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.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,Ns).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})}}Ns=new WeakMap,Z1([Ot({maxInvocations:60,period:60})],AS.prototype,"getConnectedMeetings",1);var eN=Object.defineProperty,tN=Object.getOwnPropertyDescriptor,Qh=(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};const MS=(XS=class{constructor(s){p(this,"connectedMeetings");m(this,Se,void 0);f(this,Se,s),this.connectedMeetings=new AS(s)}get telemetry(){return a(this,Se).getValue("telemetry")}get logger(){return a(this,Se).getValue("logger")}static init(s){const t=new MS(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(U.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(U.transferPeer,this.handleTransferPeer.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(U.movedPeer,this.handleMovedPeer.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(U.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(U.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.logger.info(`Honoring request to switch connected meetings. Going to ${t==null?void 0:t.meetingId}`),this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){var i,n,o,c;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
|
|
20
|
+
Please connect with our support team to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:a(this,Se).getValue("self").videoEnabled,audio:a(this,Se).getValue("self").audioEnabled};try{a(this,Se).getValue("self").cleanupEvents(),await a(this,Se).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,Se).getValue("meeting"))==null?void 0:i.meta)==null?void 0:n.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await DS.init({...a(this,Se).getValue("options"),cachedUserDetails:null,defaults:{...a(this,Se).getValue("options").defaults,...e,mediaHandler:a(this,Se).getValue("self")},authToken:s});this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(o=r==null?void 0:r.meta)==null?void 0:o.meetingId}`);try{const{hidden:d}=a(this,Se).getValue("self");r.self.setName(a(this,Se).getValue("self").name),await r.join(),d&&r.self.hide()}catch(d){this.logger.error("ConnectedMeetingsController.joinRoom",{error:d})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(c=r==null?void 0:r.meta)==null?void 0:c.meetingId}`),this.connectedMeetings.emit("meetingChanged",r),r}handleConnectedRoomsDump(s){const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(s);this.connectedMeetings.meetings=t.meetings.map(e=>({id:e.id,title:e.title,participants:e.participants||[]})),this.connectedMeetings.parentMeeting={id:t.parentMeeting.id,title:t.parentMeeting.title,participants:t.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(s){return a(this,Se).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=a(this,Se).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,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(s).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},Se=new WeakMap,XS);let vl=MS;Qh([E.trace("ConnectedMeetingsController.getConnectedMeetings")],vl.prototype,"getConnectedMeetings",1),Qh([E.trace("ConnectedMeetingsController.setupEvents")],vl.prototype,"setupEvents",1),Qh([E.trace("ConnectedMeetingsController.switchMeeting")],vl.prototype,"switchMeeting",1);var sN=Object.defineProperty,rN=Object.getOwnPropertyDescriptor,Tl=(s,t,e,r)=>{for(var i=r>1?void 0:r?rN(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&&sN(t,e,i),i};const Wn=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 L,B,Q;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(cS(s),we.isSupported()===!1)throw new k("Browser not supported","0010",c,!0);const d=zM(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 AO(s);s.setValue("connectionHandler",l);let u="",h="",g=null;c.info("CF SFU is being used.");try{g=await d.getUserDetails(),u=((L=g.meeting)==null?void 0:L.title)||"",h=((B=g.socket)==null?void 0:B.baseUri)||s.getValue("baseURI"),s.setValue("presetName",g.preset.name),s.setValue("socketBaseURI",h),c.info(`Socket Base URI ${h} is being used`)}catch(se){throw c.error("Failed to get user details",{error:se}),new k("SDK initialization failed: /participant-details API request failed","0001")}const S=Wn.createSocketService(s),y=S.connect(),w=d.getPlugins();try{await Wn.setupFlagsmith(s)}catch(se){c.error("Failed to setup flagsmith",{error:se})}try{await y}catch(se){c.error("[Controller]: Failed to connect to socket server:",{error:se})}const b=Ah.init(g.preset,!s.getValue("modules").theme);s.setValue("theme",b);const C=Oh.init(s,b.viewType,g.preset.permissions),D=Wn.setupControllers(S,s,g,w,u,b,C);TO(b)&&((Q=Wn.createRoomNodeClient(s,S).initializeConnection(g.participant.name,i,!1,C))==null||Q.catch(nt=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:nt})}));const{controllers:F}=await D;return eR(),new Wn(e,F,s)}static async setupFlagsmith(s){var l;const{peerId:t,baseURI:e,overrides:r,meetingId:i,organizationId:n,logger:o}=s.getAllValues(),c=Z_(i),d={entity:Ju.PEER,clientId:n,isAnonUser:!n,sdkVersion:s.getValue("sdkVersion"),presetName:s.getValue("presetName"),meetingHash:c,roomName:i,...we.getDeviceInfo(),isReactNative:navigator.isReactNative};try{const u=(l=r==null?void 0:r.whitelabelled_flags_endpoint)==null||l?bi({servicePrefix:"flags",baseURI:e}):"edge.api.flagsmith.com";await s.getValue("flagsmith").identify(`${Ju.PEER}_${t}`,JSON.parse(JSON.stringify(d)),!1,5e3,u,o),o.info("flagsmith::allFlags",{flags:JSON.stringify(s.getValue("flagsmith").getAllFlags())},!0)}catch(u){o.error("Failed to fetch flagsmith flags")}}static async setupControllers(s,t,e,r,i,n,o){var V,R,Je;const c=t.getValue("modules"),{participant:d}=e,l=t.getValue("defaults"),u=t.getValue("logger"),{viewType:h,mediaConstraints:{audio:g}}=n;t.setValue("viewType",h),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(V=g.enableHighBitrate)!=null?V:!1,enableStereo:(R=g.enableStereo)!=null?R:!1}},...l}),t.setValue("maxPreferredStreams",we.isMobile()?n.maxVideoStreams.mobile:n.maxVideoStreams.desktop);let S,y,w,b,C,D,F,L,B;const Q=new b1(t,s),se=new Y1(s);t.setValue("connectedMeetingsSocketHandler",se);const nt=new ol(t,s),Vs=new or(t,s),_n=new k1(s),Ls=new lS(t,s),I=new I1(t,s),T=new E1(s),P=await jr.init(t,Ls,d,o,n);t.setValue("selfController",P);const $=await If.init(t,P.self,Ls,Q,i);if(c.participant&&(L=new lr(t,P.self,Ls)),(Je=c.e2ee)!=null&&Je.enabled&&c.e2ee.manager.init(u,t.getValue("peerSessionStore")),c.chat&&(y=await is.init(t,Vs,P.self,L.participants)),c.internals&&(C=await _h.init(t)),c.livestream&&n.viewType===tr.Livestream&&t.getValue("flagsmith").hasFeature(Z.LIVESTREAM)&&(F=new zf(t,P.self,T)),c.poll&&(S=await _f.init(t,P.self,nt)),c.recording&&(D=new Nf(t,P.self,Ls)),c.stage&&(w=new Af(t,_n,Ls,P.self,L.participants)),c.plugin){if(!L)throw new k("The plugin module cannot be initialized without the `participant` module","0102");const Dr=await r;b=await vo.init(t,Dr,I,Vs,y==null?void 0:y.chat,P.self,L.participants,i)}if(c.connectedMeetings&&(B=await vl.init(t)),c.pip){const Dr=await Ku._init(t,P.self);t.setValue("pip",Dr)}const qe={storesManager:new kD(t,I),pollController:S,selfController:P,metaController:$,chatController:y,stageController:w,pluginController:b,recordingController:D,internalsController:C,livestreamController:F,participantController:L,connectedMeetingsController:B};return{theme:n,permissions:o,controllers:qe}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return oS(s,{socket:t,peerId:e})}static createSocketService(s){var d;const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),o=((d=s.getValue("socketBaseURI"))!=null?d:"").includes("realtime.cloudflare.com")?[]:["PING"];return s.getValue("logger").info(`Socket service capabilities: ${JSON.stringify(o)}`),new Oo(s,{peerId:t,meetingId:e,authToken:r,capabilities:o})}};let Do=Wn;Tl([E.trace("Controller.init")],Do,"init",1),Tl([E.trace("setupFlagsmith")],Do,"setupFlagsmith",1),Tl([E.trace("Controller.createRoomNodeClient")],Do,"createRoomNodeClient",1),Tl([E.trace("Controller.createSocketService")],Do,"createSocketService",1);class iN{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 OS=new iN;function nN(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=wi.baseURI.prod;t&&(n=t);const o=`https://${bi({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new k("Invalid auth token","0004")}}class aN{constructor(){m(this,hu);m(this,gi,new Audio);m(this,En,new MediaStream);m(this,bn,new Map);m(this,Lc,void 0);a(this,gi).srcObject=a(this,En),a(this,gi).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,gi).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,gi).srcObject=a(this,En),a(this,gi).play().catch(t=>{x(this,hu,Lv).call(this,t)})}onError(t){f(this,Lc,t)}}gi=new WeakMap,En=new WeakMap,bn=new WeakMap,Lc=new WeakMap,hu=new WeakSet,Lv=function(t){var e;(e=a(this,Lc))==null||e.call(this,t)};class oN extends aN{constructor(){super();m(this,wn,void 0);f(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 cN=Object.defineProperty,dN=Object.getOwnPropertyDescriptor,yl=(s,t,e,r)=>{for(var i=r>1?void 0:r?dN(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&&cN(t,e,i),i};let zr=(ZS=class{constructor(t,e){m(this,Qe,void 0);m(this,Pn,void 0);f(this,Pn,t),f(this,Qe,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:fi(),n=sr.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new Xf(n,o);return await c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var g,S,y,w,b,C,D;we.init();const e=(S=(g=t==null?void 0:t.cachedUserDetails)==null?void 0:g.peerId)!=null?S:fi(),{authToken:r,baseURI:i}=t,{meetingId:n,...o}=nN(r,i);if((y=o.baseURI)!=null&&y.includes("dyte.io"))throw new k("Dyte Base URIs are no longer supported. Please use RealtimeKit Base URIs. Eg: realtime.cloudflare.com","0001");window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=zr.setupContext(e,t,n,o),d=c.getValue("telemetry"),l=c.getValue("logger");$v(l),OS.init(l),d.init(c,{roomName:n,userId:o.participantId,organizationId:o.orgId,peerId:e},(b=(w=t.modules)==null?void 0:w.tracing)!=null?b:!0),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(C=t.authToken)==null?void 0:C.slice(0,10)}...
|
|
21
|
+
${(D=t.authToken)==null?void 0:D.slice(-10)}`}});const u=await Do.init(c),h=new zr(c,u);return c.setValue("meeting",h),h}static setupContext(t,e,r,i){var d,l;const n=sr.createContext(t,e),o={...H_,...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",q_({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Hs(e.cachedUserDetails)),n.setValue("sdkVersion","1.4.0-staging.1"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new oN),n}async join(){const{selfController:t}=a(this,Qe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){OS.cleanup(),a(this,Pn).getValue("peerSessionStore").reset();const{selfController:e}=a(this,Qe);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,Qe).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,Qe).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,Qe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,Qe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,Qe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,Qe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,Qe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Qe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,Qe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,Qe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,Qe).stageController)==null?void 0:t.stage}get stores(){return a(this,Qe).storesManager}get audio(){return a(this,Pn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,Qe).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},Qe=new WeakMap,Pn=new WeakMap,ZS);yl([ut("0002"),cr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],zr.prototype,"join",1),yl([ut("0003")],zr.prototype,"leave",1),yl([ut("0001"),cr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],zr,"init",1),zr=yl([ut("0000")],zr);const DS=zr;return DS}();
|